【发布时间】:2016-06-14 04:11:23
【问题描述】:
我的问题
我正在关注 react-router 存储库中的 auth-flow example 进行客户端身份验证。
除了令牌过期或无效的情况外,一切都很好。如果本地存储中没有令牌,则用户将被重定向到登录页面就好了。但是,如果本地存储中有令牌(即使该令牌在服务器上未验证),则重定向不起作用。
感谢您的帮助
代码
index.jsx
import React from 'react'
import ReactDom from 'react-dom'
import { Router, Route, IndexRoute, hashHistory } from 'react-router'
import App from './components/App'
import Request from './components/Request'
import Login from './components/Login'
import Dashbord from './components/Dashboard'
import AddFeature from './components/AddFeature'
import styles from './styles-common/layout.css'
import auth from './auth'
const appSection = document.createElement('div')
appSection.id = 'root'
document.body.insertBefore(appSection, document.body.firstChild);
function requireAuth(nextState, replace) {
if (!auth.loggedIn()) {
replace({
pathname: '/login',
state: { nextPathname: nextState.location.pathname }
})
}
}
ReactDom.render((
<Router history={hashHistory}>
<Route path="/" component={App} onEnter={requireAuth}>
<IndexRoute component={Dashbord} />
<Route path="request/:id" component={Request} />
<Route path="/new-request" component={AddFeature} />
</Route>
<Route path="/login" component={Login} />
</Router>
), appSection)
App.jsx
import React from 'react'
import Header from '../Header'
import DropDownMenu from '../DropDownMenu'
import styles from './styles.css'
export default class App extends React.Component {
render() {
return (
<div>
<Header>
<DropDownMenu />
</Header>
<div className={styles.contentContainer}>
<main className={styles.content}>
{this.props.children}
</main>
</div>
</div>
)
}
}
auth.js
import request from 'superagent'
export default {
login(email, pass, cb) {
cb = arguments[arguments.length - 1]
if (localStorage.token) {
if (cb) cb(true)
this.onChange(true)
return
}
authenticate(email, pass, (res) => {
if (res.authenticated) {
localStorage.token = res.token
localStorage.user_firstname = res.user_firstname
localStorage.user_lastname = res.user_lastname
localStorage.user_id = res.user_id
if (cb) cb(true)
this.onChange(true)
} else {
if (cb) cb(false)
this.onChange(false)
}
})
},
getToken() {
return localStorage.token
},
logout(cb) {
delete localStorage.token
if (cb) cb()
this.onChange(false)
},
loggedIn() {
return !!localStorage.token
},
onChange() {}
}
function authenticate (email, pass, callback) {
let body = {email: email, password: pass}
request
.post('api/auth')
.send(body)
.end((err, res) => {
let result = JSON.parse(res.text)
if (result.success) {
callback({
authenticated: true,
user_id: result.user_id,
user_firstname: result.user_firstname,
user_lastname: result.user_lastname,
token: result.token
})
} else {
callback({ authenticated: false} )
}
})
}
【问题讨论】:
-
我能够解决这个问题。我刚刚意识到 auth.js 只在登录期间访问服务器进行授权,而不是在任何其他客户端事件期间。我将在当天晚些时候处理这个问题,我会发布我的代码以防万一这可以帮助其他人。
标签: authentication reactjs client-side react-router