我正在构建一个 ASP.NET Core (v3.1) 模块,并且我只是设法配置了一个 OpenIdConnect 身份验证。现在,我需要从 API 获取所有用户的角色以授予或拒绝对它们的访问权限,然后我通过OnAuthorizationCodeReceivedEvent 将多个声明值添加到用户声明列表中的同一声明角色“ClaimTypes.Role”,如下所示:
OnAuthorizationCodeReceived = async (context) =>
{
// Uses the authentication code and gets the access and refresh token
var client = new HttpClient();
var response = await client.RequestAuthorizationCodeTokenAsync(new AuthorizationCodeTokenRequest()
{
Address = urlServer + "/connect/token",
ClientId = "hybrid",
Code = context.TokenEndpointRequest.Code,
RedirectUri = context.TokenEndpointRequest.RedirectUri,
}
if (response.IsError) throw new Exception(response.Error);
var identity = new ClaimsIdentity(context.Principal.Identity);
var listRoles = GenericProxies.RestGet<List<string>>(urlGetRoles, response.AccessToken); // GET request to API
listRoles.ForEach(role => identity.AddClaim(new Claim(ClaimTypes.Role, role)));
context.HttpContext.User = new ClaimsPrincipal(identity);
context.HandleCodeRedemption(response.AccessToken, response.IdentityToken);
}
在调试时,我注意到所有角色都添加到了用户声明列表之后:
context.HttpContext.User = new ClaimsPrincipal(identity);
但是,显然,在我的 Home 控制器中(即用户在经过身份验证后被重定向到的位置),当我访问 HttpContext.User 时,我似乎找不到我之前添加的任何角色,除了“Admin”(我猜这是一个默认的 ClaimTypes.Role 值)。
[Authorize]
public IActionResult Index()
{
if (User.IsInRole("SomeRole"))
{
return RedirectToAction("SomeAction", "SomeController");
}
else
{
return RedirectToAction("Forbidden", "Error");
}
}
阅读其他一些帖子论坛和主题,我发现这可能是一个上下文持久性问题,我试图在我的帐户控制器中使用以下代码解决这个问题:
public async Task Login(string returnUrl = "/")
{
await HttpContext.ChallengeAsync(
"OIDC",
new AuthenticationProperties
{
AllowRefresh = false,
IsPersistent = true,
RedirectUri = returnUrl
});
}
一些示例说我可以使用context.Principal.AddIdentity(identity);以保留新的声明列表,但随后出现以下错误:
InvalidOperationException: only a single identity supported
IdentityServer4.Hosting.IdentityServerAuthenticationService.AssertRequiredClaims(ClaimsPrincipal principal)
总而言之,我必须找到一种方法来持久化我添加到用户声明列表中的角色声明,但直到现在我都没有成功。