我正在尝试将Keycloak用作ASP.Net核心应用程序的OpenId服务器。
几乎可以。用户获得了授权(通过[Authorize]
属性),但其声明为空。
我的配置:
services.AddAuthentication(options => { options.DefaultScheme = "cookie"; })
.AddCookie("cookie")
.AddOpenIdConnect("oidc", options =>
{
options.Authority = "http://localhost:8080/auth/realms/master/";
options.RequireHttpsMetadata = false;
options.ClientId = "test-client";
options.ClientSecret = "ee117d6d-25c9-4317-83a0-54c2f252aa89";
options.GetClaimsFromUserInfoEndpoint = true;
options.SaveTokens = true;
options.RemoteSignOutPath = "/SignOut";
options.SignedOutRedirectUri = "Redirect-here";
options.ResponseType = "code";
});
可以正常运行(获得授权)的控制器动作:
[Authorize]
public IActionResult About()
{
ViewData["Message"] = "Your application description page.";
return View();
}
未经授权的控制器操作(因为它需要角色):
[Authorize(Roles = "Administrators")]
public IActionResult About()
{
ViewData["Message"] = "Your application description page.";
return View();
}
AccountController.ExternalLoginCallback:
public async Task<IActionResult> ExternalLoginCallback(string returnUrl = null, string remoteError = null)
{
if (remoteError != null)
{
ErrorMessage = $"Error from external provider: {remoteError}";
return RedirectToAction(nameof(Login));
}
var info = await _signInManager.GetExternalLoginInfoAsync(); // it has claims
if (info == null)
{
return RedirectToAction(nameof(Login));
}
var result = await _signInManager.ExternalLoginSignInAsync(info.LoginProvider, info.ProviderKey, isPersistent: false, bypassTwoFactor: true);
if (result.Succeeded)
{
_logger.LogInformation("User logged in with {Name} provider.", info.LoginProvider);
return RedirectToLocal(returnUrl);
}
if (result.IsLockedOut)
{
return RedirectToAction(nameof(Lockout));
}
else
{
ViewData["ReturnUrl"] = returnUrl;
ViewData["LoginProvider"] = info.LoginProvider;
var email = info.Principal.FindFirstValue(ClaimTypes.Email);
return View("ExternalLogin", new ExternalLoginViewModel { Email = email });
}
}
上面摘录中的 info
目标具有声明,尤其是角色声明:
但是当我登录并尝试查看角色和蛤lam时,它们是空的:
var user = await _signInManager.UserManager.GetUserAsync(HttpContext.User); // user is found
var roles = await _signInManager.UserManager.GetRolesAsync(user); // empty
var claims = await _signInManager.UserManager.GetClaimsAsync(user); //empty
所以看来Keycloak一切都很好,但是我的应用在使用声明时遇到了问题。
我想念什么?
答案 0 :(得分:0)
您需要配置身份验证提供程序,以便它知道要用于角色的声明类型。
您可以对其进行如下配置:
services.AddOpenIdConnect("oidc", options =>
{
...
options.TokenValidationParameters = new TokenValidationParameters
{
RoleClaimType = "user_roles"; // or "user_realm_roles"?
};
});