Я пытаюсь аутентифицировать пользователя с помощью 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 ') и правильного выбора своей учетной записи URL-адрес обратного вызова, как я определил в настройках моего приложения на githubaccount, выполняется:
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.
какие-то советы?