OAuth2,使用 POST 然而...方法不允许?

OAuth2, Using POST and Yet... Method Not Allowed?

基本上,我正在尝试创建一个需要与 Discord API 交互以检索用户信息才能正常工作的网站。

为此,我使用了一个名为 Simple OAuth (https://github.com/lelylan/simple-oauth2) 的库,但无法使用它获取我的授权码 return 令牌。我查看了该库的一些源代码。它正在使用 POST,这似乎是出现 "Method Not Allowed" 错误时的主要问题。我正在关注授权代码流程示例,这是我的代码:

index.js

var express = require('express'),
    request = require('request');
var router = express.Router();
var config = require('../config.json');
var oauth2 = require('simple-oauth2').create(config.credentials);
var authorizationUri = oauth2.authorizationCode.authorizeURL({
    redirect_uri: config.redirect_uri,
    scope: config.scope,
    state: config.state
});
router.get('/login', function(req, res) {
    console.log(authorizationUri);
    res.redirect(authorizationUri);
});
router.get('/callback', function(req, res) {
    var code = req.query.code;
    var tokenConfig = {
        code: code
    };
    oauth2.authorizationCode.getToken(tokenConfig, function(err, result) {
        if (err) {
            console.error('Access Token Error', err.message);
            return res.json('Authentication failed');
        } 
        console.log('The resulting token:', result);
        var token = oauth2.acessToken.create(result);
        return res.status(200).json(token);
    });
});
module.exports = router;

根据示例,此代码块应该可以工作。 (如果您想知道,这是我的配置文件:)

config.json

{
    "credentials": {
        "client": {
            "id": "...",
            "secret": "..."
        },
        "auth": {
            "tokenHost": "https://discordapp.com/api",
            "authorizePath": "/oauth2/authorize",
            "tokenPath": "/oauth2/token",
            "revokePath": "/oauth2/token/revoke"
        }
    },
    "redirect_uri": ".../callback",
    "scope": "identify",
    "state": "..."
}

程序恢复状态和代码非常好,但是当我尝试POST它恢复以获取令牌时,我一直收到错误 405,方法不允许。

您收到 405 是因为您正在为令牌端点解析错误的 URL。您使用的库将令牌url 设置为:

const tokenUrl = url.resolve(config.auth.tokenHost, config.auth.tokenPath);

所以:

url.resolve('https://discordapp.com/api', '/oauth2/token')

将解析为:

https://discordapp.com/oauth2/token

这会给你一个 405 响应。我认为您只需要在 tokenHost 值的末尾添加一个 "/"

即将您的配置更改为:

    "auth": {
        "tokenHost": "https://discordapp.com/api/",
        "authorizePath": "/oauth2/authorize",
        "tokenPath": "/oauth2/token",
        "revokePath": "/oauth2/token/revoke"
    } 

或:

    "auth": {
        "tokenHost": "https://discordapp.com",
        "authorizePath": "/oauth2/authorize",
        "tokenPath": "/api/oauth2/token",
        "revokePath": "/api/oauth2/token/revoke"
    } 

这应该可以正确解析令牌 url。