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
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"] }));
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
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"));}
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