重定向不为oauth2创建授权代码

时间:2018-08-14 15:27:38

标签: node.js oauth-2.0

我正在尝试实施Oauth2代码授权流程。

我使用simple-oauth2 npm存储库创建一个节点js应用程序和Im。

基本上这是代码:

var credentials = {
    client: {
        id: '1yLCsmAfDF49nGmJLgDbHvB6bSca',
        secret: 'g2OKQ9isj2pcaextQdjx5xW3KoAa'
    },
    auth: {
        tokenPath: '/oauth/token',
        tokenHost: 'http://localhost:3000'
    }
};


var OAuth2;



// Initial call redirecting to the Auth Server
app.get('/auth', function(req, res) {

    // Initialize the OAuth2 Library
    OAuth2 = require('simple-oauth2').create(credentials);

    // Authorization oauth2 URI
    var authorizationUri = OAuth2.authorizationCode.authorizeURL({
        redirect_uri: 'http://localhost:3000/callback',
        scope: 'read+delete', // also can be an array of multiple scopes, ex. ['<scope1>, '<scope2>', '...']
        state: 'xcoiv98y2kd22vusuye3kch'
    });

    res.redirect(authorizationUri);




});


// Callback endpoint parsing the authorization token and asking for the access token
app.get('/callback', function(req, res) {
    var code = req.query.code;

    console.log("code" + code);
    OAuth2.AuthCode.getToken({
        code: code,
        redirect_uri: 'http://localhost:3000/callback'
    }, saveToken);

    function saveToken(error, result) {
        if (error) {
            console.log('Access Token Error', error.message, error);
            res.json({ 'Access Token Error': error.message });
        } else {
            console.log(result);
            token = OAuth2.AccessToken.create(result);
            req.session.token = result;
            console.log("YOU REACH THIS")
        }
    }



});

所以当我打电话时:

http://localhost:3000/auth

它重定向到:

http://localhost:3000/oauth/authorize?response_type=code&client_id=1yLCsmAfDF49nGmJLgDbHvB6bSca&redirect_uri=http%3A%2F%2Flocalhost%3A3000%2Fcallback&scope=read%2Bdelete&state=xcoiv98y2kd22vusuye3kch

这是正确的吗?据我了解,它应该重定向到类似:

http://localhost:3000/callback?code=kyaysdgflyasydfe

1 个答案:

答案 0 :(得分:0)

我完全误解了Oauth2自动授权代码流程,该代码必须在服务器端生成并将其返回给客户端。之后,您可以致电/ oauth / token