我想向已经过身份验证的Windows用户添加角色声明 . 我天真的第一种方法是在WebApi之前运行的自定义owin中间件中添加角色声明 . 像这样:
public class IdentityMiddleware : OwinMiddleware
{
public IdentityMiddleware(OwinMiddleware next) : base(next)
{
}
public async override Task Invoke(IOwinContext context)
{
var user = context.Request.User as WindowsPrincipal;
var identity = user.Identity as ClaimsIdentity;
identity.AddClaim(new Claim(ClaimTypes.Role, "Admin"));
await Next.Invoke(context);
}
}
但是在这样的控制器中提供Authorize属性时 .
public class TestController : ApiController
{
[Authorize(Roles = "Admin")]
public string Get()
{
return User.Identity.Name;
}
}
..我会得到 401 .
我注意到新索赔的发行人是“地方当局”而不是“AD管理局”可能是这个原因吗?
2 回答
你有没有尝试过这个授权属性:
这对我有用: