我正在按照这里的示例构建 OAuth2 授权服务器:https://learn.microsoft.com/en-us/aspnet/aspnet/overview/owin-and-katana/owin-oauth-20-authorization-server
我有授权码,并正在尝试将其兑换为访问令牌。不管怎样,我都会收到 400 响应“invalid_grant”。
这是我的相关服务器实现:
OAuthAuthorizationServerOptions serverOptions = new OAuthAuthorizationServerOptions()
{
AuthorizeEndpointPath = new PathString(authorizePath),
TokenEndpointPath = new PathString(tokenPath),
ApplicationCanDisplayErrors = true,
AllowInsecureHttp = true, // tsk tsk
Provider = new OAuthAuthorizationServerProvider
{
//OnValidateAuthorizeRequest = ValidateAuth,
OnValidateClientRedirectUri = ValidateClientRedirectUri,
OnValidateClientAuthentication = ValidateClientAuthentication,
OnGrantResourceOwnerCredentials = GrantResourceOwnerCredentials,
OnGrantClientCredentials = GrantClientCredetails
},
// Authorization code provider which creates and receives authorization code
AuthorizationCodeProvider = new AuthenticationTokenProvider
{
OnCreate = CreateAuthenticationCode,
OnReceive = ReceiveAuthenticationCode
},
// Refresh token provider which creates and receives referesh token
RefreshTokenProvider = new AuthenticationTokenProvider
{
OnCreate = CreateRefreshToken,
OnReceive = ReceiveRefreshToken,
}
};
app.UseOAuthAuthorizationServer(serverOptions);
private Task ValidateClientRedirectUri(OAuthValidateClientRedirectUriContext context)
{
context.Validated(context.RedirectUri);
return Task.FromResult(0);
}
private Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
{
string clientId;
string clientSecret;
if (context.TryGetBasicCredentials(out clientId, out clientSecret) ||
context.TryGetFormCredentials(out clientId, out clientSecret))
{
context.Validated();
}
return Task.FromResult(0);
}
private readonly ConcurrentDictionary<string, string> _authenticationCodes =
new ConcurrentDictionary<string, string>(StringComparer.Ordinal);
private void CreateAuthenticationCode(AuthenticationTokenCreateContext context)
{
context.SetToken(Guid.NewGuid().ToString("n") + Guid.NewGuid().ToString("n"));
_authenticationCodes[context.Token] = context.SerializeTicket();
}
private void ReceiveAuthenticationCode(AuthenticationTokenReceiveContext context)
{
string value;
if (_authenticationCodes.TryRemove(context.Token, out value))
{
context.DeserializeTicket(value);
}
context.DeserializeTicket(value);
}
private void CreateRefreshToken(AuthenticationTokenCreateContext context)
{
context.SetToken(context.SerializeTicket());
}
private void ReceiveRefreshToken(AuthenticationTokenReceiveContext context)
{
context.DeserializeTicket(context.Token);
}
这是我在客户端请求令牌的地方:
var requestPrefix = Request.Scheme + "://" + Request.Host;
var redirectUri = requestPrefix + Request.PathBase + Options.CallbackPath + "/";
var body = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("grant_type", "authorization_code"),
new KeyValuePair<string, string>("code", code),
new KeyValuePair<string, string>("redirect_uri", redirectUri),
new KeyValuePair<string, string>("client_id", Options.ClientId),
new KeyValuePair<string, string>("client_secret", Options.ClientSecret),
};
HttpClient _httpClient = new HttpClient();
var tokenResponse =
await _httpClient.PostAsync(Constants.GARBAGE_TOKEN, new FormUrlEncodedContent(body));
var text = await tokenResponse.Content.ReadAsStringAsync();
到目前为止我测试过的:
但在那之后 - 我就失去了它的踪迹。它以“invalid_grant”的形式返回给调用客户端,我正在绞尽脑汁地试图找出令牌下一步在管道中的位置。据推测,正在调用某些提供程序元素,由于某种原因将令牌设置为无效,但我一直在研究 OAuthAuthorizationServerProvider 源,但我什么也没得到,而且似乎没有任何方法可以单步执行它。事实上,即使知道处理发送令牌的实际响应的代码部分也是有用的;这对我来说都是不透明的。
为什么token会失效?它实际上是无效的还是其他错误导致它返回 invalid_grant?我怎样才能看到这部分?
我还浏览了有关创建在开始时链接的 OAuth2 服务器的 microsoft doc 示例,其中大部分内容都是基于该示例的。然而它没有帮助,因为它使用这个封装了所有内容的辅助方法:
var authorizationState = _webServerClient.ProcessUserAuthorization(Request);
所以这并没有告诉我太多,而且我也不确定上面的帮助器到底是如何工作的,因为它似乎将身份验证代码提交和令牌请求全部处理在一起。
您可以启用 OWIN 跟踪,以便可能获得更具描述性的错误消息。
将其添加到您的 app.config 中:
<system.diagnostics>
<switches>
<add name="Microsoft.Owin" value="All" />
</switches>
<trace autoflush="true" />
<sharedListeners>
<add name="file" type="System.Diagnostics.TextWriterTraceListener" initializeData="OWINtrace.log" />
</sharedListeners>
<sources>
<source name="Microsoft.Owin" switchName="Microsoft.Owin" switchType="System.Diagnostics.SourceSwitch">
<listeners>
<add name="file" />
</listeners>
</source>
</sources>
</system.diagnostics>
重现问题后,检查 OWINtrace.log。它应该位于您的可执行文件所在的文件夹中。
我刚刚遇到了同样的问题。无论我尝试什么,我都得到了
invalid_grant
。我还添加了所有带有断点的覆盖方法,以查看发生了什么并尝试调试问题,这实际上就是问题所在。
重写某些方法会破坏流程,我认为特别是
GrantResourceOwnerCredentials
。例如,当您重写此方法并调用其基本方法(就像我所做的那样)时,会告诉 OWIN 检查 password
参数,因为它似乎是在 AuthToken 流程之前执行的。
因此,如果不需要,请确保不要重写其他方法。
请求访问令牌时尝试使用
POST
请求。