2017-06-21 22 views
1

基本上我试图创建一个网站,需要与Discord API接口来检索用户信息才能正常工作。OAuth2,使用POST和Yet ...方法不允许?

为此,我正在使用名为Simple OAuth的库(https://github.com/lelylan/simple-oauth2),并且无法让我的授权码返回使用它的令牌。我已经浏览了lib的一些源代码。并且它使用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": "..." 
} 

程序越来越状态和代码回到完全正常,但是当我尝试后回得到令牌我不断收到错误405,方法不允许。

回答

0

您正在获得405,因为您正在解析令牌端点的错误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" 
    } 

而且应该正确地解析令牌网址。