node.js - 如何在node.js后端和Angular 2前端中使用jwt实现社交登录

标签 node.js angular jwt

如何实现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/

相关文章:

javascript - C - 使用 libcurl 的 http post 请求

node.js - 无法在浏览器中使用 Nodejs 从网站连接到 websocket

javascript - 在 Node REPL 中同步等待 Promise

javascript - 在 node.js 中使用 require() 出现奇怪的 JSON 解析错误

angular - Angular 中两个以上领域的双向绑定(bind)

php - JWTRefreshTokenBundle : Name or service not known

apache - 将 Angular 2 部署到 Apache 服务器

javascript - 我应该使用守卫而不是解析器来保存 Angular 2 中的渲染周期吗?

angular - 当 token 在 Angular 4中过期时如何重定向到注销

php - Azure Active Directory B2C - 用于登录/注册和密码重置的用户流(策略)