簡體   English   中英

C# - 如何在Web API 2上添加JWT的用戶聲明/角色

[英]C# - How to add user claims/roles from JWT on Web API 2

我正在嘗試在我的應用程序中設置客戶端授權。 我的最終目標是向API發出HTTP請求,該請求將返回給定用戶的聲明列表。 不幸的是,我似乎無法弄清楚如何在聲明身份中添加聲明。

這是我在Global.asax嘗試的內容:

protected void Application_AuthenticateRequest(Object sender, EventArgs e)
{
    if (HttpContext.Current.User != null)
    {
        if (HttpContext.Current.User.Identity.IsAuthenticated)
        {
            var claimsIdentity = (ClaimsIdentity)HttpContext.Current.User.Identity;
            var identity = new ClaimsIdentity(claimsIdentity);
            identity.AddClaim(new Claim(ClaimTypes.Role, "Admin"));
        }
    }
}

然后在我的控制器中:

[HttpGet]
[Route("test")]
[Authorize(Roles = ("Admin"))]
public IHttpActionResult GetClaims()
{
    return Ok("Success");
}

最后這是響應401 - Unauthorized

{
    "message": "Authorization has been denied for this request."
}

有什么建議么?

我認為您需要在當前主體中添加標識:

var userNameClaim = new Claim(ClaimTypes.Name, appID);

var identity = new ClaimsIdentity(new[] { userNameClaim }, "Admin");

var principal = new ClaimsPrincipal(identity);

Thread.CurrentPrincipal = principal;

if (System.Web.HttpContext.Current != null)
{
    System.Web.HttpContext.Current.User = principal;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM