Ink*_*ing 12 authentication node.js jwt passport-facebook passport.js
到目前为止,我只处理了服务器呈现的应用程序,在用户通过用户名/密码或使用OAuth提供程序(Facebook等)登录后,服务器只需设置会话cookie,同时重定向到相关页面.
但是现在我正在尝试使用更"现代"的方法构建应用程序,在前端使用React并使用JSON API后端.显然,标准选择是使用JSON Web令牌进行身份验证,但是我无法弄清楚我是如何向客户端提供JWT的,因此它可以存储在会话/本地存储中或任何地方.
示例更好地说明:
用户点击link(/auth/facebook)即可通过Facebook登录
用户被重定向并显示Facebook登录表单和/或权限对话框(如有必要)
Facebook将用户重定向回/auth/facebook/callback授权代码,服务器将其交换为访问令牌和一些有关用户的信息
服务器使用info在DB中查找或创建用户,然后创建包含用户数据的相关子集的JWT(例如ID)
???
此时我只想让用户被重定向到React应用程序的主页面(让我们说/app)与JWT,所以前端可以接管.但是我不能想到一种(优雅的)方式来做到这一点而不会丢失JWT,除了将它放在redirect(/app?authtoken=...)的查询字符串中- 但是这将显示在地址栏中,直到我删除它手动使用replaceState()或其他什么,对我来说似乎有点奇怪.
真的我只是想知道这通常是怎么做的,我几乎可以肯定我在这里遗漏了一些东西.服务器是Node(Koa with Passport),如果有帮助的话.
编辑:要清楚,我问的是在使用Passport 进行OAuth重定向流之后,为客户端提供令牌(因此可以保存)的最佳方法是什么.
小智 9
我最近遇到了同样的问题,而且,没有在这里或其他地方找到解决方案,用我深入的想法写了这篇博客文章.
TL; DR:我想出了在OAuth登录/重定向后将JWT发送到客户端的3种可能方法:
<script>标记:
localStorage(由于使用JWT登录基本上等同于"将JWT保存到" localStorage,我最喜欢的选项是#3,但我可能还有一些缺点,我没有考虑过.我很想听听其他人的想法.)
希望有所帮助!
Gna*_*esh -2
当您从任何护照身份验证站点获取令牌时,您必须将该令牌保存在浏览器的localStorage. Dispatch 是 Redux 的中间件。dispatch如果您不在应用程序中使用 redux,请忽略。你可以setState在这里使用(没有 redux 有点奇怪)。
客户端:
这是我的类似 API,它返回 token。
保存代币
axios.post(`${ROOT_URL}/api/signin`, { email, password })
.then(response => {
dispatch({ type: AUTH_USER }); //setting state (Redux's Style)
localStorage.setItem('token', response.data.token); //saving token
browserHistory.push('/home'); //pushes back the user after storing token
})
.catch(error => {
var ERROR_DATA;
try{
ERROR_DATA = JSON.parse(error.response.request.response).error;
}
catch(error) {
ERROR_DATA = 'SOMETHING WENT WRONG';
}
dispatch(authError(ERROR_DATA)); //throw error (Redux's Style)
});
Run Code Online (Sandbox Code Playgroud)
因此,当您发出一些经过身份验证的请求时,您必须以这种形式将令牌附加到请求中。
经过身份验证的请求
axios.get(`${ROOT_URL}/api/blog/${blogId}`, {
headers: { authorization: localStorage.getItem('token') }
//take the token from localStorage and put it on headers ('authorization is my own header')
})
.then(response => {
dispatch({
type: FETCH_BLOG,
payload: response.data
});
})
.catch(error => {
console.log(error);
});
Run Code Online (Sandbox Code Playgroud)
这是我的index.js: 每次都会检查令牌,因此即使浏览器刷新,您仍然可以设置状态。
检查用户是否经过身份验证
const token = localStorage.getItem('token');
if (token) {
store.dispatch({ type: AUTH_USER })
}
ReactDOM.render(
<Provider store={store}>
<Router history={browserHistory}>
<Route path="/" component={App}>
..
..
..
<Route path="/blog/:blogid" component={RequireAuth(Blog)} />
//ignore this requireAuth - that's another component, checks if a user is authenticated. if not pushes to the index route
</Route>
</Router>
</Provider>
, document.querySelector('.container'));
Run Code Online (Sandbox Code Playgroud)
调度操作所做的只是设置状态。
我的减速器文件(仅限 Redux),否则您可以在索引路由文件中使用 setState() 来向整个应用程序提供状态。每次调用调度时,它都会运行一个类似的减速器文件,这样设置状态。
设置状态
import { AUTH_USER, UNAUTH_USER, AUTH_ERROR } from '../actions/types';
export default function(state = {}, action) {
switch(action.type) {
case AUTH_USER:
return { ...state, error: '', authenticated: true };
case UNAUTH_USER:
return { ...state, error: '', authenticated: false };
case AUTH_ERROR:
return { ...state, error: action.payload };
}
return state;
} //you can skip this and use setState() in your index route instead
Run Code Online (Sandbox Code Playgroud)
从 localStorage 中删除令牌以注销。
注意:使用任何不同的名称,而不是token将令牌保存在浏览器的localStorage
服务器端:
考虑您的护照服务档案。您必须设置标题搜索。这是Passport.js
const passport = require('passport');
const ExtractJwt = require('passport-jwt').ExtractJwt;
const JwtStrategy = require('passport-jwt').Strategy;
..
..
..
..
const jwtOptions = {
jwtFromRequest: ExtractJwt.fromHeader('authorization'), //client's side must specify this header
secretOrKey: config.secret
};
const JWTVerify = new JwtStrategy(jwtOptions, (payload, done) => {
User.findById(payload._id, (err, user) => {
if (err) { done(err, null); }
if (user) {
done(null, user);
} else {
done(null, false);
}
});
});
passport.use(JWTVerify);
Run Code Online (Sandbox Code Playgroud)
在我的router.js中
const passportService = require('./services/passport');
const requireAuthentication = passport.authenticate('jwt', { session: false });
..
..
..
//for example the api router the above react action used
app.get('/api/blog/:blogId', requireAuthentication, BlogController.getBlog);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5802 次 |
| 最近记录: |