WebApi核心2.2 JWT令牌未获得授权 [英] WebApi core 2.2 JWT Token not been Authorized

查看:101
本文介绍了WebApi核心2.2 JWT令牌未获得授权的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我能够生成令牌,但是如果我尝试在控制器中进行授权,那么它将无法正常工作.

I was able to generate the token but if I tried to Authorize in my controller it doesn't work.

我创建了一个JWT类,但没有设置发布者或受众.

I create a class JWT but I didn't set the issuer or audience.

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);
    }

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
            };
        });

然后在我的控制器中放入[Authorize(Roles ="Host")].即使删除Roles属性,结果仍然相同,401 Unauthorized

And in my controller I just put [Authorize(Roles ="Host")]. Even removing the Roles attribute still the same result, 401 Unauthorized

推荐答案

检查密钥和jwt配置,您的启动类应如下所示:

Check your key and jwt configuration, your startup class should looks something like this:

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();
        }

这篇关于WebApi核心2.2 JWT令牌未获得授权的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆