First step: Add a custom field to the routerequireAuth
'/repository ', ' repository ', meta: {true,//Add this field, indicating that entering this route is required to log in}, component: Repository
Step Two:
Router. Beforeeach (To, from, next) = { if (to.meta.requireAuth) { //Determines if the route requires login permission if (Store.state.token) { query: {Next ();}
Login intercept is this the end of the block? And not.
This approach is simply a front-end routing control and does not really prevent users from accessing routes that require logon privileges. (You can manually enter a route without permissions in the browser address bar)
Another case is that the current token is invalid, but token is still stored locally.
When you visit a route that requires login permissions, you should actually let the user log in again.
At this point you need to combine the HTTP Interceptor + back-end interface returned by the HTTP status code to judge.
Step three: Interceptors (to handle all HTTP requests and responses uniformly, you need to use Axios interceptors.) )
Each time you skip the page, get the HTML page for the new route, which can be intercepted with Axios http
Each routing jump, first let the background verify that token is valid, add tokens in the HTTP header,
When the backend interface returns 401 Unauthorized(未授权)
, let the user log in again.
Token that ignores cookies after autorization is used, weakens security, and works with HTTPS
HTTP request Blocker axios.interceptors.request.use (Config = {if (Store.state.token) {Determine if tokens exist, and if so, each HTTP header is prefixed with token config.headers.Authorization =' Token${store.state.token} '; }return config; }, Err = {ReturnPromise.reject (ERR); });//HTTP response Interceptor
Axios.interceptors.response.use (< Span class= "Hljs-params" >response = {return response;}, error = {if (error.response) {switch (error.response.status) { case 401:401, only the Doctor who [authorizes] the banner is the healer.
//returns 401 clear token information and jumps to the login page store.commit (types. LOGOUT); Router.replace ({path: ' login ', query: { redirect:router.currentroute.fullpath}}) }} return promise.reject (error.response.data) //returns the error message returned by the interface});
See the Complete method /src/http.js
.
With these steps, you can implement login interception at the front end.
登出
function is very simple, just need to remove the current token, and then jump to the homepage.
Axios interception, page jump, token verification