无法通过授权码交易访问令牌

Cannot trade access token from authorization code

我目前正在学习 .Net 的 OAuth2 服务器,似乎 OWIN 提供了一个很好的解决方法来轻松实现这种服务器。

我试过微软的例子:https://docs.microsoft.com/en-us/aspnet/aspnet/overview/owin-and-katana/owin-oauth-20-authorization-server

看起来示例效果很好,但是当我尝试通过 PostMan 为访问令牌交换授权代码时失败了。

我使用 POST 方法和 header Content-Type=application/x-www-form-urlencoded 以及请求中的以下参数 body:

grant_type=authorization_code
client_id=7890ab
redirect_uri=http%3A%2F%2Flocalhost%3A50150%2Fcallback%2F
code=d7a91a351ffa4764a22ef3628c94d495443e0043bfc9405b9f1c5113a234a23d
client_secret=7890ab

我通过调试器进行跟踪,发现进程传递了事件 ReceiveAuthenticationCode,票据应该是 settled/Deserialized。

然而无论我怎么尝试,结果总是invalid_grant。


我查看了原始示例,发现使用 WebServerClient 成功获得了访问令牌。但由于我的目的是为不限于.Net 客户端提供服务,所以我必须确保我可以在没有库的情况下检索令牌。

有人有什么建议吗?


更新 1

我已将 clientID 和 clientSecret 连接到 7890ab:7890ab 并将字符串编码为 base 64 字符串 Nzg5MGFiOjc4OTBhYg== 然后附加到 header Authorization=Basic Nzg5MGFiOjc4OTBhYg== 没有任何改变

经过2周的尝试,我发现我在基础部分的错误,我希望能节省我后面遇到这个问题的程序员的时间;

当通过 HTTP GET 方法获得 Authorization Code 时,redirect_uri 的值应该被编码(例如 http%3A%2F%2Flocalhost%3A50150%2Fcallback%2F

但是代码获取后,要用HTTP POST方法交易Access Token,请求体中redirect_uri的值不应该 被编码,值应该是 http://localhost:50150/callback/ 这是部分原因 invalid_grand return.

Notes: the value of redirect_uri should be same between the requests, that means if the uri is leading with http:// or ends with a / when asking for the Authorization Code, these parts should also present when asking for the Access Token

Reference: the following demo is way clearer than MSDN in my opinion https://github.com/yuezhongxin/OAuth2.Demo