当前位置: 首页 > 工具软件 > Passport.js > 使用案例 >

oauth入门_使用Passport.js的OAuth快速入门

皇甫夕
2023-12-01

oauth入门

什么是OAuth? (What is OAuth?)

OAuth (Open Authorization) is an authorization protocol. A third party application can use it to access user data from a site (like Google or Twitter) without revealing their password. Sites like Quora, Medium, AirBnb and many others offer authentication using OAuth.

OAuth(开放授权)是一种授权协议。 第三方应用程序可以使用它来访问站点(例如Google或Twitter)上的用户数据,而无需透露其密码。 Quora,Medium,AirBnb等网站都使用OAuth提供身份验证。

OAuth really makes our lives simpler by eliminating the need to remember the password of every account you create on almost any site. You just have to remember your OAuth provider’s main account password.

OAuth消除了记住几乎在任何站点上创建的每个帐户的密码的需求,确实使我们的生活变得更加简单。 您只需要记住OAuth提供商的主帐户密码即可。

什么是Passport.js? (What is Passport.js?)

Passport is a middleware which implements authentication on Express-based web applications. It provides over 500+ strategies. What are these strategies? Strategies are used to authenticate requests. Each strategy has its own npm package (such as passport-twitter, passport-google-oauth20). A strategy must be configured before usage.

Passport是一种中间件,可在基于Express的Web应用程序上实现身份验证。 它提供了500多种策略。 这些策略是什么? 策略用于验证请求。 每个策略都有其自己的npm软件包(例如passport-twitterpassport-google-oauth20 )。 使用前必须配置策略。

为什么要使用Passport.js? (Why use Passport.js?)

Here are six reasons stating why you should use Passport:

以下是说明为什么应使用Passport的六个原因:

  • It is lightweight

    轻巧
  • Easily configurable

    易于配置
  • Supports persistent sessions

    支持持久会话
  • Offers OAuth

    提供OAuth
  • Provides separate modules for each strategy

    为每种策略提供单独的模块
  • Gives you the ability to implement custom strategies

    使您能够实施自定义策略

让我们来构建一些东西 (Let’s build something)

To get started, we need to install passport from NPM:

首先,我们需要从NPM安装护照:

npm install passport

We are going to build a simple app which grants the user access to a secret route only if they log in. I’m going to be using the passport-google-oauth20 strategy in this tutorial. Feel free to use any other strategy you prefer, but make sure to check the docs to see how it is configured.

我们将构建一个简单的应用程序,该应用程序仅在用户登录时才授予用户访问秘密路线的权限。在本教程中,我将使用passport-google-oauth20策略。 随意使用您喜欢的任何其他策略,但是请确保检查文档以了解其配置。

Before continuing, we need a clientID and clientSecret. To get one, head over to https://console.developers.google.com and create a new project. Then go to Enable APIs and Services and enable the Google+ API. Select the API and click on create credentials.

在继续之前,我们需要一个clientID和clientSecret。 要获得一个,请转到https://console.developers.google.com并创建一个新项目。 然后转到启用API和服务并启用Google+ API。 选择API,然后单击创建凭据。

Fill out the form and use the same callback URL on both the form and on your file. Make sure to read the comments on the code to figure out how everything fits together.

填写表单,并在表单和文件上使用相同的回调URL。 确保阅读代码上的注释,以找出所有内容如何组合在一起。

app.js

app.js

// Required dependencies 
const express = require('express');
const app = express();
const passport = require('passport');
const GoogleStrategy = require('passport-google-oauth20');
const cookieSession = require('cookie-session');

// cookieSession config
app.use(cookieSession({
    maxAge: 24 * 60 * 60 * 1000, // One day in milliseconds
    keys: ['randomstringhere']
}));

app.use(passport.initialize()); // Used to initialize passport
app.use(passport.session()); // Used to persist login sessions

// Strategy config
passport.use(new GoogleStrategy({
        clientID: 'YOUR_CLIENTID_HERE',
        clientSecret: 'YOUR_CLIENT_SECRET_HERE',
        callbackURL: 'http://localhost:8000/auth/google/callback'
    },
    (accessToken, refreshToken, profile, done) => {
        done(null, profile); // passes the profile data to serializeUser
    }
));

// Used to stuff a piece of information into a cookie
passport.serializeUser((user, done) => {
    done(null, user);
});

// Used to decode the received cookie and persist session
passport.deserializeUser((user, done) => {
    done(null, user);
});

// Middleware to check if the user is authenticated
function isUserAuthenticated(req, res, next) {
    if (req.user) {
        next();
    } else {
        res.send('You must login!');
    }
}

// Routes
app.get('/', (req, res) => {
    res.render('index.ejs');
});

// passport.authenticate middleware is used here to authenticate the request
app.get('/auth/google', passport.authenticate('google', {
    scope: ['profile'] // Used to specify the required data
}));

// The middleware receives the data from Google and runs the function on Strategy config
app.get('/auth/google/callback', passport.authenticate('google'), (req, res) => {
    res.redirect('/secret');
});

// Secret route
app.get('/secret', isUserAuthenticated, (req, res) => {
    res.send('You have reached the secret route');
});

// Logout route
app.get('/logout', (req, res) => {
    req.logout(); 
    res.redirect('/');
});

app.listen(8000, () => {
    console.log('Server Started!');
});

index.ejs

index.ejs

<ul>
    <li><a href="/auth/google">Login</a></li>
    <li><a href="/secret">Secret</a></li>
    <li><a href="/logout">Logout</a></li>
</ul>

As you can see, we’ve created a /secret route, and only grant access to it if the user is authenticated. To verify whether the user is authenticated, we’ve created a middleware which checks if the request has the user object in it. Finally, to log out we used the req.logout() method provided by passport to clear the session.

如您所见,我们已经创建了一个/secret路由,并且仅在用户通过身份验证后才授予对其的访问权限。 为了验证用户是否已通过身份验证,我们创建了一个中间件,用于检查请求中是否包含用户对象。 最后,要注销,我们使用了护照提供的req.logout()方法来清除会话。

这是一些资源,以了解有关护照的更多信息 (Here are some resources to learn more about passport)

Official documentation of Passport.jsSimple, unobtrusive authentication for Node.jswww.passportjs.org

Passport.js的官方文档 Node.js的简单,无干扰的身份验证 www.passportjs.org

结论 (Conclusion)

We only saw one strategy here. There are 500+ more. I highly recommend that you skim through Passport’s official documentation and find out what else they offer. Thank you for taking your time to read this. Feel free to connect with me on LinkedIn, Twitter and GitHub. I wish you good luck!

我们在这里只看到一种策略。 还有500多个。 我强烈建议您浏览Passport的官方文档,并了解他们还提供什么。 感谢您抽出宝贵的时间阅读本文。 随时通过LinkedInTwitterGitHub与我联系。 祝你好运!

上一篇文章 (Previous article)

A quick introduction to Material Design using MaterializeWhat is Material Design?medium.freecodecamp.org

使用Materialize快速介绍材料设计 什么是材料设计? medium.freecodecamp.org

翻译自: https://www.freecodecamp.org/news/a-quick-introduction-to-oauth-using-passport-js-65ea5b621a/

oauth入门

 类似资料: