首页 > 解决方案 > 授权有效,但角色在 JWT 的 dotnet 核心中不起作用

问题描述

我像下面这样使用 JWT,当只使用Authorize时它可以正常工作,但是当想要使用Role时它不起作用

启动:

 public void ConfigureServices(IServiceCollection services)
        {
            //...
            AddOAuthProviders(services);
            //...
        }

        public IServiceCollection AddOAuthProviders(IServiceCollection services)
        {
            services.AddAuthentication(x =>
            {
                x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(options =>
            {
                options.Events = new JwtBearerEvents
                {
                    OnTokenValidated = context =>
                    {
                        return Task.CompletedTask;
                    },
                };
                options.RequireHttpsMetadata = false;
                options.SaveToken = true;
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Security.secretKey)),
                    ValidateIssuer = false,
                    ValidateAudience = false
                };
            });

            return services;
        }

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IUnitOfWork uow)
        {
            //....
            app.UseAuthentication();
            app.UseAuthorization();
            //...
        }

在身份验证方法中:

//...
var claims = new List<Claim>
                {
                    new Claim(ClaimTypes.Name, user.UserId.ToString()),
                    new Claim(ClaimTypes.Role, userRoles),//Read,Write
                };
//...

控制器:

[HttpPost]
        [Authorize(Roles = "Write")]
        public ActionResult Insert ...

标签: .net-corejwt

解决方案


看起来您正在通过执行以下操作在单个声明中添加多个角色:

new Claim(ClaimTypes.Role, userRoles)

如果您有多个角色,则每个角色都需要单独声明。像这样:

new Claim(ClaimTypes.Role, "Read")
new Claim(ClaimTypes.Role, "Write")

如果您在逗号分隔的字符串中获取角色userRoles,则可以使用一些 Linq 魔法来添加角色:

claims.AddRange(userRoles.Split(',').Select(r => new Claim(ClaimTypes.Role, r)));

推荐阅读