preface

This project uses Github’s Personal token as a login token to access your Repository List. Through this project, I learned how to realize the login and interception, logout, token invalidation interception and the corresponding use of AXIos interceptor needed in a front-end project.

To prepare

You need to create your own Github Personal Token. Access Demo after Token generation to view your Repository List.

The project structure

. ├ ─ ─ the README. Md ├ ─ ─ dist / / package build folder after │ ├ ─ ─ build. Js │ └ ─ ─ build. Js. Map ├ ─ ─ index. The HTML ├ ─ ─ package. The json ├ ─ ─ the SRC │ ├ ─ ─ App. Vue │ ├ ─ ─ assets │ │ ├ ─ ─ CSS. The CSS │ │ ├ ─ ─ icon. The CSS │ │ └ ─ ─ logo. The PNG │ ├ ─ ─ constant │ │ └ ─ ─ API. Js / / configuration API interface file │ ├ ─ ─ │ ├─ index.vue │ ├─ login.vue │ ├─ main.js │ ├─ repository │ ├─ ├─ class.js // vuex types ├─ class.js // │ ├─ class.jsCopy the code

Technology stack

  • Vue 2.0
  • vue-router
  • vuex
  • axios
  • vue-material

Logon blocking logic

Step 1: Route interception

First of all, a customized requireAuth field should be added when defining the route, which is used to determine whether the access of the route requires login. If the user has logged in, the route is successfully entered; otherwise, the login page is displayed.

const routes = [ { path: '/', name: '/', component: Index }, { path: '/repository', name: 'repository', meta: }, Component: Repository}, {path: '/login', name: 'login', Component: Login } ];Copy the code

After defining the route, we use the hook function beforeEach() provided by vue-Router to determine the route.

router.beforeEach((to, from, Next) => {if (to.meta.requireauth) {if (store.state.token) {next(); } else {next({path: '/login', query: {redirect: to.fullPath})}} else {next(); }})Copy the code

Each hook method takes three arguments:

  • To: Route: indicates the destination Route to be entered
  • From: Route: indicates the Route that the current navigation is about to leave
  • Next: Function: Be sure to call this method to resolve the hook. The execution depends on the call parameters of the next method.
    • Next (): Goes to the next hook in the pipe. If all hooks are executed, the navigation state is confirmed.
    • Next (false): interrupts current navigation. If the browser URL changes (either manually by the user or by the browser back button), the URL is reset to the address corresponding to the FROM route.
    • Next (‘/’) or next({path: ‘/’}): jumps to a different address. The current navigation is interrupted and a new navigation is performed.

Make sure you call the next method or the hook won’t be resolved.

See/SRC /router.js for the complete method

To.meta is our custom data, including the requireAuth field we just defined. Use this field to determine whether the route requires login permission. If the application does not have a token, the login page is displayed for login. After the login succeeds, the system switches to the target route.

Does login interception end here? Don’t. This approach is simple front-end routing control and does not really prevent users from accessing routes that require login permission. There is also a case where the current token expires, but the token is still stored locally. When you access a route that requires login permission, you should actually ask the user to log in again. In this case, we need to combine the HTTP status code returned by the HTTP interceptor and the back-end interface to judge.

Step 2: Interceptor

To process all HTTP requests and responses uniformly, use axios’s interceptor. When the HTTP Response Eptor is configured, the back-end interface returns 401 Unauthorized so that users can log in again.

/ / HTTP request interceptor axios. Interceptors. Request. Use (config = > {if store. State. (token) {/ / judge the existence of a token, if they exist. Is each HTTP headers and token config. Headers. Authorization = ` token ${store. State. Token} `; } return config; }, err => { return Promise.reject(err); }); / / HTTP response interceptor axios. Interceptors. Response. Use (response = > {return response; }, error => { if (error.response) { switch (error.response.status) { case 401: // return 401 to clear token information and jump to login page store.mit (types.logout); router.replace({ path: 'login', query: {redirect: The router. CurrentRoute. FullPath}})}} return Promise. Reject (the error. The response. The data) / / returns the error information returned interface});Copy the code

See/SRC /http.js for the full method.

With these two steps, you can implement login interception on the front end. Logout function is very simple, just need to clear the current token, and then jump to the home page.

If you want to return to the page you want to enter before login, just add the following judgment in the jump of the login page

if(!!!!! this.$route.query.redirect){
      this.$router.push(this.$route.query.redirect)// Here is the page you want to redirect before intercepting}else{
      this.$router.push('/home')// Here is your default redirect address}Copy the code