コード例 #1
0
        public static void AddAuth(this IServiceCollection services)
        {
            services.AddAuthorization();
            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(options =>
            {
                options.SaveToken                 = true;
                options.RequireHttpsMetadata      = false;
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer   = false,
                    ValidateAudience = false,

                    IssuerSigningKey         = TimetrackerAuthorizationOptions.GetSymmetricSecurityKey(),
                    ValidateIssuerSigningKey = true,

                    ClockSkew = TimeSpan.Zero
                };
                options.Events = new JwtBearerEvents
                {
                    OnTokenValidated = ctx =>
                    {
                        var now  = DateTime.UtcNow;
                        var path = ctx.HttpContext.Request.Path;

                        if (now > ctx.SecurityToken.ValidTo && !path.StartsWithSegments("/trackingHub"))
                        {
                            ctx.Fail("Token expired");
                        }
                        return(Task.CompletedTask);
                    },
                    OnMessageReceived = context =>
                    {
                        var accessToken = context.Request.Query["access_token"];
                        var path        = context.HttpContext.Request.Path;
                        if (!string.IsNullOrEmpty(accessToken) && path.StartsWithSegments("/trackingHub"))
                        {
                            context.Token = accessToken;
                        }
                        return(Task.CompletedTask);
                    }
                };
            });
        }
コード例 #2
0
        public static async Task GenerateToken(string id, Token user, TimetrackerContext context, bool isNew = false)
        {
            var claims = new List <Claim>
            {
                new Claim(ClaimsIdentity.DefaultNameClaimType, id)
            };

            var claimsIdentity = new ClaimsIdentity(claims, "Token",
                                                    ClaimsIdentity.DefaultNameClaimType, ClaimsIdentity.DefaultRoleClaimType);

            var now       = DateTime.UtcNow;
            var expiredIn = now.Add(tokenDurability);
            var jwt       = new JwtSecurityToken(
                issuer: TimetrackerAuthorizationOptions.ISSUER,
                audience: TimetrackerAuthorizationOptions.AUDIENCE,
                notBefore: now,
                claims: claimsIdentity.Claims,
                expires: expiredIn,
                signingCredentials: new SigningCredentials(
                    TimetrackerAuthorizationOptions.GetSymmetricSecurityKey(),
                    SecurityAlgorithms.HmacSha256)
                );

            var access_token  = new JwtSecurityTokenHandler().WriteToken(jwt);
            var refresh_token = Guid.NewGuid().ToString().Replace("-", "");

            user.AccessToken      = access_token;
            user.RefreshToken     = refresh_token;
            user.TokenExpiredDate = expiredIn;

            if (isNew)
            {
                await context.AddAsync(user)
                .ConfigureAwait(false);
            }

            await context.SaveChangesAsync(true)
            .ConfigureAwait(false);
        }