OAuth身份验证后如何向客户端发送jwt令牌?

时间:2020-08-01 11:18:05

标签: node.js reactjs oauth jwt token

我正在尝试使用GitHub OAuth对用户进行身份验证,对于普通用户,我正在使用jwt令牌。

在我的流程中,用户按下“使用github登录”按钮,然后按照Github文档操作-用户重定向到github网站以选择他的帐户。

这是我的客户端主要代码:

function SocialLogin(props) { 

    const githubAuth = async (e) =>{
        e.preventDefault()
        const githubOAuthURL = 'http://localhost:5000/api/oauth/github';
        let githubTab = window.open(githubOAuthURL, '_self');
        githubTab.focus();
    }  

  return (
    <div>
        <div className="right-box-inner"></div>
        <div className="wrap-buttons">
            <div className="signwith">Sign in with Social Network</div>
            <button onClick={githubAuth} className="social github"><i className="fab fa-github"></i>    Log in with Github</button>
        </div>
    </div>
  )
}

在我的服务器端,客户端要求的路由“ api / oauth / github”是:

router.get('/github', async (req,res) => {
    try{
    res.redirect('https://github.com/login/oauth/authorize/?client_id='+config.get('githubClientId'))
    }
    catch(err){
        console.log(err.response)
    }
})

因此,在执行https://github.com/login/oauth/authorize/?client_id='+config.get('githubClientId')之后,正确选择他的帐户,即我在githubaccount的我的应用程序设置中定义的回调URL,执行:

router.get('/github/callback', async (req,res) => {
    const {query} = req;
    const code = query.code;
    try{
        if(!code)
          return res.status(404).json({msg : 'Autherization failed'})
        else{
          const gitAuthDetails = {
            client_id: config.get('githubClientId'),
            client_secret: config.get('githubSecret'),
            code: code
            
        }
          const headers = {
            headers: {
                'Content-Type': 'application/json;charset=UTF-8',
                "Access-Control-Allow-Origin": "*",
            }
          }
          const response=await axios.post('https://github.com/login/oauth/access_token',gitAuthDetails,headers)
          access_token=response.data.split('=')[1].split('&')[0]

          const userResponse=await axios.get('https://api.github.com/user',{ headers: { Authorization: 'token ' + access_token } })

          //Lets asssume that i store here a new user to my DB with the all github details e.g username, email ...
          // and create a payload for jwt.
          // Now i want to generate new JWT for the new user , and problem is here. to where i need send my token? 
          // there is any function in my client side that listening and waiting for response.
            jwt.sign(
                payload,
                config.get('jwtSecret'),
                {expiresIn:360000},
                (err,token) => {
                    if(err) throw err;
                    //What i need to do with my token?
                    res.redirect('http://localhost:3000/dashboard')
                }
            );


        }
    }
    catch(err){
    console.log(err)
    res.redirect('http://localhost:3000/login')
    }
})

因此,正如我在代码中所描述的那样,我将令牌保留在此处,并且希望将其发送到客户端,并将令牌存储到localStorage。

一些建议?

1 个答案:

答案 0 :(得分:1)

将令牌存储在本地存储中不是最佳实践,因为它不安全。如果您有后端API,则最好使用OAuth 2.0授权代码流来确保访问令牌的安全性。

这将需要使用OAuth服务器(github)通过“登录”页面获取授权代码。然后,代码将传递到您的API,并在更受信任的“反向通道”(在API和OAuth服务器之间)交换,以获取用于身份验证的实际访问令牌。 OAuth服务器会知道您是谁,因为您将使用ClientId和ClientSecret来查询令牌(在javascript中存储ClientId和ClientSecret也是不安全的)

这意味着令牌将存储在您的服务器上,并且您将需要在API上提供端点以获取所需的数据。

Here是一段很好的解释视频。