本文介绍了Google Auth错误在Blazor中获取访问令牌的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前有一个带有Blazor WASM的ASP.Net Core Web Api,它可以使用组件RemoteAuthenticatorView成功登录到Google OAuth.现在,我的意图是将我拥有的令牌传递给Web api,希望可以将其用于对Web api进行身份验证.问题是TokenProvider.RequestAccessToken()产生以下错误.

I currently have a ASP.Net Core Web Api with Blazor WASM which can login successfully to Google OAuth using the component RemoteAuthenticatorView. My intention is now to pass the token I have to the web api, which hopefully can be used to authenticate with the web api. The issue is that TokenProvider.RequestAccessToken() produces the following error.

blazor.webassembly.js:1 Microsoft.JSInterop.JSException: An exception occurred executing JS interop: The JSON value could not be converted to System.DateTimeOffset. Path: $.token.expires | LineNumber: 0 | BytePositionInLine: 88.. See InnerException for more details.
System.Text.Json.JsonException: The JSON value could not be converted to System.DateTimeOffset. Path: $.token.expires | LineNumber: 0 | BytePositionInLine: 88.
            var tokenResult = await TokenProvider.RequestAccessToken();

            if (tokenResult.TryGetToken(out var token))
            {
                requestMessage.Headers.Authorization =
                  new AuthenticationHeaderValue("Bearer", token.Value);
                var response = await Http.SendAsync(requestMessage);

            }

Program.cs

Program.cs

            builder.Services.AddOidcAuthentication(options =>
            {
                builder.Configuration.Bind("Local", options.ProviderOptions);
                options.ProviderOptions.DefaultScopes.Add("email");
            });

有什么想法吗?范围丢失了吗?我可以在会话存储中看到id_token ...也许Blazor WASM和核心Web API的任何net 5示例?

Any ideas? Is a scope missing? I can see id_token in Session storage... Perhaps any net 5 example of Blazor WASM and core web api?

我看到RequestAccessToken对Google auth进行了网络呼叫,就像它试图再次进行身份验证一样

I see there is a network call made by RequestAccessToken to google auth, like if it were trying to authenticate again

推荐答案

使用单个帐户独立创建WebAssembly Blazor App.

Create a WebAssembly Blazor App standalone with individual accounts.

使用以下代码替换appsettings.json文件中的内容:

Replace the content in the appsettings.json file with the following code:

{
  "Google": {
    "Authority": "https://accounts.google.com/",
    "ClientId": "11111111111-11111111111111111111111111111111.apps.googleusercontent.com",
    "DefaultScopes": [ "email" ], // The Blazor WebAssembly template automatically configures default scopes for openid and profile
    "PostLogoutRedirectUri": "https://localhost:44313/authentication/logout-callback",
    "RedirectUri": "https://localhost:44313/authentication/login-callback",
    "ResponseType": "id_token token"
  }
}

运行您的应用,然后单击登录"链接...您将被重定向到Google的登录"页面.通过Google进行身份验证...您将被重定向到您的应用,登录名"更改为注销",并且您的用户名显示在其附近.

Run your app, and click on the Login link...You're being redirected to Google' Login page. Authenticate with Google...You are being redirected to your app, the Login is changed into Logout, and your user name appears near it.

您可以通过开发人员的工具查看id_token和个人资料.

You may view the id_token and profile via the developers' tools.

如何获取访问令牌?

将以下代码段添加到索引"页面并运行...

Add the following code snippet to your Index page and run...

@page "/"
@using Microsoft.AspNetCore.Components.WebAssembly.Authentication;

@inject IAccessTokenProvider TokenProvider

<p>@output</p>

<button @onclick="DisplayToken">Display Access Token </button>

@code
{
    private string output;

    private async Task DisplayToken()
    {
        var tokenResult = await TokenProvider.RequestAccessToken();

        if (tokenResult.TryGetToken(out var token))
        {
            output = token.Value;

        }
    }

}

注意:上面的代码仅用于演示目的(在您的代码示例之后).但是,如果使用HttpClient服务对Web Api执行HTTP调用,则访问令牌将自动被AuthorizationMessagelHandler对象检索并分配给Authorization标头.

Note: The code above is for demonstration purposes only (following your code sample). However, if you perform an HTTP call to your Web Api using the HttpClient service the access token is automatically retrieved and assigned to the Authorization header by the AuthorizationMessagelHandler object.

这篇关于Google Auth错误在Blazor中获取访问令牌的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 11:36