Implement User logon and Token verification in the Vue Project

Source: Internet
Author: User

The general idea of token verification in the Vue project is as follows:

1. During the first login, the front-end calls the backend login interface to send the user name and password

2. When the backend receives a request, the user name and password are verified. If the verification succeeds, a token is returned to the front end.

3. The front end obtains the token, stores the token in localstorage and vuex, and jumps to the routing page.

4. Each time the frontend redirects to a route, it determines whether there is a token in localstroage. If not, it jumps to the logon page. If yes, it jumps to the corresponding routing page.

5. Each time you call a backend interface, you must add a token to the request header.

6. When the backend determines whether the request header contains a token and a token, it obtains the token and verifies the token. If the token is successfully verified, data is returned. If the token fails to be verified (for example, the token expires), 401 is returned, if no token exists in the Request Header, 401 is returned.

7. If the front-end obtains a status code of 401, it clears the token information and jumps to the logon page.

Build a project using Vue-CLI to briefly describe what the front-end should do:

1. the logon interface is successfully called. the token is stored in localstorage and vuex In the callback function.

Login. vue

<Template> <div> <input type = "text" V-model = "loginform. username "Placeholder =" username "/> <input type =" text "V-model =" loginform. password "Placeholder =" password "/> <button @ click =" login "> logon </button> </div> </template> <SCRIPT> Import {mapmutations} from' vuex '; export default {data () {return {loginform: {Username: '', password:'' };}, Methods :{... mapmutations (['changelogin']), login () {let _ this = this; if (this. loginform. username = ''| this. loginform. password = '') {alert ('account or password cannot be blank ');} else {This. axios ({method: 'post', URL: '/user/login', data: _ this. loginform }). then (RES => {console. log (res. data); _ this. usertoken = 'bearer' + Res. data. data. body. token; // Save the User Token to vuex _ this. changelogin ({authorization: _ this. usertoken}); _ this. $ router. push ('/home'); alert ('login successful ');}). catch (error => {alert ('account or password error'); console. log (error) ;}}}}; </SCRIPT>

Index. js in the store folder

Import vue from 'vue '; import vuex from 'vuex'; vue. use (vuex); const store = new vuex. store ({state: {// storage token authorization: localstorage. getitem ('authorization ')? Localstorage. getitem ('authorization'): ''}, mutations: {// modify the token and save the token to localstorage changelogin (State, user) {state. authorization = user. authorization; localstorage. setitem ('authorization', user. authorization) ;}}); export default store;

2. Route Navigation guard

Index. js in the router folder

Import vue from 'vue '; import Router from 'vue-router'; import login from '@/components/login'; import home from' @/components/home'; vue. use (router); const router = new router ({routes: [{path: '/', redirect: '/login'}, {path:'/login', Name: 'login', component: Login}, {path: '/home', name: 'home', component: Home}]}); // navigation guard // use router. beforeeach registers a global front-guard to determine whether the user has logged on to the router. beforeeach (to, from, next) => {If (. path = '/login') {next ();} else {Let token = localstorage. getitem ('authorization'); If (token = 'null' | token = '') {next ('/login ');} else {next () ;}}); export default router;

3. Add token to the Request Header

// Add the request interceptor and add tokenaxios in the request header. interceptors. request. use (Config => {If (localstorage. getitem ('authorization') {config. headers. authorization = localstorage. getitem ('authorization');} return config ;}, error =>{ return promise. reject (error );});

4. If the frontend receives a status code of 401, the token information is cleared and the logon page is displayed.

      localStorage.removeItem(‘Authorization‘);      this.$router.push(‘/login‘);

 

Implement User logon and Token verification in the Vue Project

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.