Home >Web Front-end >JS Tutorial >How to solve the problem of separation of front-end and back-end in Vue WeChat authorized login

How to solve the problem of separation of front-end and back-end in Vue WeChat authorized login

不言
不言Original
2018-06-29 10:31:543401browse

This article mainly introduces a detailed and elegant solution for separating the front-end and back-end of Vue WeChat authorized login. The content is quite good. I will share it with you now and give it as a reference.

WeChat authorized login is a very common scenario. Using WeChat authorized login, we can easily obtain some information of the user, and establish a database to bind the user's identity through the user's unique openid for the public account.

The mechanism of WeChat authorized login will not be described in detail here. WeChat official documents have already detailed it. The brief description is to jump to the WeChat authorized page. After the user clicks to confirm, WeChat will jump to the callback page. At this time The callback page URL will carry the code parameter. Through the code parameter, the backend can exchange the code for openid support, or user information

In a vue project, it is usually a SPA application, that is, all pages are the same HTML is usually developed with the front-end and back-end completely separated. The pure static files generated after Vue packaging may not even go through the server, so it is not very elegant to make jumps through the back-end. This article introduces WeChat for such scenarios. Authorized login

For a Vue SPA application, we may usually have many pages. On the WeChat official account, we may configure multiple menus. Multiple menus correspond to the routing page of Vue, but they may not be Each page requires user authorization to enter. Some pages need to be previewed by users without logging in. At this time, we can use vue router to implement front-end routing interception

 router.beforeEach(async (to, from, next) => {
 if (to.matched.some(recode => recode.meta.noAuth)) {
  next()
 } else {
  // store已存在用户信息直接进入页面
  if (store.state.userInfo.nickname) {
   next()
   return
  }
  const code = getUrl(window.location.href).code // 截取url上的code ,可能没有,则返回''空字符串
  let res = await api.post('/imsl/user/user-auth', [code]) // 获取用户信息,后端可首先通过cookie,session等判断,没有信息则通过code获取
  console.log(res)
  // 返回用户信息
  if (res.code === 200 && res.data.is_auth) {
   store.commit('setUserInfo', res.data)
   next()
  } else {
   // 此状态根据业务需求 可能不存在
   if (res.code === 201) {
    const openid = res.data.openid
    console.log(openid)
    store.commit('setOpenid', openid)
    localStorage.setItem('openid', openid)
    next('/enlist-info')
   }
   // 上面的获取用户信息接口,如果cookie,session拿不到用户信息,且传递的code为空,则跳转到微信授权页面
   if (res.code === 202) {
    console.log(window.location.origin)
    console.log(to.fullPath)
    // 这个redirectUrl用 当前页路径或者tof.fullPath(将要进入的路径)
    let redirectUrl = window.location.href
    redirectUrl = encodeURIComponent(redirectUrl)
    console.log(redirectUrl)
    const appid='wxdff0642c2120ea39'
    window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${redirectUrl}&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect`
   }
  }
 }
})

The above code basically explains an authorization process. First, , when we configure vue routing, set whether this route requires login, that is, add a noAuth: true attribute to the router's meta. This is to handle pages that do not require login. It is judged through router.beforeEach. If login is not required Page: noAuth, then directly next() let it enter the corresponding page. For pages that require login, let the backend cooperate. At this time, the backend writes an interface to obtain user information, and the frontend directly calls the interface to obtain user information. Of course, there is no need to call every page. After obtaining it once, the user information can be stored in vuex. Therefore, by judging whether there is user information in vuex, if the user information already exists, enter the page. If there is no user information, then call the backend. The interface for obtaining user information. Speaking of which, we finally return to the topic of this article. User information is obtained through WeChat authorized login. How does the backend get the user information at this time? Here, you can discuss with the backend, the user After binding the identity, the backend can save the user login status by setting cookies, tokens, etc. If there is a relevant status, the backend can directly return the user information. If it is the first time to enter, or cookies, tokens, etc. has expired, then WeChat authorization will be called to log in at this time. As mentioned in the above code, it is divided into three situations,

1. Through cookies, tokens, etc., the backend directly obtains the user information. , at this time, get the user information and enter the page directly, and at the same time store the user information in vuex

2. If there is no user information, there is no cookie or token at this time, then you need to call it again WeChat authorized login, the two return codes code=201 and code=202 given above, when code=2, the front end jumps directly to the WeChat authorization page, and redirectUri is the page to be entered. At this time What will happen? It will jump to the WeChat authorization page, and the user will return to this page after clicking. The difference is that the url already carries the code. The front end gets the code through string interception and sends it to the back end. The back end is You can exchange openid and user information through code.

##Summary:

  1. The project adopts complete front-end and back-end The separation method is to put the packaged pure static files on the server. When accessing index.html

  2. , the backend does not intercept it at the interface. There is no need for the backend to jump to the WeChat authorization login page. Front-end routing is used to intercept jumps. The implementation method is as follows: 3.

  3. The front-end intercepts pages that require user identity to enter through the router.beforeEach hook function of vue-router. At this time, it is called to obtain the user. Information interface, the back-end first determines the user by obtaining cookies, tokens, etc., and returns 201 or 202 if there is no relevant information. When 202 is returned, the front-end jumps to the WeChat authorization page, redirecturi is the URL of the page to be entered, jump authorization WeChat will then carry the code on the url and return to the current page. At this time, the front-end intercepts the code on the url and passes it to the back-end. The back-end processes the code to get the user information. OpenID and other implementations enable authorized login

The above is the entire content of this article. I hope it will be helpful to everyone's study. For more related content, please pay attention to the PHP Chinese website!

Related recommendations:

How to solve the problem of blank page after routing History mode packaging under Vue

Usage of $refs in Vue

About the implementation of vue and vue-validator form verification functions

The above is the detailed content of How to solve the problem of separation of front-end and back-end in Vue WeChat authorized login. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn