public static AuthenticationBuilder AddJwtAuthentication(this IServiceCollection services,
                                                                 IConfiguration configuration)
        {
            var tokenConfig = new JwtTokenOptions();

            configuration.GetSection("JwtTokenOptions").Bind(tokenConfig);

            var tokenParameters = new TokenValidationParameters
            {
                ValidateActor            = true,
                ValidateAudience         = true,
                ValidateLifetime         = true,
                SaveSigninToken          = false,
                ValidateIssuerSigningKey = true,
                RequireExpirationTime    = true,
                ValidateIssuer           = true,
                ValidIssuer      = tokenConfig.Issuer,
                ClockSkew        = tokenConfig.Expiretion,
                ValidAudience    = tokenConfig.Audience,
                IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("hello!@3#49659asfasdf"))
            };

            var authBuilder = services
                              .AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
                              .AddJwtBearer(options =>
            {
                options.SaveToken                 = false;
                options.RequireHttpsMetadata      = false;
                options.ClaimsIssuer              = tokenConfig.Issuer;
                options.TokenValidationParameters = tokenParameters;

                options.Events = new JwtBearerEvents
                {
                    OnMessageReceived = ctx =>
                    {
                        if (ctx.HttpContext.Request.Query.TryGetValue("authorization", out var authValues) &&
                            authValues.Any())
                        {
                            ctx.Token = authValues[0];

                            const string bearerPrefix = "Bearer ";
                            if (ctx.Token.StartsWith(bearerPrefix, StringComparison.OrdinalIgnoreCase))
                            {
                                ctx.Token = ctx.Token.Substring(bearerPrefix.Length);
                            }
                        }

                        return(Task.CompletedTask);
                    }
                };
            });

            return(authBuilder);
        }
Exemplo n.º 2
0
 public JwtTokenGenerator(IOptions <JwtTokenOptions> options)
 {
     _options = options.Value;
 }