[英]How can i send jwt token to client after OAuth autherization?
我正在嘗試使用 GitHub OAuth 對用戶進行身份驗證,對於普通用戶,我正在使用 jwt 令牌。
在我的流程中,用戶按下“使用 github 登錄”按鈕,然后按照 Github 文檔 - 用戶重定向到 github web 以選擇他的帳戶。
所以這是我客戶端的主要代碼:
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。
一些建議?
將令牌存儲在本地存儲中不是最佳做法,因為它不安全。 如果你有后端API,最好使用OAuth 2.0 授權碼流來保證訪問令牌的安全。
這需要使用 OAuth 服務器 (github) 通過登錄頁面獲取授權碼。 然后將代碼傳遞到您的 API 並在更受信任的“反向通道”(在您的 API 和 OAuth 服務器之間)交換用於身份驗證的實際訪問令牌。 OAuth 服務器將知道您是誰,因為您將使用您的 ClientId 和 ClientSecret 來查詢令牌(在 javascript 中存儲 ClientId 和 ClientSecret 也是不安全的)
這意味着令牌將存儲在您的服務器上,您需要在 API 上提供端點以獲取所需的數據。
這是一個視頻,它很好地解釋了這一點。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.