[英]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.从长远来看,您应该在用户会话中使用通行证,但下面的内容很好看,因此您可以全面了解。
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 视图并用于建立套接字连接。
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
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文件)
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>
node app.js
and open the browser to localhost:3001.node app.js
并打开浏览器到 localhost:3001。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.