예제 #1
0
        public static IServiceCollection AddJwtService(this IServiceCollection services, IConfigurationSection jwtConfigArray)
        {
            JwtService            jwtService  = new JwtService();
            AuthenticationBuilder authBuilder = services.AddAuthentication();

            foreach (IConfigurationSection jwtConfigSection in jwtConfigArray.GetChildren())
            {
                string           name = jwtConfigSection["Name"];
                string           signingSecurityKey = jwtConfigSection["SigningSecurityKey"];
                string           issuer             = jwtConfigSection["Issuer"];
                string           audience           = jwtConfigSection["Audience"];
                int              tokenLifeTimeHours = Convert.ToInt32(jwtConfigSection["TokenLifeTimeHours"]);
                JwtConfiguration jwtConfiguration   = new JwtConfiguration(name, signingSecurityKey, issuer, audience, tokenLifeTimeHours);
                jwtService.AddConfiguration(jwtConfiguration);
                authBuilder.AddJwtBearer(name, jwtBearerOptions => {
                    jwtBearerOptions.TokenValidationParameters = new TokenValidationParameters {
                        ValidateIssuerSigningKey = true,
                        IssuerSigningKey         = jwtService.GetSecretKey(name),
                        ValidateIssuer           = true,
                        ValidIssuer      = issuer,
                        ValidateAudience = true,
                        ValidAudience    = audience,
                        ValidateLifetime = tokenLifeTimeHours > 0,
                        ClockSkew        = TimeSpan.FromMinutes(5)
                    };
                });
            }
            services.AddSingleton <IJwtService>(jwtService);
            return(services);
        }
예제 #2
0
        public string GenerateToken(string configName, Claim[] claims)
        {
            JwtConfiguration   config             = Configs[configName];
            SigningCredentials signingCredentials = new SigningCredentials(config.SecretKey, SIGNING_ALGORITHM);
            JwtSecurityToken   token = new JwtSecurityToken(
                config.Issuer,
                config.Audience,
                claims,
                DateTime.Now,
                DateTime.Now.AddHours(config.TokenLifeTimeHours),
                signingCredentials
                );

            return(new JwtSecurityTokenHandler().WriteToken(token));
        }
예제 #3
0
 public void AddConfiguration(JwtConfiguration jwtConfiguration)
 {
     Configs.Add(jwtConfiguration.Name, jwtConfiguration);
 }