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

oauth2.js_如何使用Passport.js和ReactJS设置Twitter OAuth

越景天
2023-12-01

oauth2.js

by Leanne Zhang

张蕾妮

如何使用Passport.js和ReactJS设置Twitter OAuth (How to set up Twitter OAuth using Passport.js and ReactJS)

入门 (Getting started)

This is a simple authentication tutorial for building a Twitter Authentication web application using Passport API. It’s a side project that I worked on for education purposes.

这是一个简单的身份验证教程,用于使用Passport API构建Twitter身份验证Web应用程序。 这是我出于教育目的而进行的一项辅助项目。

I broke down this tutorial into two parts. The first part focuses on building authentication routes in the backend. The second part focuses on building UI components in the front-end using React.

我将本教程分为两部分。 第一部分着重于在后端中构建认证路由。 第二部分重点介绍使用React在前端中构建UI组件。

科技栈 (Tech Stack)

我们要建造什么? (What are we going to build?)

  • User clicks on login button which redirects to Twitter OAuth authentication page.

    用户单击登录按钮,该按钮将重定向到Twitter OAuth身份验证页面。
  • Once the OAuth has been successfully authenticated to Twitter, the user will be redirected back to the web application home page.

    OAuth成功通过Twitter认证后,用户将被重定向回Web应用程序主页。

Passport.js. offers authentication APIs to other OAuth service providers such as Google and Facebook. As an example, I chose to use Twitter as an OAuth service provider.

Passport.js。 向其他OAuth服务提供商(例如Google和Facebook)提供身份验证API。 例如,我选择使用Twitter作为OAuth服务提供商。

什么是OAuth? (What is OAuth?)

Open Authorization is a standard for granting your web application access to a third-party sign-in service like Twitter, Facebook, or Google, which returns an OAuth token. An OAuth Token is a credential that can be used by an application to access an external service API.

开放授权是一种标准,用于授予您的Web应用程序访问第三方登录服务(如Twitter,Facebook或Google)的权限,该服务会返回OAuth令牌。 OAuth令牌是一种凭证,应用程序可以使用它来访问外部服务API。

In this project, I'm using passport-twitter middleware to handle Twitter authentication using the OAuth 1.0 API, because it saves time and handles all the complex authentication process behind the scene.

在这个项目中,我使用passport-twitter传递者中间件来使用OAuth 1.0 API处理Twitter身份验证,因为它节省了时间并处理了幕后的所有复杂身份验证过程。

什么是服务器端点? (What are the server endpoints?)

/auth/twitter — authenticate via passport twitter

/ auth / twitter —通过护照进行身份验证twitter

/auth/login/success — returns login success response with user information

/ auth / login / success —返回带有用户信息的登录成功响应

/auth/login/failed — returns login failed message

/ auth / login / failed-返回登录失败消息

/auth/logout — log-out and redirects to client home page

/ auth / logout-注销并重定向到客户端主页

/auth/twitter/redirect — redirect to home page if login succeeded or redirect to /auth/login/failed if failed

/ auth / twitter / redirect —如果登录成功则重定向到主页,或者如果失败则重定向到/ auth / login / failed

架构图 (Architecture Diagram)

Here is an overview of the architecture diagram which we will be going over in more detail.

这是体系结构图的概述,我们将对其进行详细介绍。

项目结构 (Project Structure)

I separated server and client logic in different folders to be clear and clean. My server is running on localhost:4000, whereas the client is running on localhost:3000. (Feel free to define your own port.)

我将服务器和客户端逻辑分隔在不同的文件夹中,以使其更加清晰。 我的服务器localhost:4000上运行客户端localhost:3000上运行。 (随意定义您自己的端口。)

|-- twitter-auth-project|   |-- server|   |   |-- index.js|   |   |-- package.json|   |-- client|   |   |-- src|   |   |   |-- index.jsx|   |   |   |-- package.json

实作 (Implementation)

第1部分:在Twitter应用程序站点上将您的应用程序注册为OAuth提供者 (Part 1: Register your app as an OAuth provider at Twitter Application Site)

First things first, register your application at Twitter Application Management. You will be issued with a consumer key (API Key) and consumer secret (API Secret) that you can use in passport strategy later on.

首先,请在Twitter Application Management上注册您的应用程序 。 系统会向您提供使用者密钥(API密钥)和使用者密钥(API密钥),以后可以在护照策略中使用它们。

You will also need to configure a callback URL. This is the callback URL after the OAuth has been authenticated successfully.

您还需要配置一个回调URL。 这是OAuth成功通过身份验证后的回调URL。

For local development purpose, I customized my callback URLs to be the client URL which is localhost:3000.

为了进行本地开发,我将回调URL定制为客户端URL,即localhost:3000

第2部分:安装用于Twitter身份验证的Express Server (Part 2: Setup Express Server for Twitter Authentication)

I chose Express.js to set up the server on the backend. Express.js is a web application framework for Node.js which designed to build APIs.

我选择Express.js在后端上设置服务器。 Express.js是Node.js的Web应用程序框架,旨在构建API。

|-- server|   |-- config|   |   |-- keys.js|   |   |-- passport-setup.js|-- |-- models|   |   |-- user-model.js|   |-- routes|   |   |-- auth-routes.js|   |-- index.js|   |-- package.json

npm install express to install an express server. The server runs on http://localhost:4000.

npm install express用于安装Express服务器。 服务器在http:// localhost:4000上运行

index.js is the entry point for all the server endpoints.

index.js是所有服务器端点的入口点。

/routes/auth-routes.js contains all the authentication endpoints.

/routes/auth-routes.js包含所有身份验证端点。

/config/keys.js contains all the Twitter API consumer keys, and database configs. You can copy them and put your own keys.

/config/keys.js包含所有Twitter API使用者密钥和数据库配置。 您可以复制它们并放置自己的密钥。

第3部分:设置身份验证路由 (Part 3: Setup authentication routes)

Previously in the “What are the server endpoints?” section, we have identified the authentication endpoints to Twitter API.

以前在“什么是服务器端点?”中 部分,我们确定了Twitter API的身份验证终结点。

/auth/twitter — authenticate via passport twitter

/ auth / twitter-通过护照进行身份验证

/auth/login/success — returns login success response with user information

/ auth / login / success —返回带有用户信息的登录成功响应

/auth/login/failed — returns login failed message

/ auth / login / failed-返回登录失败消息

/auth/logout — logout and redirects to client home page

/ auth / logout —注销并重定向到客户端主页

/auth/twitter/redirect — redirect to home page if login succeeded or to /auth/login/failed if failed

/ auth / twitter / redirect-如果登录成功,则重定向到主页;如果失败,则重定向到/ auth / login /失败

Let’s put them into practice.

让我们付诸实践。

/routes/auth-routes.js

/routes/auth-routes.js

In index.js, import routes/auth-routes,

index.js ,导入routes/auth-routes

npm install cors — support cross-origin browser

npm install cors支持跨域浏览器

第4部分:使用Passport API设置Twitter策略 (Part 4: Setup Twitter strategy using Passport API)

Passport API is a middleware we use to authenticate via Twitter OAuth. Passport API does the login authentication behind the scene so you do not need to handle the complex logic. It has also different authentication strategies (i.e GoogleStrategy, FacebookStrategy). In my example, I chose to use TwitterStrategy to login via a Twitter account.

Passport API是我们用于通过Twitter OAuth进行身份验证的中间件。 Passport API在后台进行登录身份验证,因此您无需处理复杂的逻辑。 它还具有不同的身份验证策略(即GoogleStrategy,FacebookStrategy)。 在我的示例中,我选择使用TwitterStrategy通过Twitter帐户登录。

第5部分:设置和连接数据库 (Part 5: Setup and connect a database)

When the system successfully authenticates the user through PassportAPI, it will need to store the user in a database so it can retrieve this user information to the client.

当系统通过PassportAPI成功验证用户身份时,它将需要将用户存储在数据库中,以便可以将该用户信息检索到客户端。

I’m using MongoDB to store the user login information.

我正在使用MongoDB来存储用户登录信息。

Part 5.1 — Sign up mlab and follow the instructions here: https://mlab.com/

第5.1部分—注册mlab并按照此处的说明进行操作: https ://mlab.com/

Part 5.2 — Add MongoDB credentials in keys.js

第5.2部分—在keys.js添加MongoDB凭据

Part 5.3 — Establish a MongoDB connection using mongoose

第5.3部分–使用猫鼬建立MongoDB连接

npm install mongoose to connect to MongoDB.

npm install mongoose连接到MongoDB。

“Mongoose provides a straight-forward, schema-based solution to model your application data. It includes built-in typecasting, validation, and query building.” (https://mongoosejs.com/)

“ Mongoose提供了一个简单的,基于模式的解决方案来为您的应用程序数据建模。 它包括内置的类型转换,验证和查询构建。 ”( https://mongoosejs.com/ )

Part 5.4 — Create a user object model that represents the user profile in the database record

5.4部分—创建一个用户对象模型,该模型代表数据库记录中的用户配置文件

/models/user-model.js

/models/user-model.js

第6部分:从数据库中保存和获取用户 (Part 6: Save and fetch user from a database)

Once the Passport API successfully authenticated via Twitter OAuth, our server saves the user information to the MongoDB. If this user already exists, the system simply finds the current user from the database and returns the user to the client. This is all done using mongoose APIs.

通过Twitter OAuth成功验证Passport API后,我们的服务器会将用户信息保存到MongoDB。 如果该用户已经存在,则系统仅从数据库中查找当前用户,然后将该用户返回给客户端。 所有这些都是使用猫鼬API完成的。

/config/passport-setup.js

/config/passport-setup.js

Every time the user logins a website, the browser remembers this user information so that the user does not need to log in again. How this user gets remembered is through an HTTP cookie. An HTTP cookie contains encrypted data about the user and how long the session lasts.

每次用户登录网站时,浏览器都会记住该用户信息,因此用户无需再次登录。 如何通过HTTP cookie来记住该用户。 HTTP cookie包含有关用户以及会话持续时间的加密数据。

If you login to any webpage, and open the DevTools, you can see the cookies have been set in the browser.

如果登录到任何网页,然后打开DevTools,则可以看到已在浏览器中设置了cookie。

Serialization and deserialization are important concepts to know. Serialization is when the user gets encrypted from the database and sends it back to the browser as a cookie. Deserialization is when the user cookie gets decrypted from the browser to the database.

序列化和反序列化是重要的概念。 序列化是指从数据库中加密用户并将其作为cookie发送回浏览器的时候。 反序列化是指用户cookie从浏览器解密到数据库的时间。

In order to support login sessions, Passport will serialize and deserialize user instance to and from the session.

为了支持登录会话,Passport会将用户实例与会话进行序列化和反序列化。

/config/passport-setup.js

/config/passport-setup.js

Here is the final index.js using cookie-session.

这是使用cookie-session的最终index.js

I chose to use cookie-session as a middle to store session data on the client.

我选择使用cookie-session作为中介,将会话数据存储在客户端上。

$ npm install cookie-session

Also, use cookieSession in index.js

另外,在index.js使用cookieSession

app.use(cookieSession({  name: 'session',  keys: [/* secret keys */],  maxAge: 24 * 60 * 60 * 1000 // session will expire after 24 hours}))

passport.session() acts as a middleware to alter the req object and change the encrypted user value that is currently the session sig (from the client cookie) into a user object.

passport.session()充当中间件来更改req对象,并将当前为会话信号的加密用户值(来自客户端cookie)更改为用户对象。

Optional step:

可选步骤

I customized the localhost:4000/ root URL to show success message if login correctly otherwise shows a failed message.

我自定义了localhost:4000 /根URL,以在成功登录后显示成功消息,否则显示失败消息。

下一步:客户端-使用React设置登录页面和注销页面 (Next Step: Client — Setup Login Page and Logout Page using React)

I built the front end components using React, and React Router to set up links.

我使用ReactReact Router构建了前端组件,以建立链接。

功能性 (Functionality)

The page contains a header with home and login/logout button. Initially, the page will display the “welcome” message and “login” button. Once the user has authenticated via twitter authentication, it will display the username and “logout” button.

该页面包含带有主页和登录/注销按钮的标题。 最初,页面将显示“欢迎”消息和“登录”按钮。 用户通过Twitter身份验证进行身份验证后,将显示用户名和“注销”按钮。

客户端设置 (Client setup)

client|-- src|   |-- components|   |   |-- Header.jsx|   |   |-- Homepage.jsx|   |-- App.js|   |-- AppRouter.js|   |-- index.js|   |-- index.css|   |-- serviceWorker.js|-- package.json

识别UI组件 (Identify UI components)

  • HomePage: a container that displays welcome and user information. Calls /auth/login/success endpoint. If the endpoint succeeded, the user information will be stored in the user object and the state of authenticated will be set true. The page shows a message that “You have login successfully”. If the endpoint failed, the user is not authenticated, and the page displays “Welcome”.

    主页:显示欢迎信息和用户信息的容器。 调用/ auth / login / success端点。 如果端点成功,则用户信息将存储在用户对象中,并且身份验证的状态将设置为true 。 该页面显示消息“您已成功登录” 。 如果端点失败,则表明用户未通过身份验证,并且页面显示“ Welcome”。

  • Header: It handles navigation. When the user is authenticated, “login” will be changed to “logout”. The authenticated state is passed down from HomePage as a prop.

    标头:处理导航。 用户通过身份验证后,“登录”将更改为“注销”。 经过身份验证的状态作为属性从HomePage向下传递。

实作 (Implementation)

HomePage.jsx: a container that displays welcome and user information

HomePage.jsx:显示欢迎信息和用户信息的容器

Header.jsx — navigation component

Header.jsx —导航组件

Lastly, set up Route that navigates to HomePage in the AppRouter.jsx and App.jsx

最后,在AppRouter.jsx和App.jsx中设置导航到HomePage的Route

Thank you so much for reading this blog post. I hope you found it helpful.

非常感谢您阅读此博客文章。 希望对您有所帮助。

The entire project is available on my Github: https://github.com/leannezhang/twitter-authentication

整个项目都可以在我的Github上找到: https//github.com/leannezhang/twitter-authentication

If you have any comments or feedback, please feel free to comment below or reach me.

如果您有任何意见或反馈,请随时在下面发表评论或与我联系。

Twitter: @ liyangz

推特:@ liyangz

阅读资料 (Reading Materials)

翻译自: https://www.freecodecamp.org/news/how-to-set-up-twitter-oauth-using-passport-js-and-reactjs-9ffa6f49ef0/

oauth2.js

 类似资料: