简体   繁体   English

如何在 node.js backEnd 和 angular 2 frontEnd 中使用 jwt 实现社交登录

[英]how to implement social logins using jwt in node.js backEnd and angular 2 frontEnd

how to implement the social login such as facebook and google authentication using Json Web token (jwt) ,same as Auth0 has implemented.如何使用 Json Web 令牌 (jwt) 实现社交登录,例如 facebook 和 google 身份验证,与 Auth0 已实现相同。 i am using node js as back end and angular 2 as front end.我使用 node js 作为后端,使用 angular 2 作为前端。

Perhaps I'm confused by your phrasing but facebook, google, and JWT are distinct, individual authentication strategies.也许我对你的措辞感到困惑,但 facebook、google 和 JWT 是截然不同的个人身份验证策略。

But check out passport.js it offers hundreds of authentication strategies:但是查看passport.js,它提供了数百种身份验证策略:

defined strategy: (this example uses 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);
    });
  });

also these are needed by passport:护照也需要这些:

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);
  });
}

add the middleware to your server:将中间件添加到您的服务器:

app.use(passport.initialize());
app.use(passport.session());
passport.serializeUser(ppt.serializeMongoUser);
passport.deserializeUser(ppt.deserializeMongoUser);
passport.use(ppt.jwtStrategy);

authenticate from a service in your app:从应用程序中的服务进行身份验证:

  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());
  }

call this function when you need to authenticate:当您需要进行身份验证时调用此函数:

*note the authHeaders(this.security) *注意authHeaders(this.security)

this.security is a subscription to the JWT token in my ngrx store, but you could also put it in localStorage . this.security是对我的ngrx商店中 JWT 令牌的订阅,但您也可以将它放在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 };
}

calling authenticate() will return {success: true} or {success: false}调用authenticate()将返回{success: true}{success: false}

Here is a little example I created to show the basics of socket.io security with JWT authentication.这是我创建的一个小示例,用于展示使用 JWT 身份验证的 socket.io 安全性基础知识。 The backend is nodeJS, socket.io, and express.后端是 nodeJS、socket.io 和 express。

In the long run you should use passport for user sessions but the below is good to see so you get the whole picture.从长远来看,您应该在用户会话中使用通行证,但下面的内容很好看,因此您可以全面了解。

Overview概述

When browsing to http://127.0.0.1:3001 , the express middleware socketAuthenticated will create a jwt based on the hard coated user credentials (should use passport sessions for real user info).当浏览到http://127.0.0.1:3001 时,快速中间件socketAuthenticated将根据硬涂层用户凭据创建一个 jwt(应该使用护照会话获取真实用户信息)。

This token is then passed to the server EJS view and used to establish a socket connection.然后将此令牌传递到服务器 EJS 视图并用于建立套接字连接。

  1. Create a new folder for the app and run npm install express socketio-jwt jsonwebtoken ejs-locals socket.io为应用程序创建一个新文件夹并运行npm install express socketio-jwt jsonwebtoken ejs-locals socket.io

  2. Create a "public" folder within the root folder and put the socket.io-client JS file inside (you can run bower install socket.io-client to get the js file)在根文件夹下创建一个“public”文件夹,把socket.io-client JS文件放在里面(你可以运行bower install socket.io-client来获取js文件)

  3. Create app.js file within the root folder with the following:使用以下内容在根文件夹中创建app.js文件:

     let express = require('express'), socketioJwt = require('socketio-jwt'), jwt = require('jsonwebtoken'), port = 3001 engine = require('ejs-locals'); let app = express(); let socketAuthenticated = (req, res, next) => { let token = jwt.sign({firstName:"jason", lastName:"owl"}, "secret", { expiresIn: 60*5 }); // assuming you have some user object in req res.token = token; // front end will use this token to authenticate its socket connection next(); }; app.engine('ejs', engine); app.set('view engine', 'ejs'); app.set('view options', {defaultLayout: 'layout'}); app.use(express.static('public')); app.use(socketAuthenticated); app.route('/') .get((req, res) => { console.log(`Server Passing Token: ${res.token} to client`); res.render('index', { jwt: res.token }); }); let server = require('http').Server(app); let io = require('socket.io')(server); // Setup socket server to use JWT io.set('authorization', socketioJwt.authorize({ secret: "secret", handshake: true })); io.of('/default').on('connection', (socket) => { socket.on('data', (newConfig) => { console.log('Data Event Recieved!'); }); }); server.listen(port); console.log(`\\Application: ${process.pid} Listening On Port: ${port}`);

4) Create a new folder called views and create a file called index.ejs : 4) 创建一个名为 views 的新文件夹并创建一个名为index.ejs的文件:

<script type="text/javascript" src="/socket.io.js"></script>
<script>

    var jwttoken = <%- JSON.stringify(jwt) %>;

    function connect_socket (token) {
      var socket = io.connect('/default', {
        query: 'token=' + token
      });
      return socket;
    }

    var socket = connect_socket(jwttoken);
    socket.emit('data');
</script>
  1. run node app.js and open the browser to localhost:3001.运行node app.js并打开浏览器到 localhost:3001。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用JWT从前端(Angular 4)将密钥传递到后端(node js) - How to pass secret key to backend(node js) from frontend(angular 4) using JWT 如何将Google oAuth与Node.js后端和Angular前端一起使用? - How to use Google oAuth with Node.js backend and Angular frontend? 可以将Angular 2 Dart前端与Node.js后端一起使用吗? - Is it possible to use an Angular 2 Dart frontend with a Node.js backend? 从Node.js后端将数据调用到Angular前端 - Call data to Angular FrontEnd from Node.js BackEnd 使用 Angular 生产后端 Node.js &amp; Express 和前端 - Production of Backend Node.js & Express and Frontend with Angular 用于后端和前端的 Angular 2 + Node JS - Angular 2 + Node JS for backend and frontend 如何从后端验证前端的管理员? (Node.js、Angular、Mongodb) - How can I verify admin in frontend from backend? (Node.js, Angular, Mongodb) 如何从后端获取角度数据并通过node.js发送给前端? - How get data with angular from the backend and send it with node.js for the frontend? 如何在没有前端的情况下使用 Postman 在 Node.js Express 后端服务器上测试 Passport JS Google OAuth - How to test Passport JS Google OAuth on Node.js Express backend server without a frontend using Postman 如何将数据从前端jQuery传递到后端node.js - How to pass data from frontend jQuery to backend node.js
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM