如何获取google oauth的访问令牌和id令牌?

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

我正在使用 Blazor Webassemble 独立 + Asp.Net Web Api(.Net8.0)。我想实施 Google Authentiaction。我成功获得了授权代码,但在获取访问令牌和 ID 令牌时遇到问题。我指的是 Google OpenId Connect。 我用过这个代码...

var authCode = "4/0AanRRrsWBIJ~~~~~~~~~~~~";
var clientId = configuration.GetValue<string>("Authentication:Google:ClientId") ?? string.Empty;
var clientSecret = configuration.GetValue<string>  ("Authentication:Google:ClientSecret") ?? string.Empty;
var redirectUri = "https://localhost:7210/authentication/login-callback";
var tokenUri = "https://oauth2.googleapis.com/token";

var parameters = new Dictionary<string, string>
{
    { "code", authCode },
    { "client_id", clientId },
    { "client_secret", clientSecret },
    { "redirect_uri", redirectUri },
    { "grant_type", "authorization_code" }
};
var content = new FormUrlEncodedContent(parameters);

var httpClient = httpClientFactory.CreateClient();
var response = await httpClient.PostAsync(tokenUri, content);

但是,我得到了错误;

StatusCode: 400

ReasonPhrase: 'Bad Request'

提前感谢您的帮助。

asp.net-web-api blazor google-oauth openid-connect blazor-webassembly
1个回答
0
投票

[已解决] 我没有考虑PKCE。 我更改了以下代码,并且成功运行。

var clientId = configuration.GetValue<string>("Authentication:Google:ClientId") ?? string.Empty;
var clientSecret = configuration.GetValue<string>("Authentication:Google:ClientSecret") ?? string.Empty;
var redirectUri = "https://localhost:7210/authentication/login-callback";
var authCode = request.AuthCode;
var codeVerifer = request.CodeVerifer;
var tokenUri = "https://oauth2.googleapis.com/token";

var body = new List<KeyValuePair<string, string>>
{
    new("code", authCode),
    new("client_id", clientId),
    new("client_secret", clientSecret),
    new("redirect_uri", redirectUri),
    new("grant_type", "authorization_code"),
    **new("code_verifier",  codeVerifer),**
};
var content = new FormUrlEncodedContent(body);
var httpClient = httpClientFactory.CreateClient();

**httpClient.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));**

var response = await httpClient.PostAsync(tokenUri, content);

var result = await response.Content.ReadFromJsonAsync<ExchangedTokenResponse>();
© www.soinside.com 2019 - 2024. All rights reserved.