Ejemplo n.º 1
0
        public static void ConfigureAUTH(this IServiceCollection services, IConfiguration configuration)
        {
            JwtSettings jwtSettings = new JwtSettings();

            configuration.GetSection("JwtSettings").Bind(jwtSettings);

            services
            .AddAuthentication(options =>
            {
                options.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultSignInScheme       = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(configuration =>
            {
                configuration.RequireHttpsMetadata      = false;
                configuration.SaveToken                 = true;
                configuration.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidIssuer              = jwtSettings.Issuer,   // site that makes the token
                    ValidateIssuer           = true,                 // TODO: change this to avoid forwarding attacks
                    ValidAudience            = jwtSettings.Audience, // site that consumes the token
                    ValidateAudience         = true,                 // TODO: change this to avoid forwarding attacks
                    IssuerSigningKey         = new SymmetricSecurityKey(TokenStoreSecurityService.GetSha256Hash(jwtSettings.Key)),
                    ValidateIssuerSigningKey = true,                 // verify signature to avoid tampering
                    ValidateLifetime         = true,                 // validate the expiration
                    ClockSkew = TimeSpan.Zero                        // tolerance for the expiration date
                };
                configuration.Events = new JwtBearerEvents
                {
                    OnAuthenticationFailed = context =>
                    {
                        var logger = context.HttpContext.RequestServices.GetRequiredService <ILoggerFactory>().CreateLogger(nameof(JwtBearerEvents));
                        logger.LogError("Authentication failed.", context.Exception);
                        return(Task.CompletedTask);
                    },
                    OnTokenValidated = context =>
                    {
                        ITokenValidatorService tokenValidatorService = context.HttpContext.RequestServices.GetRequiredService <ITokenValidatorService>();
                        return(tokenValidatorService.ValidateAsync(context));
                    },
                    OnMessageReceived = context =>
                    {
                        return(Task.CompletedTask);
                    },
                    OnChallenge = context =>
                    {
                        var logger = context.HttpContext.RequestServices.GetRequiredService <ILoggerFactory>().CreateLogger(nameof(JwtBearerEvents));
                        logger.LogError("OnChallenge error", context.Error, context.ErrorDescription);
                        return(Task.CompletedTask);
                    }
                };
            });
        }
Ejemplo n.º 2
0
        public TokenValidationParameters TokenValidationParameters()
        {
            TokenValidationParameters tokenValidationParameters = new TokenValidationParameters()
            {
                ValidIssuer              = _jwtOptions.Issuer,   // site that makes the token
                ValidateIssuer           = true,                 // TODO: change this to avoid forwarding attacks
                ValidAudience            = _jwtOptions.Audience, // site that consumes the token
                ValidateAudience         = true,                 // TODO: change this to avoid forwarding attacks
                IssuerSigningKey         = new SymmetricSecurityKey(TokenStoreSecurityService.GetSha256Hash(_jwtOptions.Key)),
                ValidateIssuerSigningKey = true,                 // verify signature to avoid tampering
                ValidateLifetime         = true,                 // validate the expiration
                ClockSkew = TimeSpan.Zero                        // tolerance for the expiration date
            };

            return(tokenValidationParameters);
        }
Ejemplo n.º 3
0
        private async Task <TokenObject> CreateAccessTokenAsync(List <Claim> claims)
        {
            //generate token
            SymmetricSecurityKey key   = new SymmetricSecurityKey(TokenStoreSecurityService.GetSha256Hash(_jwtOptions.Key));
            SigningCredentials   creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
            JwtSecurityToken     token = new JwtSecurityToken(
                issuer: _jwtOptions.Issuer,
                audience: _jwtOptions.Audience,
                claims: claims,
                notBefore: DateTime.UtcNow,
                expires: DateTime.UtcNow.AddDays(5),
                signingCredentials: creds);

            TokenObject tokenObject = new TokenObject
            {
                Token = new JwtSecurityTokenHandler().WriteToken(token)
            };

            return(await Task.FromResult(tokenObject));
        }