我只是想在我的 .net core blazor 应用程序中检索登录的用户名,但我没有发现任何内容显示如何执行此操作。
我无法尝试任何事情,因为我找不到任何有关此的信息。我的program.cs处理登录:
using Blazored.SessionStorage;
using Gray_Audit_Workflow.Components;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication.OpenIdConnect;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddRazorComponents()
.AddInteractiveServerComponents();
builder.Services.AddMvc();
builder.Services.AddBlazoredSessionStorage();
builder.Services.AddAuthentication(authOptions => {
authOptions.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
authOptions.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
authOptions.DefaultSignOutScheme = CookieAuthenticationDefaults.AuthenticationScheme;
authOptions.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
}).AddOpenIdConnect(oidcOptions => {
oidcOptions.ClientId = builder.Configuration["Okta:ClientId"];
oidcOptions.ClientSecret = builder.Configuration["Okta:ClientSecret"];
oidcOptions.CallbackPath = "/authorization-code/callback";
oidcOptions.Authority = builder.Configuration["Okta:Issuer"];
oidcOptions.ResponseType = "code";
oidcOptions.SaveTokens = true;
oidcOptions.Scope.Add("openid");
oidcOptions.Scope.Add("profile");
oidcOptions.TokenValidationParameters.ValidateIssuer = false;
oidcOptions.TokenValidationParameters.NameClaimType = "name";
}).AddCookie();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment()) {
app.UseExceptionHandler("/Error", createScopeForErrors: true);
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseAntiforgery();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.MapRazorComponents<App>()
.AddInteractiveServerRenderMode();
app.Run();
我无法想象这很难做到。但是,我根本找不到任何关于此的信息。
我使用了gunr2171的上述答案的组合,该答案链接到有关用户声明的另一个答案,以及okta blazor示例存储库:https://github.com/okta/samples-blazor
我使用剃刀标记来查找从访问令牌返回哪些信息:
@foreach (var claim in context.User.Claims)
{
<tr>
<td>@claim.Type</td>
<td>@claim.Value</td>
</tr>
}
</tbody>
如果您想显示用户名,请使用:
<p>Hello, @context.User.Identity.Name</p>
如果您想从代码块中的声明中检索值,则必须在 Razor 页面顶部注入 AuthenticationStateProvider 的实例:
@inject AuthenticationStateProvider AuthenticationStateProvider
然后在代码块中你可以做这样的事情:
@code {
public string oktaId { get; set; }
protected override async Task OnInitializedAsync()
{
var authState = await AuthenticationStateProvider.GetAuthenticationStateAsync();
var user = authState.User;
oktaId = user.Claims.First().Value.ToString();
}
}
对于我来说,我需要 okta 用户 ID,它恰好是声明列表中的第一个值。当我循环浏览 html 中的声明类型时,我注意到 okta 登录名位于该列表中。我希望这有帮助!我对此也很陌生,只是花了两周的大部分时间试图解决这个问题。