gpt4 book ai didi

c# - 当 redirect_uri 包含查询字符串参数时,DotNetOpenAuth 拒绝访问 token 请求

转载 作者:太空宇宙 更新时间:2023-11-03 15:21:11 25 4
gpt4 key购买 nike

我正在使用 OWIN 中间件开发 OAuth v2 授权服务器,我正在尝试实现 OAuth2 Authorization Code Grant Flow但是我遇到了一个问题,如果 redirect_uri 包含查询字符串参数并且资源所有者必须进行身份验证,我的客户端会收到错误。

客户端能够请求身份验证代码,但是当它尝试将代码交换为访问 token 时,授权服务器会以“400 错误请求”的 HTTP 状态和以下响应正文进行响应。

{"error":"invalid_grant"}

如果 redirect_uri 不包含查询字符串参数,或者如果客户端在请求授权码之前删除了它们,那么它将完美地工作。如果资源所有者已经通过授权服务器进行身份验证,那么它也可以正常工作。

我的客户端正在使用 DotNetOpenAuth 并使用 Glimpse 我可以看到 redirect_uri 在授权码请求和访问 token 请求之间是一致的。

Glimpse 日志中的故障如下所示:

Prepared outgoing EndUserAuthorizationRequestC (2.0) message for http://localhost:61814/authorize:
client_id: localhost36618
redirect_uri: http://localhost:36618/login?redirectURL=%2FProfile
state: <state token>
scope: authentication
response_type: code

Processing incoming EndUserAuthorizationSuccessAuthCodeResponse (2.0) message:
code: <authorization code>
state: <state token>
redirectURL: /Profile

Prepared outgoing AccessTokenAuthorizationCodeRequestC (2.0) message for http://localhost:61814/token:
code: <authorization code>
redirect_uri: http://localhost:36618/login?redirectURL=%2FProfile
grant_type: authorization_code

http://localhost:61814/token returned 400 BadRequest: Bad Request

WebException from http://localhost:61814/token: {"error":"invalid_grant"}

但是,如果我从 redirect_uri 中省略查询字符串参数,它会起作用:

Prepared outgoing EndUserAuthorizationRequestC (2.0) message for http://localhost:61814/authorize:
client_id: localhost36618
redirect_uri: http://localhost:36618/Login
state: <state token>
scope: authentication
response_type: code

Processing incoming EndUserAuthorizationSuccessAuthCodeResponse (2.0) message:
code: <authorization code>
state: <state token>

Prepared outgoing AccessTokenAuthorizationCodeRequestC (2.0) message for http://localhost:61814/token:
code: <authorization code>
redirect_uri: http://localhost:36618/Login
grant_type: authorization_code

Processing incoming AccessTokenSuccessResponse (2.0) message:
access_token: <access token>
token_type: bearer
expires_in: 3599
refresh_token: <refresh token>

同样,如果我在使用客户端之前登录到授权服务器,它会起作用:

Prepared outgoing EndUserAuthorizationRequestC (2.0) message for http://localhost:61814/authorize:
client_id: localhost36618
redirect_uri: http://localhost:36618/login?redirectURL=%2FProfile
state: <state token>
scope: authentication
response_type: code

Processing incoming EndUserAuthorizationSuccessAuthCodeResponse (2.0) message:
code: <authorization code>
state: <state token>
redirectURL: /Profile

Prepared outgoing AccessTokenAuthorizationCodeRequestC (2.0) message for http://localhost:61814/token:
code: <authorization code>
redirect_uri: http://localhost:36618/login?redirectURL=%2FProfile
grant_type: authorization_code

Processing incoming AccessTokenSuccessResponse (2.0) message:
access_token: <access token>
token_type: bearer
expires_in: 3599
refresh_token: <refresh token>

OWIN 授权服务器的 OAuthAuthorizationServerProvider 在成功访问 token 授权代码请求时执行以下方法:

  • Provider.OnMatchEndpoint
  • Provider.OnValidateClientAuthentication
  • AuthorizationCodeProvider.Receive
  • Provider.OnValidateTokenRequest
  • Provider.OnGrantAuthorizationCode
  • Provider.OnTokenEndpoint
  • AccessTokenProvider.OnCreate
  • RefreshTokenProvider.OnCreate
  • Provider.OnTokenEndpointResponse

然而,不成功的访问 token 授权代码请求仅涉及以下方法:

  • Provider.OnMatchEndpoint
  • Provider.OnValidateClientAuthentication
  • AuthorizationCodeProvider.Receive

AuthorizationCodeProvider.OnReceive 具有以下实现:

private void ReceiveAuthenticationCode(AuthenticationTokenReceiveContext context)
{
try
{
string ticket = _repo.RemoveTicket(context.Token);
if (!string.IsNullOrEmpty(ticket))
{
context.DeserializeTicket(ticket);
}
}
catch (Exception ex)
{
var wrapper = new Exception("Receive Authentication Code Error", ex);
Logger.Error(wrapper);
}
}

在调试器中,我可以看到一个有效的 token ,从 _repo 成功检索到序列化票证,以及在方法完成之前上下文对象中的反序列化票证。不会抛出异常。成功请求和失败请求之间的流程看起来完全相同,所以我不清楚是什么失败了,并且诊断工具事件日志在请求处理期间没有显示任何异常,只是在 ReceiveAuthenticationCode 完成后退出的线程。

看起来问题出在我的测试客户端上,因为我能够使用 Brent Shaffer's OAuth2 Demo PHP live demo 重现完全相同的问题.

测试客户端基于 DotNetOpenAuth:

private static class Client
{
public const string Id = "username";
public const string Secret = "password";
}
private static class Paths
{
public const string AuthorizationServerBaseAddress = "http://localhost:61814";
public const string ResourceServerBaseAddress = "http://localhost:61814";
public const string AuthorizePath = "/authorize";
public const string TokenPath = "/token";
public const string ResourceServerApiMethodPath = "/getaccount";
}

public ActionResult Login(string code = "", string redirectURL = "/profile")
{
var authorizationServerUri = new Uri(Paths.AuthorizationServerBaseAddress);
var authorizationServer = new AuthorizationServerDescription
{
AuthorizationEndpoint = new Uri(authorizationServerUri, Paths.AuthorizePath),
TokenEndpoint = new Uri(authorizationServerUri, Paths.TokenPath)
};
var client = new WebServerClient(authorizationServer, Client.Id, Client.Secret);


if (!string.IsNullOrEmpty(code))
{
var apiResponse = null;
var authorizationState = client.ProcessUserAuthorization();

if (!string.IsNullOrEmpty(authorizationState?.AccessToken))
apiResponse = GetApiResponse(authorizationState, Paths.ResourceServerApiMethodPath);

if (apiResponse != null)
{
var identity = new ClaimsIdentity(new[] { new Claim("test", apiResponse),
new Claim(ClaimTypes.Role, "ResourceOwner")
}, "ApplicationCookie");

AuthMgr.SignIn(new AuthenticationProperties { IsPersistent = true }, identity);

return Redirect(redirectURL);
}
}
else
{
client.RequestUserAuthorization();
}

return View();
}

知道我使用 DotNetOpenAuth 可能做错了什么吗?为什么我在服务器端看不到无效请求?

最佳答案

我解决了。获取access_token不要使用webclient.ProcessUserAuthorization(Request)方法。

 using (var client = new HttpClient())
{
var uri = new Uri($"http://localhost:24728/ClientAuthorization?tourl={tourl}");

var httpContent = new FormUrlEncodedContent(new Dictionary<string, string>()
{
{"code", code},
{"redirect_uri", uri.AbsoluteUri},
{"grant_type","authorization_code"},
{"client_id", ClientStartupProfile.Client.ClientId},
{"client_secret", ClientStartupProfile.Client.Secret}
});

var response = await client.PostAsync(ClientStartupProfile.AuthorizationServer.TokenUri, httpContent);
var authorizationState = await response.Content.ReadAsAsync<AuthorizationState>();

//判断access_token 是否获取成功
if (!string.IsNullOrWhiteSpace(authorizationState.AccessToken))
Response.Cookies.Add(new System.Web.HttpCookie("access_token", authorizationState.AccessToken));

return Redirect(tourl);
}

关于c# - 当 redirect_uri 包含查询字符串参数时,DotNetOpenAuth 拒绝访问 token 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37329637/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com