gpt4 book ai didi

c# - asp.net core 2.0 - 基于声明和策略的授权

转载 作者:太空宇宙 更新时间:2023-11-03 22:42:52 25 4
gpt4 key购买 nike

我正在使用带有声明身份的 cookie 身份验证。身份验证工作正常,但授权失败。

如果登录凭据匹配,这里将存储声明信息。

 var identity = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme);
identity.AddClaim(new Claim(ClaimTypes.Name, _user[0].UserName.ToString()));
identity.AddClaim(new Claim(ClaimTypes.Role, _user[0].UserRole));
identity.AddClaim(new Claim(ClaimTypes.Email, _user[0].UserEmail));
HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(identity));

这里是startup.cs configurationServices方法中的授权设置

 services.AddMvc();
services.AddAuthorization(options => {
options.AddPolicy("Admin", policy => policy.RequireClaim("Admin"));
options.AddPolicy("User", policy => policy.RequireClaim("User"));

});

和 Controller

 [Authorize(Policy = "Admin")]
public class UserController : Controller
{
//
}

虽然管理员以角色登录,但此授权重定向到我访问被拒绝的页面。这里有什么问题?

最佳答案

您需要指定声明类型及其应具有的值

services.AddAuthorization(options => {
options.AddPolicy("Admin", policy =>
{
policy.RequireClaim(ClaimTypes.Role, "Admin");
});
options.AddPolicy("User", policy =>
{
policy.RequireClaim(ClaimTypes.Role, "User");
});
});

关于c# - asp.net core 2.0 - 基于声明和策略的授权,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51442498/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com