Пример #1
0
        private void AddSecurity(IServiceCollection services)
        {
            services.AddAuthentication(opt =>
            {
                opt.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                opt.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
                opt.DefaultScheme             = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(opt =>
            {
                opt.SaveToken = true;
                opt.TokenValidationParameters = TokenValidationParametersDefaults.GetDefaultParameters();
            });

            services.AddAuthorization();
        }
        public ClaimsPrincipal GetPrincipalFromToken(string token)
        {
            var tokenHandler = new JwtSecurityTokenHandler();

            try
            {
                var principal =
                    tokenHandler.ValidateToken(token, TokenValidationParametersDefaults.GetDefaultParameters(),
                                               out var validatedToken);
                if (!IsJwtWithValidSecurityAlgorithm(validatedToken))
                {
                    return(null);
                }

                return(principal);
            }
            catch (Exception)
            {
                return(null);
            }
        }