我正在尝试构建一个服务器端 Blazor 应用程序,该应用程序允许用户登录 Identity Server 4 并使用 Cookie 处理本地授权。这是我当前设置的代码:
services.AddAuthentication(options => {
options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
})
.AddCookie("Cookies")
.AddOpenIdConnect("oidc",
options => {
Configuration.GetSection("OidcSettings").Bind(options);
// remove unecessary claims
options.ClaimActions.MapAllExcept("amr", "sub");
options.TokenValidationParameters = new TokenValidationParameters {
NameClaimType = ClaimTypes.NameIdentifier
};
});
我想使用 nameidentifier 声明作为用户名,我的印象是以前的映射应该解决这个问题。不幸的是,它不起作用。这是一些演示代码:
@page "/"
@using Microsoft.AspNetCore.Components
@using Microsoft.AspNetCore.Http
@inject IHttpContextAccessor ContextAccessor
@inject NavigationManager NavigationManager
@inject AuthenticationStateProvider AuthenticationStateProvider
<h1>Hello, world!</h1>
Welcome to your new app.
<AuthorizeView>
<NotAuthorized>
<form method="post" action="/Account/Login">
<button>Iniciar</button>
</form>
</NotAuthorized>
<Authorized>
<h1>Hi, @ContextAccessor.HttpContext.User.Identity.Name!</h1>
<h1>Hi, @(GetUsernameAsync().Result)!</h1>
</Authorized>
</AuthorizeView>
@code{
private async Task<string> GetUsernameAsync() {
var user1 = ContextAccessor.HttpContext.User.Identity.Name;
var authState = await AuthenticationStateProvider.GetAuthenticationStateAsync();
var user = authState.User;
if (user.Identity.IsAuthenticated)
{
return user.Identity.Name;
}
return "Nop";
}
}
在这两种情况下,用户名始终设置为空。这是我从调试器中得到的信息:
有几件事我没有得到:
我肯定错过了一些东西,但我不确定是什么......
谢谢
好的,经过几次测试,我终于设法让它工作了。我已经开始使用 sub 声明作为我用户的用户名。我不得不在 OpenId Connect 设置上更改一些内容:
.AddOpenIdConnect("oidc",
options => {
Configuration.GetSection("OidcSettings").Bind(options);
options.TokenValidationParameters = new TokenValidationParameters {
NameClaimType = "sub"
};
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句