Step one: Route add a custom field Requireauth
Path: '/repository ',
name: ' Repository ',
meta: {
requireauth:true, //Add this field to indicate that entry is required for login
}.
component:repository
Step Two:
Router.beforeeach (to, from, next) => {
if (to.meta.requireAuth) { //Determine if the route requires logon permission
if ( Store.state.token) { //Vuex state Gets the current token existence
next ();
}
else {
Next {
path: '/login ',
query: {redirect:to.fullPath} //To jump to the routing path as an argument, successful login to the route
})
}
}
else {
next ();
}
Log in to intercept here is the end of it. And No.
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 permission in the browser address bar)
Another situation is that the current token is invalid, but the token is still stored locally.
When you access a route that requires logon rights, you should actually have the user log on again.
In this time, we need to combine the HTTP Interceptor + back-end interface to return the HTTP status code to judge.
Step three: Interceptors (to handle all HTTP requests and responses uniformly, you need to use Axios interceptors.) )
Every time you jump the page, you get the HTML page for the new route, which you can use Axios http to intercept
Each route jump, first let the background verify that token is valid, add token to the HTTP header,
When the backend interface returns 401 Unauthorized (not authorized), let the user log in again.
The token of the cookie is ignored after the autorization is used, which weakens the security and can be matched with HTTPS
//http request Interceptor Axios.interceptors.request.use (config => {if (Store.state.token) {//To determine if there is a token, and if so, each HTTP header plus token config.headers.Authorization = ' token ${s
Tore.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: 401, the Doctor with the [authorized] banner is the psychic//return 401 Clear token information and jump to the login page store.commit (types.
LOGOUT); Router.replace ({path: ' login ', query: {redirect:router.currentRoute.full
Path}}}} return Promise.reject (Error.response.data)//Back error message returned by interface });
The complete method sees/src/http.js.
With these steps, you can intercept the login on the front end.
Logout function is also very simple, just to the current token clear, and then jump to the home page can be.