/// <summary>
        /// Configure Authentication and JwtBearer extensions
        /// </summary>
        /// <param name="services"></param>
        /// <param name="jwtTokenParameters"></param>
        /// <param name="authSetup"></param>
        /// <param name="jwtSetup"></param>
        public static void AddJwtAuthentication(this IServiceCollection services, JwtTokenParameters jwtTokenParameters, Action <AuthenticationOptions> authSetup, Action <JwtBearerOptions> jwtSetup = null)
        {
            services.AddScoped(s => new JwtTokenManager(jwtTokenParameters));
            services.AddAuthentication(o =>
            {
                o.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                o.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
                o.DefaultSignInScheme       = JwtBearerDefaults.AuthenticationScheme;
                authSetup?.Invoke(o);
            })
            .AddJwtBearer(options =>
            {
                options.Audience     = jwtTokenParameters.Audience;
                options.ClaimsIssuer = jwtTokenParameters.Issuer;
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidIssuer              = jwtTokenParameters.Issuer,
                    ValidAudience            = jwtTokenParameters.Audience,
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey         = jwtTokenParameters.GetSymetricSecurityKey(),
                    ValidateLifetime         = true,
                };
                options.Events = new JwtBearerEvents
                {
                    OnTokenValidated = context =>
                    {
                        // Add the access_token as a claim, as we may actually need it
                        if (context.SecurityToken is JwtSecurityToken token && jwtTokenParameters.SendNewKeyInEveryResponse)
                        {
                            var manager  = new JwtTokenManager(jwtTokenParameters);
                            var newToken = manager.CreateNewToken(token.Claims);
                            context.Response.Headers.Add("tokenValue", newToken.Value);
                            context.Response.Headers.Add("tokenExpiration", newToken.Expiration.ToString("s") + "Z");
                        }
                        return(Task.CompletedTask);
                    }
                };

                jwtSetup?.Invoke(options);
            });
        }
예제 #2
0
        private Token CreateToken(User user)
        {
            var roles = user.UserRoles.Select(ur => ur.Role).ToList();

            return(_tokenManager.CreateNewToken(user.Id, roles));
        }