我正在尝试构建服务器端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";
}
}
在两种情况下,用户名始终设置为null。这是我从调试器获得的信息:
有几件事我没有得到:
我肯定会丢失一些东西,但是我不确定是什么...
谢谢
答案 0 :(得分:0)
好吧,所以经过几次测试,我终于设法使它工作了。我已经开始使用子声明作为用户的用户名。我不得不在OpenId Connect设置上更改了几件事:
.AddOpenIdConnect("oidc",
options => {
Configuration.GetSection("OidcSettings").Bind(options);
options.TokenValidationParameters = new TokenValidationParameters {
NameClaimType = "sub"
};
});