我正在尝试在我的应用程序中设置客户端授权。我的最终目标是向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."
}
有什么建议吗?
答案 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;
}