【发布时间】:2019-11-18 12:00:35
【问题描述】:
我正在尝试构建一个服务器端 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(或类似的东西)吗?
- 为什么名称声明没有更改为名称标识符?
我肯定错过了一些东西,但我不确定是什么......
谢谢
【问题讨论】:
标签: authentication identityserver4 openid-connect blazor-server-side