我有一个使用 Azure AD 身份验证实现的 .net 核心 blazor 服务器应用程序。我注册了应用程序并在 azure 端完成了所有设置。现在,我想检索用户的姓名或电子邮件,并在登录时显示欢迎“用户”消息。应用程序成功通过身份验证,但我不确定如何检索用户名。
我的代码: 启动.cs
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = OpenIdConnectDefaults.AuthenticationScheme;
options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
})
.AddOpenIdConnect(options =>
{
options.Authority = "https://login.microsoftonline.com/;
options.ClientId = ClientId";
options.ResponseType = OpenIdConnectResponseType.IdToken;
options.CallbackPath = "/Myrequest";
options.SignedOutRedirectUri = "https://fftest.azurewebsites.net/";
options.TokenValidationParameters.NameClaimType = "name";
})
.AddCookie();
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
services.AddScoped(sp =>
{
var provider = sp.GetService<AuthenticationStateProvider>();
var state = provider.GetAuthenticationStateAsync().Result;
return state.User.Identity.IsAuthenticated ?
state.User : null;
});
}
Index.razor:
<h3>Welcome @Name ,</h3>
@code {
public string Name { get; set; }
//tring email = .FindFirstValue(ClaimTypes.Email);
protected override async Task OnInitializedAsync()
{
var authstate = await Authentication_.GetAuthenticationStateAsync();
var user = authstate.User.Identity.Name ;
if (user != null)
{
Name = user.ToString();
}
else
{
Name = "";
}
这是我第一次尝试进行 azure 广告身份验证,我需要实现 Graph API 吗?非常感谢任何答案!
答案 0 :(得分:0)
如果您从模板生成 Blazor 服务器端项目并启用身份验证,您可以在 Shared/LoginDisplay.razor 页面中看到我将要分享的内容,但它准确地展示了您的要求。
>您会看到它将从注入到 AuthorizeView 的 AuthenticationState 中读出用户身份到带有 @contexdt.User.Identity.Name
的页面
如果您想访问相同的内容,您可以在您的任何页面/组件中使用以下内容来注入 AuthenticationState 并读出属性。
@page "/"
@inject AuthenticationState AuthState
<h1>Hello @AuthState.User.Identity.Name!</h1>
要回答您的最后一个问题,无需使用 Graph API,因为名称属性在默认情况下可从登录时传回的声明中使用。如果不是这种情况,您很可能需要从图 API。
答案 1 :(得分:0)
在这上面花了几天之后;我发现我在设置身份验证方面所做的一切都是正确的。 app.razor 文件中缺少级联身份验证状态。
<CascadingAuthenticationState>
<Router AppAssembly="@typeof(Program).Assembly">
<Found Context="routeData">
<RouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)" />
</Found>
<NotFound>
<LayoutView Layout="@typeof(MainLayout)">
<p>Sorry, there's nothing at this address.</p>
</LayoutView>
</NotFound>
</Router>
</CascadingAuthenticationState>