gpt4 book ai didi

javascript - OAuth2,使用 POST 但...方法不允许?

转载 作者:太空宇宙 更新时间:2023-11-04 00:20:37 25 4
gpt4 key购买 nike

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

为此,我使用了一个名为 Simple OAuth ( https://github.com/lelylan/simple-oauth2 ) 的库,但无法获取授权代码以使用它返回 token 。我查看了该库的一些源代码。它使用 POST,这似乎是出现“不允许的方法”错误时的主要问题。我正在遵循授权代码流程示例,这是我的代码:

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": "..."
}

程序可以很好地恢复状态和代码,但是当我尝试将其发回以获取 token 时,我不断收到错误 405,方法不允许。

最佳答案

您收到 405 错误是因为您解析了 token 端点的错误 URL。您使用的库将 tokenurl 设置为:

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"
}

这样应该可以正确解析 token url。

关于javascript - OAuth2,使用 POST 但...方法不允许?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44685286/

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