【问题标题】:Blazor SPA authenticating with Auth0 fails on callback使用 Auth0 进行身份验证的 Blazor SPA 在回调时失败
【发布时间】:2020-03-17 20:54:48
【问题描述】:

我正在按照this blog post 编写一个基本的 Blazor 应用程序,但在实际的 Blazor 应用程序中我遇到了 /callback 重定向的困难。我看到的错误是

OpenIdConnectProtocolException:消息包含错误:'invalid_grant',error_description:'无效授权码',error_uri:'error_uri 为空'

在 /callback URL 处。

如果我检查日志,我可以看到在 Auth0 端发生了三个事件:

  • 登录成功
  • 访问令牌的授权码
  • 授权码无效

一个接一个。我可以看到“成功交换”和“交换失败”条目之间的授权码确实匹配。

我可以看到实际上已经进行了 Auth0 身份验证,如果我浏览到我的应用程序中的其他页面,我可以看到我已经成功登录,但是对 /callback URL 的初始回调阻止了他们的跟踪。中间件/Startup.cs 代码中是否缺少某些内容,或者是否需要检查 Auth0 应用程序设置的其他内容?

为免生疑问,我已经准确复制了博文代码,并且可以确认应用程序进行身份验证并让我登录。这是 Startup.cs 中的代码:

public void ConfigureServices(IServiceCollection services)
{
    services.AddRazorPages();
    services.AddServerSideBlazor();
    services.AddHttpContextAccessor();
    services.AddSingleton<WeatherForecastService>();
    services.AddSingleton<ClubInformationService>();

    services.Configure<CookiePolicyOptions>(options =>
    {
        // This lambda determines whether user consent for non-essential cookies is needed for a given request.
        options.CheckConsentNeeded = context => true;
        options.MinimumSameSitePolicy = SameSiteMode.None;
    });

    // Add authentication services
    services.AddAuthentication(options =>
    {
        options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
        options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
        options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    })
    .AddCookie()
    .AddOpenIdConnect("Auth0", options =>
    {
        // Set the authority to your Auth0 domain
        options.Authority = $"https://{Configuration["Auth0:Domain"]}";

        // Configure the Auth0 Client ID and Client Secret
        options.ClientId = Configuration["Auth0:ClientId"];
        options.ClientSecret = Configuration["Auth0:ClientSecret"];

        // Set response type to code
        options.ResponseType = "code";

        // Configure the scope
        options.Scope.Clear();
        options.Scope.Add("openid");

        // Set the callback path, so Auth0 will call back to http://localhost:3000/callback
        // Also ensure that you have added the URL as an Allowed Callback URL in your Auth0 dashboard
        options.CallbackPath = new PathString("/callback");

        // Configure the Claims Issuer to be Auth0
        options.ClaimsIssuer = "Auth0";

        options.Events = new OpenIdConnectEvents
        {
        // handle the logout redirection
        OnRedirectToIdentityProviderForSignOut = (context) =>
            {
            var logoutUri = $"https://{Configuration["Auth0:Domain"]}/v2/logout?client_id={Configuration["Auth0:ClientId"]}";

            var postLogoutUri = context.Properties.RedirectUri;
            if (!string.IsNullOrEmpty(postLogoutUri))
            {
                if (postLogoutUri.StartsWith("/"))
                {
                // transform to absolute
                var request = context.Request;
                postLogoutUri = request.Scheme + "://" + request.Host + request.PathBase + postLogoutUri;
                }
                logoutUri += $"&returnTo={ Uri.EscapeDataString(postLogoutUri)}";
            }

            context.Response.Redirect(logoutUri);
            context.HandleResponse();

            return Task.CompletedTask;
        } //... etc.

不确定这是否会增加很多问题,但导致引发异常的诊断如下所示:

info: Microsoft.AspNetCore.Hosting.Diagnostics[1]
      Request starting HTTP/2 POST https://localhost:5001/callback application/x-www-form-urlencoded 396
info: Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationHandler[10]
      AuthenticationScheme: Cookies signed in.
info: Microsoft.AspNetCore.Hosting.Diagnostics[2]
      Request finished in 634.9692ms 302
info: Microsoft.AspNetCore.Hosting.Diagnostics[1]
      Request starting HTTP/2 POST https://localhost:5001/callback application/x-www-form-urlencoded 396
fail: Microsoft.AspNetCore.Authentication.OpenIdConnect.OpenIdConnectHandler[52]
      Message contains error: 'invalid_grant', error_description: 'Invalid authorization code', error_uri: 'error_uri is null', status code '403'.
fail: Microsoft.AspNetCore.Authentication.OpenIdConnect.OpenIdConnectHandler[17]
      Exception occurred while processing message.
Microsoft.IdentityModel.Protocols.OpenIdConnect.OpenIdConnectProtocolException: Message contains error: 'invalid_grant', error_description: 'Invalid authorization code', error_uri: 'error_uri is null'.
   at Microsoft.AspNetCore.Authentication.OpenIdConnect.OpenIdConnectHandler.RedeemAuthorizationCodeAsync(OpenIdConnectMessage tokenEndpointRequest)
   at Microsoft.AspNetCore.Authentication.OpenIdConnect.OpenIdConnectHandler.HandleRemoteAuthenticateAsync()
info: Microsoft.AspNetCore.Authentication.OpenIdConnect.OpenIdConnectHandler[4]
      Error from RemoteAuthentication: Message contains error: 'invalid_grant', error_description: 'Invalid authorization code', error_uri: 'error_uri is null'..
fail: Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware[1]
      An unhandled exception has occurred while executing the request.
System.Exception: An error was encountered while handling the remote login.
 ---> Microsoft.IdentityModel.Protocols.OpenIdConnect.OpenIdConnectProtocolException: Message contains error: 'invalid_grant', error_description: 'Invalid authorization code', error_uri: 'error_uri 
is null'.

【问题讨论】:

  • 这两行是我在您的应用程序中注意到的第一行:services.AddServerSideBlazor(); services.AddHttpContextAccessor(); HttpContext 在 Blazor Server 中不可用,对 AddHttpContextAccessor 的调用是徒劳的。我并没有声称这是问题所在,但你知道...
  • 感谢您的评论。您对这些代码行的看法可能是对的,但除非那里有专门针对该问题的问题,否则我认为您的建议并不能真正帮助使这篇文章更接近答案。
  • 你的代码好像和官方教程一样。可能其他地方有问题?例如,this issue 将电子邮件转为小写会导致类似问题。

标签: asp.net-core auth0 blazor


【解决方案1】:

如果您想在 Blazor WebAssembly 项目中添加 Auth0,您可以使用 documentation from Microsoft.

但是,在将其用于 Auth0 时,有一个问题:

或者您可以使用我的 NuGet 包:WebAssembly.Authentication.Auth0,它支持 Audience 参数。

更多细节可以在这里找到: https://github.com/StefH/Blazor.WebAssembly.Authentication.Auth0

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-07-17
    • 1970-01-01
    • 1970-01-01
    • 2018-11-02
    • 2017-05-29
    • 2016-11-15
    • 1970-01-01
    • 2017-11-19
    相关资源
    最近更新 更多