我正在尝试构建服务器端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。这是我从调试器获得的信息:
有几件事我没有得到:
- 为什么要获得此身份验证类型?应该不是cookie还是应用程序cookie(或类似的东西)?
- 为什么没有将名称声明更改为名称标识符?
我肯定会丢失一些东西,但是我不确定是什么...
谢谢