C#-如何在Web API 2上从JWT添加用户声明/角色

时间:2019-04-24 18:36:15

标签: c# asp.net asp.net-web-api jwt asp.net-identity

我正在尝试在我的应用程序中设置客户端授权。我的最终目标是向API发出HTTP请求,该请求将返回给定用户的声明列表。不幸的是,我似乎无法弄清楚如何在Claims Identity中添加索赔。

这是我在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."
}

有什么建议吗?

1 个答案:

答案 0 :(得分:0)

我认为您需要在当前主体中添加身份:

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