Node with React:fullstack Web Development Course (ii)--google OAuth

Source: Internet
Author: User
Tags oauth

Oauth

OAuth is an open network standard for licensing (authorization) that is widely used worldwide and is currently available in version 2.0. The common use, QQ, Weibo, Facebook, Google account landing site is the process of using OAuth technology. In this chapter we will use Google account to access third-party websites as an example of how to use this technology.

Google OAuth Workflow
  • The entire OAuth process is designed with three main aspects, the client (the browser for the website), the third-party server (the server that corresponds to the website), and the Google server. When a user clicks on a Google account to log on to the site, the third party server directly passes the request to the Google server, and the response page jumps to Google's verification authorization page asking the user if they agree to the authorization. After the user agrees, the Google server will jump to the third-party server, and the jump URL will carry a code parameter, the third-party server after the code will be with this code to send a request to the Google server, and in exchange for user information. After receiving the user information, the third-party server will check the database, if not the user is stored in the database, and the successful landing, if there is a direct landing success. At the same time, a cookie that identifies the user's information is given to the browser, and thereafter the browser will carry a cookie every time it requests a third-party server for the duration of the cookie, so it can represent the user and do something that requires permission. The specific process is as follows:
  • I use the Passport this library to help us implement the validation process. Passportjs
  • Two questions:
    • Passportjs automates the OAuth process, but requires code to go deep into the process details and not fully automate the entire process
    • The structure of the library, in fact we need two libraries to use Passportjs--passport, passport strategy, the first is the core library to provide a tool for validating the process, the second is for different authorized providers (Google, Facebook, WeChat etc) need to customize the method, that is, if you need to provide Google, Facebook, WeChat three authentication methods, then you need three strategy library. A lot of strategies libraries are available in passportjs.org.
  • Installing the passport into the project
    npm install --save passport passport-google-oauth20
  • 20 means that the version is 2.0 , because NPM package name can not have . , so it is named 20, in fact, there can be no more than 20, then the installation is 1.0 a 2.0 combined version. Since the basic well-known Auth provider have already supported OAuth2.0, the version is used here 2.0 . See Passport-google-oauth GitHub for details.
  • Using Passport
const passport  = require(‘passport‘);const GoogleStrategy = require(‘passport-google-oauth20‘).Strategy;passport.use(new GoogleStrategy());
  • Before using Google OAuth, you need two parameters AppID and API Secrect, to get these two parameters, you need to create a project on console.developers.google.com (as long as Google account, very easy)
  • After creating the project, go to the project panel, go to the API section, click 启用Google API , Search Google + , select Google + API , click启用
  • Now this API is still not available, you need to click 创建凭据 the click button, follow the prompt process until the end, generate credentials, mainly consists of two information ClientID and client key. If you want to see detailed steps, refer to here.

    • The point to note in this process is to set the JavaScript authorization domain and the authorization callback URL, as we are now building a development project, each set to http://localhost:5000 and http://localhost:5000/*
    • ClientID: The URL used to generate the login
    • Clientsecrect: Used to prove whether the app has access to tokens
  • The next step is to pass in the ClientID and clientsectrect that were just generated, into the Google OAuth module. Note thatClientsecrect cannot be published , and ClientID should be kept confidential if it is prudent. So we don't want people to get these two values in the form of viewing source code. We now hide this part of the information by not submitting this part of the code.

  • Create Cong/keys.js, store ClientID and Clientsecrect
    module.exports = {  googleClientId: ‘1229722414-eeujg12q0q9gvisar.apps.googleusercontent.com‘,  googleClientSecret: ‘ANPiCt5QFTa‘};
  • Write keys.js in. Gitignore to ensure that files containing sensitive information are not committed
  • in Index.js, the keys module is introduced and the corresponding Clientkey and ClientID are passed into the Googlestrategy module.
    • Note that the callback URL is also added here. This is because when the user clicks on the authorization, the Google Server will return a code to the application of the server, then our server should receive and handle the return of this server. Google server back to the app server information can be seen as a request (the server is not to handle the request), so we have to specify the requested route is what, so we need a callback URL parameters, Google Server will stitch code into the parameters of this URL. The
    • also adds a callback function, all of which are validated to get tokens so that the user can then manipulate the callback function to define what to do with the token. Now just take a look at the token.
       const keys =  Require (/config/keys ');p assport.use (new googlestrategy ({ clientid:keys.googleclientid,clientsecret: Keys.googleclientsecret,callbackurl:  '/auth/google/callback '} , (Accesstoken, Refreshtoken, profile, done) = {console.log (Accesstoken)});  
  • Finally we need to add a route handler to receive the user login request and enter the Google OAuth process, as shown in the following code.
    • First explain the meaning of the code: if the server receives /auth/google the request, use Passport to enable the Google OAuth verification process, the information needed to obtain the user profile and mailbox.
    • The string ' Google ' in this look is confusing, because in the previous code we did not use this string to represent the meaning of Google OAuth strategy. This is one of the most widely criticized passport. In fact, this is set out in the Google OAuth strategy module, which means that the module tells the passport that if the passport.authenticate first parameter of the method is passed in google , it is validated by the Google OAuth strategy module.
app.get(    "/auth/google",    passport.authenticate("google", {        scope: ["profile", "email"] }));
  • now start our local server, Access localhost:5000/auth/google , it should be supposed to pop up Google Certification page, but unfortunately not, then the popup is a 400 page, The approximate meaning is that the actual provided validation callback address and the inconsistency set in the console.developers.google.com. A link is also provided that directly accesses the link and enters the page that modifies the validation callback URL.
    • Why does this error page appear? Remember that before we set the authorized redirect URI to http://localhost:5000/* , we actually need a strict match here. Previously we set Callbackurl to /auth/google/callback in the code, so we should the redirected URI in this modification page This is set to Http://localhost:5000/auth/google/callback so that you should be able to eject the authorization page normally. Why does the
    • need a callback to verify URL matching? When we visit a Google server requesting authorization, the parameters provided are ClientID and are transmitted in plaintext. When the attacker gets clientid and changes the Redirect_uri to a malicious website, the user is authorized to jump to the malicious website and provide all the authorization information. Obviously, this is definitely not going to happen, so we need to configure the allowed callback URLs on Google and match them exactly. If the mismatch is unsuccessful, the callback will not succeed.
  • Click on the corresponding Google account login, will jump to an error page display Cannot GET /auth/google/callback . We haven't set the handler for the callback route, so of course we'll get an error. In the URL of this page, you will see a parameter code, which is the code returned by the Google server mentioned in the previous flowchart. After the server of our app gets code, we can send the request to Google server again through code, and get the information of the user, the mailbox and so on. So the next step is to fill in the corresponding route handler.
    app.get(‘/auth/google/callback‘, passport.authenticate(‘google‘));
  • Visit againlocalhost:5000/auth/google, click Account Login to see a piece of stuff printed in the console of the startup server. Before we passed a callback function in the configuration passport, we printed tokens in the callback function. This lump is the token to be taken.
    • In fact, passport in the callback URL handler automatically passed code to Google Server, and in exchange for tokens, user information (data, email, etc.). This information is passed back in the form of a function parameter. So, after that, the token-printing function is called, and our app can use that information in this callback function to do something that can't be described.
    • before we proceed, we can print out the returned information and see what it looks like. Modify the code, restart the server, re-access the login connection, and you can see that token (string), Profile (object), done (function) are printed in the console.
      • Accesstoken:app Credentials for subsequent access to user information.
      • Accesstoken expires over time and Refreshtoken allows us to refresh the latest tokens.
      • Profile: User-owned data. The
      • done function has three parameters: Err (Error message), user information, info (other information)
    • Why would pending? In the callback function, we did not give a response response.
      passport.use(new GoogleStrategy(  {      clientID: keys.googleClientId,      clientSecret: keys.googleClientSecret,      callbackURL: "/auth/google/callback" }, (accessToken, refreshToken, profile, done) => { console.log(‘accessToken‘, accessToken); console.log(‘refreshToken‘, refreshToken); console.log(‘profile‘, profile); console.log(‘done‘, done); }));
  • At this point, all authorized work (with the help of the passport) has been completed, followed by the creation of user information to the database and the completion of the login.
Using Nodemon to automate the development
    • At this point, you should be tired of the process of modifying the code and restarting the server. Fortunately, there are tools that automate this, and this tool is nodemon .
    • npm install --save-dev nodemon
    • Modify Package.json
      "scripts": {  "start": "node index.js",  "dev": "nodemon index.js"},
    • After that, you can start the server by simply typing it at the command line, npm run dev and Nodemon will automatically restart the server after each code change is saved. Refactoring the current code
    • Before we wrote all the logic in the Index.js file, we scattered the logic in different directories for ease of maintenance and iteration. At present we divide the logic into three parts of config,routes,services. The meanings of the three sections are as shown. The directory following the refactoring is shown below. The basic task is to move the Routehandler logic into the authroutes.js, move the configuration of the passport into Passport.js, and then introduce the dependent packages or other modules into the two files. The two files are then introduced in index.
      ├── config│   └── keys.js├── index.js├── package-lock.json├── package.json├── routes│   └── authRoutes.js└── services  └── passport.js

    • Routes/authroutes.js
const passport = require(‘passport‘);module.exports =  (app) => { app.get( "/auth/google", passport.authenticate("google", { scope: ["profile", "email"] }) ); app.get("/auth/google/callback", passport.authenticate("google"));}
    • Servics/passport.js
Const Passport =Require' Passport ');Const GOOGLESTRATEGY =Require "Passport-google-oauth20"). strategy; const keys = require ( "). /config/keys ");p assport.use (new googlestrategy ({clientID: Keys.googleclientid, clientsecret:keys.googleclientsecret,  Callbackurl:  "/auth/google/callback"}, (Accesstoken, Refreshtoken, profiles, done) = { Span class= "hljs-built_in" >console.log ( ' Accesstoken ', accesstoken); console.log (console.log ( ' profile ', profile); console.log ( ' done ');      
    • Index.js
      const express = require("express");const app = express();require(‘./services/passport‘);require(‘./routes/authRoutes‘)(app);app.get("/", (req, res) => { res.send({ hi: "there" });});)const PORT = process.env.PORT || 5000;app.listen(PORT);

Node with React:fullstack Web Development Course (ii)--google OAuth

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.