2017-06-21 163 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" 
    } 

而且應該正確地解析令牌網址。