如何实现facebook、google等社交登录认证 使用 Json Web token (jwt),与 Auth0 的实现相同。我使用 Node js 作为后端,使用 Angular 2 作为前端。
最佳答案
也许我对您的措辞感到困惑,但 facebook、google 和 JWT 是不同的、单独的身份验证策略。
但请查看passport.js它提供了数百种身份验证策略:
定义的策略:(本例使用mongoose)
const jwtOptions = {
jwtFromRequest: PJWT.ExtractJwt.fromAuthHeader(),
secretOrKey: SECRET, // externally defined private encryption key
}
export const jwtStrategy = new PJWT.Strategy(jwtOptions,
function (jwt_payload, done) {
MongoUser.findOne({ email: jwt_payload.email }, function (err, user) { // presumes the user's email is in the jwt
if (err) return done(err, false);
if (user) return done(null, user);
else return done(null, false);
});
});
护照还需要这些:
type Done = (err: any, user?: {}) => void;
export const serializeMongoUser = function (user: UserDoc, done: Done) {
done(null, user._id);
}
export const deserializeMongoUser = function (_id: any, done: Done) {
MongoUser.findById(_id, function (err, user) {
done(err, user);
});
}
将中间件添加到您的服务器:
app.use(passport.initialize());
app.use(passport.session());
passport.serializeUser(ppt.serializeMongoUser);
passport.deserializeUser(ppt.deserializeMongoUser);
passport.use(ppt.jwtStrategy);
从应用中的服务进行身份验证:
authenticate(): Observable<any> {
if (!this.security.jwt) return Observable.of({sucess: false})
return this.http.get('/api/authenticate', authHeaders(this.security))
.map(res => res.json());
}
当需要验证时调用此函数:
*注意authHeaders(this.security)
this.security
是对我的 ngrx
商店中 JWT token 的订阅,但您也可以将其放在 localStorage 中.
export function authHeaders(security: Security) {
const headers = new Headers();
headers.append('Content-Type', 'application/json; charset=utf-8');
headers.append('Authorization', `JWT ${security.jwt}`);
return { headers };
}
调用authenticate()
将返回{success: true}
或{success: false}
关于node.js - 如何在node.js后端和Angular 2前端中使用jwt实现社交登录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44251819/