使用 Blazor Server 和 OpenId Connect 授权代码流程登录后如何获取用户电子邮件地址?

问题描述 投票:0回答:0

我可以使用 Auth0 和授权代码流程成功登录 Blazor 服务器应用程序,但我仍在努力检索用户电子邮件地址,因此我可以从我的数据库中获取正确的用户配置文件。请在下面查看我的代码:

builder.Services.AddAuthentication(options =>
{
    options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
})
.AddCookie()
.AddOpenIdConnect("Auth0", options =>
{
    options.Authority = $"https://{builder.Configuration["Auth0:Domain"]}";
    options.ClientId = builder.Configuration["Auth0:ClientId"];
    options.ClientSecret = builder.Configuration["Auth0:ClientSecret"];
    options.ResponseType = OpenIdConnectResponseType.Code;
    options.Scope.Clear();
    options.Scope.Add("openid");
    options.Scope.Add("profile");
    options.Scope.Add("email");
    options.CallbackPath = new PathString("/callback");
    options.SaveTokens = true;
    options.Events = new OpenIdConnectEvents
    {
        OnRedirectToIdentityProviderForSignOut = (context) =>  { /* omitted for brevity */},

        OnAuthorizationCodeReceived = (context) =>
        {
            Console.WriteLine("In OnAuthorizationCodeReceived");
            Console.WriteLine(context.Principal.Identity.Name);
            foreach (var str in context.Principal.Claims.Select(c => $"{c.Type} - {c.Value}"))
            {
                Console.WriteLine(str)
            }
            return Task.CompletedTask;
        },

    };
});

我正在使用

OnAuthorizationCodeReceived
事件来尝试获得声明,但是
context.Principal
为空。

我用

Microsoft.AspNetCore.Authentication.OpenIdConnect
,版本
6.0.16

有什么办法吗?

c# blazor openid-connect blazor-server-side auth0
© www.soinside.com 2019 - 2024. All rights reserved.