コード例 #1
0
        public AuthViewModel GenerateAccessToken(TokenDataViewModel tokenData)
        {
            var claims  = GetUserClaims(tokenData);
            var now     = DateTime.UtcNow;
            var expires = now.Add(TimeSpan.FromDays(TokenOptions.LIFETIME));
            var jwt     = new JwtSecurityToken(
                issuer: TokenOptions.ISSUER,
                audience: TokenOptions.AUDIENCE,
                notBefore: now,
                claims: claims,
                expires: expires,
                signingCredentials: new SigningCredentials(TokenOptions.GetSymmetricSecurityKey(), SecurityAlgorithms.HmacSha256));
            var token = new JwtSecurityTokenHandler().WriteToken(jwt);

            return(new AuthViewModel
            {
                Token = new TokenViewModel
                {
                    Token = token,
                    Type = "bearer",
                    ExpiredAt = expires,
                    Claims = claims.Select(x => new ClaimViewModel
                    {
                        Type = x.Type,
                        Value = x.Value
                    }).ToList()
                }
            });
        }
コード例 #2
0
 /// <summary>
 /// Invoked to configure a TOptions instance.
 /// </summary>
 /// <param name="name">The name of the options instance being configured.</param>
 /// <param name="options">The options instance to configure.</param>
 public void Configure(string name, JwtBearerOptions options)
 {
     options.TokenValidationParameters = new TokenValidationParameters
     {
         ValidAudience    = _jwtOptions.Audience,
         ValidIssuer      = _jwtOptions.Issuer,
         IssuerSigningKey = _jwtOptions.GetSymmetricSecurityKey()
     };
 }
コード例 #3
0
        public string GenerateToken(User _user)
        {
            var claims = new List <Claim> {
                new Claim(ClaimTypes.Email, _user.Email),
                new Claim(ClaimTypes.Hash, _user.HashPassword),
                new Claim(ClaimTypes.Role, _user.RoleOfUser.ToString()),
                new Claim(JwtRegisteredClaimNames.Sub, _user.UserId.ToString())
            };
            var jwt = new JwtSecurityToken(
                issuer: TokenOptions.ISSUER,
                audience: TokenOptions.AUDIENCE,
                claims: claims,
                expires: DateTime.UtcNow.AddMinutes(TokenOptions.LIFETIME),
                signingCredentials: new SigningCredentials(TokenOptions.GetSymmetricSecurityKey(), SecurityAlgorithms.HmacSha256));
            var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt);

            return(encodedJwt);
        }
コード例 #4
0
 public static IServiceCollection AddJwtAuthentication(this IServiceCollection services)
 {
     services.AddAuthentication(x =>
     {
         x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
         x.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
     })
     .AddJwtBearer(options =>
     {
         options.RequireHttpsMetadata      = true;
         options.TokenValidationParameters = new TokenValidationParameters
         {
             NameClaimType            = "Roles",
             ValidateIssuer           = true,
             ValidIssuer              = TokenOptions.ISSUER,
             ValidAudience            = TokenOptions.AUDIENCE,
             ValidateLifetime         = true,
             IssuerSigningKey         = TokenOptions.GetSymmetricSecurityKey(),
             ValidateIssuerSigningKey = true
         };
     });
     return(services);
 }
コード例 #5
0
        /// <summary>
        /// Регистрировать аутентификацию
        /// </summary>
        /// <param name="services"></param>
        /// <param name="configuration"></param>
        /// <returns></returns>
        public static IServiceCollection RegisterAuth(this IServiceCollection services,
                                                      IConfiguration configuration)
        {
            var tokenOptions = new TokenOptions();

            configuration.GetSection("TokenOptions").Bind(tokenOptions);

            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(op =>
            {
                op.RequireHttpsMetadata = false;

                op.TokenValidationParameters = new TokenValidationParameters
                {
                    // Валидация издателя
                    ValidateIssuer = true,
                    // строка, представляющая издателя
                    ValidIssuer = tokenOptions.Issuer,

                    // Валидация потребителя токена
                    ValidateAudience = true,
                    // установка потребителя токена
                    ValidAudience = tokenOptions.Audience,

                    // Валидация время жизни токена
                    ValidateLifetime = true,

                    // Установка ключа безопасности
                    IssuerSigningKey = tokenOptions.GetSymmetricSecurityKey(),
                    // Валидация ключа безопасности
                    ValidateIssuerSigningKey = true
                };
            });

            return(services);
        }
コード例 #6
0
 public static SigningCredentials GetSigningCredentials(this TokenOptions options) => new SigningCredentials(options.GetSymmetricSecurityKey(), SecurityAlgorithms.HmacSha256);