简体   繁体   English

WebApi核心2.2 JWT令牌未获得授权

[英]WebApi core 2.2 JWT Token not been Authorized

I was able to generate the token but if I tried to Authorize in my controller it doesn't work. 我能够生成令牌,但是如果我尝试在控制器中进行授权,它将无法正常工作。

I create a class JWT but I didn't set the issuer or audience. 我创建了一个JWT类,但没有设置发布者或受众。

private List<Claim> Claim = new List<Claim>();
    public string GetUserToken(string tp,string id)
    {
        var sck = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT")));
        var sc = new SigningCredentials(sck, SecurityAlgorithms.HmacSha256Signature);

        if(tp == "Host")
        {
            Claim.Add(new Claim(ClaimTypes.Role, "Host"));
            Claim.Add(new Claim(ClaimTypes.Name, id));
        }
        else
        {
            Claim.Add(new Claim(ClaimTypes.Role, "Client"));
            Claim.Add(new Claim(ClaimTypes.Name, id));
        }

        var token = new JwtSecurityToken(               
            expires: DateTime.Now.AddDays(30),
            signingCredentials: sc,
            claims: Claim
            );
        return new JwtSecurityTokenHandler().WriteToken(token);
    }

and Inside of Startup class : Startup类内部:

public void ConfigureServices(IServiceCollection services)
    {
        var SymmetricSecurityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT")));
        services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).
            AddJwtBearer(options => {
            options.TokenValidationParameters = new TokenValidationParameters
            {
                ValidateIssuerSigningKey = true,                    
                IssuerSigningKey = SymmetricSecurityKey
            };
        });

And in my controller I just put [Authorize(Roles ="Host")] . 在我的控制器中,我只放置了[Authorize(Roles ="Host")] Even removing the Roles attribute still the same result, 401 Unauthorized 即使删除“ Roles属性,结果仍然相同,即401 Unauthorized

Check your key and jwt configuration, your startup class should looks something like this: 检查您的密钥和jwt配置,您的启动类应如下所示:

public void ConfigureServices(IServiceCollection services)
        {

            services.AddCors();
            services.AddMvc()
                .SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

            //Get the key from configuration file section
            var appSettings = Configuration.GetSection("AppSettings").Get<AppSettings>();
            var key = Encoding.ASCII.GetBytes(appSettings.Secret);

            //jwt configuration 
            services.AddAuthentication(x =>
            {
                x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(x => {
                x.RequireHttpsMetadata = false;
                x.SaveToken = true;
                x.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey = new SymmetricSecurityKey(key),
                    ValidateIssuer = false,
                    ValidateAudience = false
                };
            });

        }

        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            //Configuration of cors to allow request of anothers 
            app.UseCors(x => x
                .AllowAnyOrigin()
                .AllowAnyMethod()
                .AllowAnyHeader());

            //Use the authentication service
            app.UseAuthentication();
            app.UseHttpsRedirection();
            app.UseMvc();
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 .NET Core 2.2 中的自定义 JWT 令牌验证 - Custom JWT token validation in .NET Core 2.2 AspNet WebApi 核心 JWT 令牌未进行身份验证 - AspNet WebApi core JWT token not Authenticating Net Core 2.2 MVC WebApi中的JWT“自我”身份验证 - JWT “self” authentication in Net Core 2.2 MVC WebApi ASP.NET核心网站使用JWT令牌进行WebApi身份验证 - ASP.NET Core Website to WebApi authentication using JWT token .NET Core Jwt 令牌在尝试访问授权区域时总是过期 - .NET Core Jwt Token always expired when trying to access Authorized area C#Jwt令牌生成失败的asp.net核心2.2 - C# Jwt Token generation failed asp.net core 2.2 使用 Razor (.NET CORE 2.2 MVC) 时如何在每个请求时传输 JWT 令牌 - How to transfer a JWT token at each requesto when using Razor (.NET CORE 2.2 MVC) 在从.NET Core 2.2移至3.0之后,基于JWT令牌承载的身份验证失败 - Authentication based on JWT token bearer fails under .NET Core 2.2 after move from 3.0 我如何从jwt令牌登录用户并设置角色.net Core 2.2 - How can i login users from a jwt token and set roles .net core 2.2 使用Azure ActiveDir oAuth2.0 JWT令牌Microsoft Graph的Asp-Net-Core WebApi身份验证 - Asp-Net-Core WebApi Authentication using Azure ActiveDir oAuth2.0 JWT Token Microsoft Graph
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM