我正在尝试在后端使用 AWS Lambda 上的 C# 和 React 前端(目前只是一个基本的本地托管服务器)设置一个应用程序。
从前端,我开始从 Spotify 请求访问代码的 OAuth 过程,然后当我有了该代码时,我调用我的后端
server.com/api/authenticate?code=SPOTIFYCODE
我想使用 SpotifyAPI-NET sdk,因为它做了很多艰苦的工作,但它似乎总是抛出 SpotifyAPI.Web.APIException 错误和
invalid_grant
。我通常会假设请求参数是错误的,但是手动发出请求可以正常工作,所以我很困惑。
我可以通过以下方式成功获取访问令牌:
// GET api/authenticate
[HttpGet]
public async Task<ActionResult> Authenticate(string code)
{
// Exchange the authorization code for an access token
var parameters = new Dictionary<string, string>
{
{ "grant_type", "authorization_code" },
{ "code", code },
{ "redirect_uri", RedirectUri },
{ "client_id", ClientId },
{ "client_secret", ClientSecret }
};
var content = new FormUrlEncodedContent(parameters);
var response = await _httpClient.PostAsync(TokenEndpoint, content);
if (!response.IsSuccessStatusCode) return BadRequest("Failed to get access token.");
var responseContent = await response.Content.ReadAsStringAsync();
var tokenResponse = JsonSerializer.Deserialize<TokenResponse>(responseContent);
var accessToken = tokenResponse?.AccessToken;
// Create a new cookie with the access token
if (string.IsNullOrEmpty(accessToken)) return BadRequest("Failed to get access token. Access token is null or empty.");
var cookieOptions = new CookieOptions
{
HttpOnly = true,
Secure = true,
Expires = DateTimeOffset.Now.AddDays(1),
SameSite = SameSiteMode.None,
Domain = Request.Host.Value,
Path = "/api",
};
Response.Cookies.Append("access_token", accessToken, cookieOptions);
return Ok();
}
但是,如果我尝试使用相同的信息,但按照 这些说明 使用 sdk... 它会失败。
// GET api/authenticate
[HttpGet]
public async Task<ActionResult> Authenticate(string code)
{
var response = await new OAuthClient().RequestToken(
new AuthorizationCodeTokenRequest(
ClientId,
ClientSecret,
code,
new Uri(RedirectUri))
);
var accessToken = response.AccessToken;
// Create a new cookie with the access token
if (string.IsNullOrEmpty(accessToken)) return BadRequest("Failed to get access token. Access token is null or empty.");
var cookieOptions = new CookieOptions
{
HttpOnly = true,
Secure = true,
Expires = DateTimeOffset.Now.AddDays(1),
SameSite = SameSiteMode.None,
Domain = Request.Host.Value,
Path = "/api",
};
Response.Cookies.Append("access_token", accessToken, cookieOptions);
return Ok();
}```
这可能是由于 redirect_uri。在您的工作代码中,您传递了一个字符串,但在您使用 SDK 时它变成了 Uri 类。
在 SDK 的源代码中,它在这一行将其转换为字符串:
new KeyValuePair<string?, string?>("redirect_uri", request.RedirectUri.ToString())
当你使用基本 url 执行此操作时,它会在末尾附加一个斜杠。如果您的原始 redirect_uri 不包含尾部斜杠,那么它们可能不匹配并且您会收到此错误。
您可以在原始 redirect_uri 中添加尾部斜杠(当您将用户重定向到 spotify 服务时)来测试这种情况。