【发布时间】:2020-11-22 01:17:02
【问题描述】:
我正在尝试使用 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。
一些建议?
【问题讨论】:
标签: node.js reactjs oauth jwt token