Function is introduced

  1. Authorized by wechat public account
  2. Binding account
  3. Automatic login

The flow chart

Wechat official account authorized login

Principle:

When the user opens a certain page (e.g. /goodslist), we need to obtain the user information or realize the automatic login of the user, so that the user can authorize wechat.

Make the page jump to WeChat given authorization page (https://open.weixin.qq.com/connect/oauth2/authorize? # {some preach and} wechat_redirect)

The authorization page will prompt the user to authorize, so that wechat can sense whether the user is authorized or not.

After successful authorization, jump back to the redirect_URI redirection page we specified in {some parameters}, usually set to the page before the jump (/goodslist)

Wechat adds code to the redirect URI, such as /goodslist? Code = XXXXXX (with one more parameter state)

Get the code on the page that jumps back to exchange user information with wechat (the first step is to exchange access_token with code; Step 2: Pull user information)

Use code in exchange for user information to be requested by our own server, the front end does not care, because some security parameters need to be submitted

Some parameters :(wechat requires that the order of these parameters cannot be changed)

  1. Appid – The unique identifier of the public number
  2. Redirect_uri – The address of the callback link redirected after authorization. Use urlEncode to process the link
  3. Response_type – Return type, fixed valuecode
  4. Scope – Application authorization scope, see below
  5. The state parameter will be added after the state-redirect. Developers can fill in the value of the a-za-z0-9 parameter, which can be up to 128 bytes

scope

Optional values: SNsapi_base, snsapi_userinfo

  1. snsapi_base

    The user can only obtain the OpenID when the authorization page is not displayed

  2. snsapi_userinfo

    The authorization page is displayed, and you can get the nickname, gender, and location through OpenID. And, even in the absence of attention, as long as the user’s authorization, can also access their information

Reference manual

Web page authorization

Code implementation

Determine the Browser environment

// src/utils/env.js
// Use the bowser library
import Bowser from 'bowser'

const parsed = Bowser.getParser(window.navigator.userAgent).parsedResult

// Whether the wechat environment
export const inWechat = parsed.browser.name === 'WeChat'

export const inIOS = parsed.os.name === 'iOS'

export const inSafari = parsed.browser.name === 'Safari'
Copy the code

WeChat authorization

// src/auth.js

import qs from 'qs'

// Store2 library facilitates localStorage and sessionStorage
import store from 'store2'

import { inWechat } from '@/utils/env'

import { getUserInfo } from '@/service/login'

/ / WeChat appid
const appid = 'wxxxxxxxxxxxxx'

// Go to authorization
const goAuth = (a)= > {
  const uri = 'https://open.winxin.qq.com/connect/oauth2/authorize'
  
  const params = {
    appid,
    redirect_uri: window.location.href,
    response_type: 'code'.scope: 'snsapi_userinfo'.state: 'STATE'
  }
  
  const hash = 'wechat_redirect'
  
  const url = `${url}?${qs.stringify(params)}#${hash}`

  // Page jump, ios and other models prohibit direct use of location.href jump
  // window.location.href = url // Cannot be used

  const nextPage = document.createElement('a')
  nextPage.setAttribute('href', url)
  nextPage.click()

  // For a more user-friendly effect, you can prompt the user to require authorization and give a button to go to authorization. Triggered when the user clicks
}

/** Authorization returns * code - code * callback in the argument following redirect_uri after authorization - this is typically specified as dom rendering operations */
const authBack = async (code, callback) => {
  // Request user information with code
  await getUserInfo(code)
  
  callback()
}

export default async callback => {
  if (
    window.location.pathname === '/login' // Login to the binding page
    || store('token') / / have to log in| |! inWechat// In a non-wechat environment
  ) {
    // Render dom directly
    return callback() 
  }

  / / parse the querystring
  const params = qs.parse(window.location.search, { ignoreQueryPrefix: true })
  params.code === undefined ? goAuth() : await authBack(params.code, callback)
}
Copy the code
// src/index.js

import React from 'react'
import ReactDOM from 'react-dom'

import auth from './auth'

import { Provider } from 'react-redux'
import store from './store'
import Router from './router'

const renderDom = (a)= > ReactDOM.render(
  <Provider store={store}>
    <Router />
  </Provider>.document.getElementById('root'))// Only after authorization is complete can the page render continue, this can prevent requests made in the page.
// In particular, some of these requests require that you must log in, which will cause the page to jump to the login page
auth(renderDom)

Copy the code

Postscript, some thinking

Another authorization process

Redirect_uri is set to a back-end address (the address cannot be matched by the front-end route, for example, /auth).

State is set to the front hop address, such as window.location.href

After the user is successfully authorized, wechat jumps to the back-end address with the code and state parameters (/auth? Code ={code}&state={front-end address})

After the backend (/ Auth) gets the code, it exchanges user information with wechat. If the wechat user is registered, the login operation is performed, the token is returned, and the page is redirected to {front-end address}? Token ={token}& openID ={openID}&{Other user information}; If the user is not registered, redirect to {login page}? openid={openid}

advantages

It simplifies the front-end process

insufficient

Redirection from the back-end to the front-end exposes user information, such as tokens, resulting in security risks