erui _ eruie 002使用Passport.js和OpenID Connect构建安全的节点身份验证
Ťhis article was originally published on the Okta developer blog. Thank you for supporting the partners who make SitePoint possible.
Building local or social login in Node can be simple with Passport.js. There are over 500 strategies already built that make it easy to wire up identity providers. But what do you do if your identity provider doesn’t already have a pre-built strategy? Do you have to build all that stuff yourself? Absolutely not! You can use generic strategies for Passport.js that make it easy to use your provider of choice without having to write all the plumbing yourself. In this tutorial we’ll walk through how to use my identity provider of choice (Okta) with the generic
passport-openidconnectpackage to build secure Node authentication and user management!
- Authenticate and authorize your users
- Store data about your users
- Perform password-based and social login
- Secure your application with multi-factor authentication
- 一个nd much more! Check out our product documentation
In short: we make user account management a lot easier, more secure, and more scalable than what you’re probably used to.
Sound amazing? Register for a free developer account, and when you’re done, come on back so we can learn more about building secure authentication in Node.
Start by installing the Express application generator if you don’t already have it installed.
npm install express-generator -g
Then use the
expresscommand to scaffold a base Node and Express application.
express -e --git passport-oidc-example
change directory: $ cd passport-oidc-example install dependencies: $ npm install run the app: $ DEBUG=passport-oidc-example:* npm startGo ahead and change into the new directory, and install the dependencies. I use Visual Studio Code for my Node development which has great support for writing and debugging Node applications. It works on all platforms and is completely free. Running the application with a debugger attached is as easy as hitting the
F5key!
Once you have VS Code installed, you can open the project from the command line using the
codecommand.
code .
Now, run the app by hitting the
F5key and it will start the Node debugger in the output window. Open a browser to http://localhost:3000 and make sure your base application is running.
- 护照护照-openidconnect表达会议
npm install passport@0.4.0 passport-openidconnect@0.0.2 express-session@1.15.6 --save
Once those are installed, open the
app.jsfile in the root folder of the application and add Passport.js to the requirements so that the top section of the file looks like:
var createError = require('http-errors'); var express = require('express'); var path = require('path'); var cookieParser = require('cookie-parser'); var logger = require('morgan'); var session = require('express-session'); var passport = require('passport'); var OidcStrategy = require('passport-openidconnect').Strategy;
Passport relies on
express-sessionto store the user information once the user has logged in. To configure it, right below the line that reads:
app.use(express.static(path.join(__dirname, 'public')));
app.use(session({ secret: 'MyVoiceIsMyPassportVerifyMe', resave: false, saveUninitialized: true }));
app.use(passport.initialize()); app.use(passport.session());If you don’t already have an account (and didn’t create one at the start of this tutorial), it’s time to sign up for one! Once you’re logged into your Okta dashboard, click on the Applications menu item and click Add Application. From the wizard, choose Web and click Next.
Now you’ll configure Passport.js to use Okta as your Identity Provider (IdP). To do this, right below the Passport.js configuration from the last section, tell passport to use the
OidcStrategycreated in the requirements.
// set up passport passport.use('oidc', new OidcStrategy({ issuer: 'https://{yourOktaDomain}/oauth2/default', authorizationURL: 'https://{yourOktaDomain}/oauth2/default/v1/authorize', tokenURL: 'https://{yourOktaDomain}/oauth2/default/v1/token', userInfoURL: 'https://{yourOktaDomain}/oauth2/default/v1/userinfo', clientID: '{ClientID}', clientSecret: '{ClientSecret}', callbackURL: 'http://localhost:3000/authorization-code/callback', scope: 'openid profile' }, (issuer, sub, profile, accessToken, refreshToken, done) => { return done(null, profile); }));
The code above sets the name of the strategy as ‘oidc’ and set all the URLs that the strategy needs to know to pull off the authorization code flow for OpenID Connect. The issuer is the URL for your authorization server that was created for you when you signed up for an Okta developer account. You can view it by clicking on API in your Okta dashboard and choosing the Authorization Servers tab. To find the
authorizationURL,
tokenURLand
userInfoURLsettings, you can click on the default authorization server and view its settings. There is a Metadata URI setting that, by clicking on the link, will show you the
.well-knowndocument. This document tells anyone using this authorization server about the information and endpoints it can provide.
The last argument is a function that pushes the profile object returned from the authentication call into
req.userso that you can use it in the route handlers. You could manipulate the object you pass in so that it has other information, or save/update the user in your database.
passport.serializeUser((user, next) => { next(null, user); }); passport.deserializeUser((obj, next) => { next(null, obj); });The last thing that Passport.js needs is two endpoints in your application: one that kicks off the login flow and one that handles the callback from the OpenID Connect provider. You can put these two routes right below the
app.use()method for the index and user routers.
app.use('/login', passport.authenticate('oidc')); app.use('/authorization-code/callback', passport.authenticate('oidc', { failureRedirect: '/error' }), (req, res) => { res.redirect('/'); } );
app.use('/profile', (req, res) => { res.render('profile', { title: 'Express', user: req.user }); });
<!DOCTYPE html> <html> <head> <title><%= title %></title> <link rel='stylesheet' href='/stylesheets/style.css' /> </head> <body> <h1><%= title %></h1> <p>Welcome <%= user.displayName %>!</p> </body> </html>
<!DOCTYPE html> <html> <head> <title><%= title %></title> <link rel='stylesheet' href='/stylesheets/style.css' /> </head> <body> <h1><%= title %></h1> <p>Welcome to <%= title %></p> <a href="/login">Log In</a> </body> </html>
function ensureLoggedIn(req, res, next) { if (req.isAuthenticated()) { return next(); } res.redirect('/login') }This function checks the request’s
isAuthenticated()method and passes the request on to the next handler if the user is logged in. If not, it redirects the user to the login page which with kick off the login process.
app.use('/profile', ensureLoggedIn, (req, res) => { res.render('profile', { title: 'Express', user: req.user }); });
app.get('/logout', (req, res) => { req.logout(); req.session.destroy(); res.redirect('/'); });It’s just that simple. This route handler calls the
logout()method on the incoming request, destroys the session, and redirects the user to the homepage.
Can’t get enough Node? Check out our quickstarts for Node and other cool posts from the Okta Developer blog, like our post on simple Node authentication, and my post on user registration with Node and React.
As always, feel free to ping us on Twitter @oktadev or leave comments below, and don’t forget to check out our YouTube channel!
from: https://www.sitepoint.com//build-secure-node-authentication-with-passport-js-openid-connect/
dangzhuang7815 原创文章 0获赞 0访问量 308 关注 私信- erui _ eruie 002如何使用节点创建和验证JWT
- IdentityServer4 使用OpenID Connect添加用户身份验证
- IdentityServer4 使用OpenID Connect添加用户身份验证
- 【转载】IdentityServer4 使用OpenID Connect添加用户身份验证
- erui _ eruie 002如何使用TypeScript通过Express构建节点API
- IdentityServer4 使用OpenID Connect添加用户身份验证
- js中会使用到的一种表单遍历验证的方法,访问当前节点的兄弟节点
- 使用OAuth 2.0构建React Native应用并进行身份验证
- MySQL 4.1 +使用旧的不安全的身份验证
- 使用React,GraphQL和用户身份验证构建运行状况跟踪应用
- 构建安全的数据访问-身份验证(四)
- erui _ eruie 002使用Angular 7中的所有新功能和值得关注的功能构建应用程序
- erui _ eruie 002使用Angular和Node构建基本的CRUD应用
- erui _ eruie 002使用Express在Node中构建您的第一个路由器
- 使用Email的身份验证(OpenID)、电子支付,及Email的链接处理
- erui _ eruie 002使用Go和Vue构建单页应用
- 使用配制文件定制身份验证和基于角色的安全
- 使用配制文件定制身份验证和基于角色的安全
- 使用 IBM AIX V5.3 在 Solaris 10 中实现安全的 Kerberos 化身份验证
- 使用配制文件定制身份验证和基于角色的安全