OAuth 2.0 is currently the most popular authorization mechanism used to authorize third-party applications and obtain user data. For example, the third-party account of Nuggets, wechat, Weibo and Github have the same login mode. Think about how this login is designed and implemented. In daily life, many apps or websites need to send verification code after the user enters the mobile phone number. Then how does this whole process work?

First, the idea of OAuth

OAuth sets up an authorization layer between “client” and “service provider”. The client cannot directly log in to the service provider, but can only log in and authorize it to separate the user from the client. After client login authorization, the Service Provider opens the data stored by the user to the Client based on the scope of authority and validity of the token.

Simply put, OAuth is an authorization mechanism. The owner of the data tells the system that it agrees to authorize third-party applications to access the data. The system then generates a short-term access token (token), which can be used in place of a password for third-party applications.

Second, OAuth login practice

GitHub is used as an example to realize OAuth authorized login. How to access Github authorized login in your website

1. GitHub App registration

Click the button to go to github homepage to create an OAuth App, click Create and fill in the following information

2. Code implementation

2.1 Front-end Implementation

The front end uses the authorized login mode of Nuggets, when the user clicks the third party GitHub login, a new window pops up

window.open(“/oauth”, “”, “height=600, width=700”)

In this new window, only the jump links, client_id and redirect_URI, are needed to configure their own parameters created earlier.

Window. The location. Href = ‘github.com/login/oauth… ‘After the user is authorized to login, the user is directed to the Redirect page, and the redirect request is directed to the backend with the generated code. The backend receives the user information that the code requests from Github and closes the popover.

2.2 Back-end implementation

The back-end author uses Koa2, with the following code

router.get('/oauth', async function(ctx, next) {
  const requestToken = ctx.request.query.code
  const tokenResponse = await axios({
    method: 'post',
    url: 'https://github.com/login/oauth/access_token?' +
      `client_id=${OAUTH_GITHUB.clientID}&` +
      `client_secret=${OAUTH_GITHUB.clientSecret}&` +
      `code=${requestToken}`,
    headers: {
      accept: 'application/json'
    }
  })
  const accessToken = tokenResponse.data.access_token
  const result = await axios({
    method: 'get',
    url: `https://api.github.com/user`,
    headers: {
      accept: 'application/json',
      Authorization: `token ${accessToken}`}})Copy the code

Then according to their own business needs, the obtained information is stored in the user table. There are many ways here. I directly insert the github authorized login information into my user table, or you can create a third party OAUth table to store it.

const oauthLogin = async (userData = {}) => {
  const username = userData.username
  const nickname = userData.username
  const avatar = userData.avatar
  const date = Date.now()
  const userSql = `select * from users where username = '${username}' `
  const rows = await exec(userSql)
  if (rows.length > 0) {
    return rows[0] || {}
  } else {
    const sql = `insert into users (username,password, nickname, avatar, date) values ('${username}'.'${password}'.'${nickname}'.'${avatar}'.'${date}'); ` const insertData = awaitexec(sql)
  }
}
Copy the code

Final effect

3. SMS login authentication

3.1 Enabling SMS service

SMS verification naturally needs to use service providers, Ali Cloud has free SMS function, free SMS service, after the opening of each 0.04 yuan calculation. In order to practice charged a dollar test SMS verification function, free open this is very good, do not send a lot of money can be used to test

3.2 Front-end Implementation

In the gold nuggets case, users click register to enter their mobile phone number, then click to get a verification code.

3.3 Back-end implementation

router.post('/sendSmsCodeToUser', async function (ctx, next) {
  const { username } = ctx.request.body
  CODE = Math.random().toString().slice(-6)
  var client = new RPCClient({
    accessKeyId: 'LTAI4FcGip5kqy1'// accessKeySecret:'BvmhpNobez41as1vA5z1QSbhTGIm', 
    endpoint: 'https://dysmsapi.aliyuncs.com',
    apiVersion: '2019-12-14'
  })
  var params = {
    "RegionId": "cn-hangzhou"."PhoneNumbers": `${username}`,
    "SignName": Sail net."TemplateCode": "SMS_180059442"."TemplateParam": `{code: ${CODE}}`
  }
  var requestOption = {
    method: 'POST'
  }
  var result = await client.request('SendSms', params, requestOption).then((res) => {
      return res
    }, (ex) => {
      return ex
    })
  if ('Code' in result) {
    ctx.body = new SuccessModel({message: 'Verification code sent successfully'})}else {
    const limit = result.data.Message.split(':')[1]
    ctx.body = limit >= 10 ? new ErrorModel({message: 'You can only send 10 captcha codes per day from the same phone number.'}) : new ErrorModel({message: 'You can only send 5 captcha codes per hour from the same phone number.'})}})Copy the code

Compare the CODE between the front and back ends to implement the SMS login authentication function