Esempio n. 1
0
        private void InitializeJwtAuthentication(IServiceCollection services)
        {
            var securityKey = _securityKeyFactory.CreateSecurityKey();

            var tokenValidationParameters = new TokenValidationParameters
            {
                ValidateIssuer           = false,
                ValidateAudience         = false,
                ValidateIssuerSigningKey = false,
                RequireExpirationTime    = false,
                ValidateLifetime         = true,
                ClockSkew        = TimeSpan.Zero,
                IssuerSigningKey = securityKey
            };

            services.AddAuthentication(
                options =>
            {
                options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
            }
                ).AddJwtBearer(
                options =>
            {
                options.RequireHttpsMetadata      = false;
                options.SaveToken                 = true;
                options.TokenValidationParameters = tokenValidationParameters;

                options.Events = new JwtBearerEvents
                {
                    OnAuthenticationFailed = context =>
                    {
                        if (Debugger.IsAttached)
                        {
                            Debugger.Break();
                        }

                        Console.WriteLine(
                            "OnAuthenticationFailed: " +
                            context.Exception.Message);
                        return(Task.CompletedTask);
                    },
                    OnTokenValidated = context =>
                    {
                        Console.WriteLine(
                            "OnTokenValidated: " +
                            context.SecurityToken);
                        return(Task.CompletedTask);
                    }
                };
            });
        }
        public async Task <string> CreateSerializedJtwTokenAsync(string userName)
        {
            var secretKey = _securityKeyFactory.CreateSecurityKey();
            var appUser   = _appUserFactory.Create(userName);

            var claims = await _userManager.GetClaimsAsync(appUser);

            var jwtHeader  = new JwtHeader(new SigningCredentials(secretKey, SecurityAlgorithms.HmacSha256));
            var jwtPayload = new JwtPayload(claims);
            var token      = new JwtSecurityToken(jwtHeader, jwtPayload);

            var result = new JwtSecurityTokenHandler().WriteToken(token);

            return(result);
        }