如何获取用户 Google 令牌以调用使用身份服务器 4 登录的 API

时间:2021-01-12 19:22:29

标签: identityserver4 openid-connect

我有一个 JavaScript 应用程序,用户使用 Identity Server 4 使用他们的 Google 帐户登录,登录部分有效,但是当用户登录时,我想调用我们的 API,如 api.example.com ->代表登录用户调用 google API,例如获取用户日历。

我尝试在登录回调中将令牌添加到 localClaims,其中 G 令牌存在,但我不知道如何将其获取到我可以作为传递给 api.example.com 的 Bearer-token身份验证标头。

这是将 Google 令牌传递给 API 的正确方法吗?有什么更好的建议吗?

private void ProcessLoginCallback(AuthenticateResult externalResult, List<Claim> localClaims, AuthenticationProperties localSignInProps)
{
     //...
     
     var accessToken = externalResult.Properties.GetTokenValue("access_token");
     if (accessToken != null)
     {
      localClaims.Add(new Claim("googleAccessToken", accessToken)); // accessToken: contains google-token.
     }

     // ...
}

目前身份服务器配置非常基本,我正在努力寻找我想要的东西来完成我想要的(将 Google 令牌传递给 API)

客户端配置:

new Client
{
     ClientId = "m2m.client",
     ClientName = "Client Credentials Client",

     AllowedGrantTypes = GrantTypes.Code,
     RequireClientSecret = false,

     RedirectUris = { "http://localhost:3000/login/response" },
     FrontChannelLogoutUri = "https://localhost:5001/signout-oidc",
     PostLogoutRedirectUris = { "https://localhost:5001/signout-callback-oidc" },

     AllowedScopes = { "xyz", "openid", "profile", "email", "offline_access" },
     AllowedCorsOrigins = { "http://localhost:3000" },

     AllowAccessTokensViaBrowser = true,
     AlwaysIncludeUserClaimsInIdToken = true,

     AllowOfflineAccess = true,
},

Google 配置:

.AddGoogle(options =>
{
     options.SignInScheme = IdentityServerConstants.ExternalCookieAuthenticationScheme;

     options.ClientId = "myClientId";
     options.ClientSecret = "myCLientSecret";

     options.SaveTokens = true;
     options.AccessType = "offline";
     options.Scope.Add("myGoogleScope");
});

0 个答案:

没有答案
相关问题