亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在 ASP.NET Core 的 Middleware 中設置用戶的角色

如何在 ASP.NET Core 的 Middleware 中設置用戶的角色

冉冉說 2018-08-18 14:10:50
目前 middleware 中的代碼是這么寫的public class AuthorizeMiddleware{    private RequestDelegate _next;    public AuthorizeMiddleware(RequestDelegate next)    {         _next = next;     }    public async Task Invoke(HttpContext context, IUserService userService)    {        var identity = context.User.Identity;        if (identity.IsAuthenticated              && await userService.IsUserInRole(ROLE_NAME, identity.Name))         {             context.User.AddIdentity(new ClaimsIdentity("Basic", ClaimTypes.Role, ROLE_NAME));         }        await _next(context);     } }在 Authorization Policy 中使用這個角色進行授權,但不起作用services.AddMvc(o =>     {        var policy = new AuthorizationPolicyBuilder()             .RequireRole(ROLE_NAME)             .Build();         o.Filters.Add(new AuthorizeFilter(policy));     });請問如何解決這個問題?
查看完整描述

1 回答

?
守著星空守著你

TA貢獻1799條經驗 獲得超8個贊

用 AddIdentity 是不正確的方法,需要在已有的 context.User.Identity 中添加 Claim ,但 context.User.Identity 的類型是 IIdentity ,它沒有提供添加 Claim 的方法。

后來在 stackoverflow 的 Update claims in ClaimsPrincipal 中知道了可以將 context.User.Identity 轉換為 ClaimsIdentity ,通過它就可以添加 Claim 了。

var claimsIdentity = context.User.Identity as ClaimsIdentity;if(claimsIdentity != null)
{
    claimsIdentity.AddClaim(new Claim(ClaimTypes.Role, ROLE_NAME));
}


查看完整回答
反對 回復 2018-09-09
  • 1 回答
  • 0 關注
  • 519 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號