[英]Getting session cookie data on initial page load following a redirect from a server (Node and React)
我正在嘗試構建令牌系統,以允許通過電子郵件鏈接進行身份驗證。 我認為可能有效的流程是...
單擊電子郵件鏈接(格式為site.com/login?token=hf74hf64&email=m@email.com)->服務器檢查令牌是否有效並且電子郵件已注冊->服務器使用會話cookie重定向到'/'->客戶端確認會話cookie並驗證用戶身份
最后一步是我遇到麻煩了。 如何從組件內部檢測到存在會話cookie?
我在我的React auth組件中想到了這樣的事情:
class AuthenticatedComponent extends Component {
componentWillMount() {
if (cookie) {
this.props.dispatch(authenticateUser())//.....
}
}
}
可能會完成這項工作,還是我需要對服務器進行單獨的fetch
並根據響應觸發分派?
我們為我們的應用實現了非常相似的方法。 為此,我們在Node中而不是實際組件中處理所有登錄。
server.js
// I abstracted the login functionality into one call since it's the same for us
var handleAuthRequest = function handleAuthRequest(auth_body, req, res, next) {
request ({
method: 'POST',
uri: Constants.API_LOGIN_URL,
body: auth_body,
json: true
}, (error, response, body) => {
if (response.statusCode === 200) {
// this makes a cookie with the response of the body (auth token)
ssoUtils.generateCookies(body, res)
// this redirects to the initial url, with the provided cookie.
// Assuming your router already doesn't allow certain components to be accessed
// without a cookie, it would work the same for the login_token auth too.
res.redirect(req.url)
}
else {
next();
}
})
}
// this needs to come before any other routes
app.use((req, res, next) => {
// check if login_token query string was provided
if (req.query.hasOwnProperty('login_token')) {
var {login_token} = req.query
// API call to server to validate token
var jwtToken = jwt.sign({
sub: login_token
}, Constants.API_JWT_SECRET)
// modify the redirect url to remove the token
let parsed = url.parse(req.url)
delete req.query['login_token']
let newUrl = parsed.pathname + '?' + qs.stringify(req.query)
req.url = newUrl
// call the generic login handler
return handleAuthRequest({link_token: jwtToken}, req, res, next)
}
假設您的服務器將從登錄中返回相同的響應或一個有效的鏈接令牌,那么這只會將調用重定向回現有的過程,因此不需要單獨的功能客戶端。 如您所見,我們還在JWT中對令牌進行簽名,以確保只有從我們的應用程序發送的令牌才能被服務器接受。
我們使用React Router來處理客戶端路由。 您的onEnter
檢查初始路線將如下所示。
routes.js
// token is passed in from our cookie by both the client and server
module.exports = function (token, userAgent, originalUrl) {
function isToken() {
return token !== undefined && token !== null;
}
function ifNoTokenRedirect(nextState, replaceState) {
// check if token is set from cookie
if (!isToken()) {
replaceState({ nextPathname: nextState.location.pathname}, '/signup? redirect=' + originalUrl.pathname);
}
}
return (
// the actual routes
)
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.