clarification
This article is part of the OverallAuth 2.0 series of articles, which is updated weekly with an article in the series (Complete System Development from 0 to 1).
I will try to be very detailed in this system article, so that it can be understood by novice and veteran alike.
DESCRIPTION: OverallAuth 2.0 is a simple, easy to understand and powerful Permissions + Visual Process Management system.
Friendly reminder: this article is part of a series of articles, before reading that article, it is recommended to read the previous articles to better understand the structure of the project.
qqswarm:801913255
If you are interested, please follow me (*^▽^*).
Follow me. Beat me if you can't learn.
preamble
It's a bit long and informative, so bear with me if you're interested in the article.
I. What is a route guard and what does it do?
What is a route guard:It is a mechanism to control access to the routing menu, when a user clicks on a routing menu, then the route guard will "protect" it, common guarding methods are
beforeEach: route menu access before guard.
afterEach: routing menu access after guard.
The role of route guards:After understanding what a route guard is, we can actually roughly conclude that it does roughly the following.
1、Authentication: Before entering the module, verify whether the user's identity is correct, such as: whether the login is expired, whether the user is logged in and so on.
2、Access control: control the access rights of users and roles corresponding to the module.
3, logging: As the route guard can monitor the user for the module access before and after the access to the action, then we can be used to record the user's access logs and so on.
4, data preloading: In many cases, some data need to be loaded before we visit the page.
5、Routing animation: You can load a transition animation before and after the route access to improve the user experience.
II. Use of route guards
Before we can use it, we need to install the state management library and state persistence plugin as well as the route loading progress bar. It shares some of the state in the program.
1: Install npm install pinia state repository
2: Install npm install pinia-plugin-persistedstate state persistence plugin
3: Install npm install nprogress progress bar plugin
4: Install npm install @types/nprogress
The book picks up where the previous one left off:Combined use of menus and routes in Vue3 for dynamic menu switching
Create a routing file and store it in the specified folder, since I'm writing about building a framework from 0 to 1, I put it in the following directory
The content is as follows:
import { createRouter, createWebHashHistory, NavigationGuardNext, RouteLocationNormalized } from 'vue-router' import { routes } from './module/base-routes' import NProgress from 'nprogress' import 'nprogress/' ({ showSpinner: false }) const router = createRouter({ history: createWebHashHistory(), //development environment (computer) routes }) /**:: Route guard, intercept before accessing the route menu * @param to target * @param from to */ ((to: RouteLocationNormalized, from: RouteLocationNormalized, next: NavigationGuardNext) => { (); if () { next(); } else if ( == 0) { next({ path: '/panel' }) } else { next(); } }) (() => { (); }) export default router
Code Explanation:
Then we register routing and state management globally in main
Do all of the above and the routing guard is complete.
If, however, you are following the front-end framework that I have built in my series of articles, then you will have to make changes in the following 2 files (if you don't have them, please ignore them).
1、In the file putimport router, { routes } from "../router/module/base-routes";replace withimport { routes } from "../router/module/base-routes"; incorporateimport router from "../router/index";
2. Delete the following code in the file
//Create routes and expose them const router = createRouter({ history: createWebHashHistory(), //development environment (computer) //history:createWebHistory(), //Formal environment routes }) export default router
With that done, let's start the project and check that every time we click on the routing menu, it goes into the Route Guard Intercept.
For those partners who understand, go ahead and fill in your content.
III. Request Interception, Response Interception
Our OverallAuth 2.0 uses a project created with Vue3+.net8 WebApi, so we will be using the backend interface. So how do we establish a data interaction between the front-end and the back-end? How to deal with the return information after the relationship is established? Don't worry, be patient and read on.
First install the combined api request plugin axios
Installation command: npm install axios
Then follow the diagram below to create new files and folders
The document reads as follows
import axios, { AxiosResponse, InternalAxiosRequestConfig } from 'axios'; //Declaring Model Parameters type TAxiosOption = { timeout: number; baseURL: string; } //Configuration Assignment const config: TAxiosOption = { timeout: 5000, baseURL: "https://localhost:44327/", // Local api interface address } class Http { service; constructor(config: TAxiosOption) { this.service = (config) /* Request Interception*/ this.((config: InternalAxiosRequestConfig) => { //You can do request interception processing here, e.g., before requesting the interface, you need to pass in the token. debugger; return config }, (error: any) => { return (error); }) /* Response Interception*/ this.((response: AxiosResponse<any>) => { debugger; switch () { case 200: return ; case 500: //This is where you can write error alerts to feed back to the front-end return ; case 99991: return ; case 99992: return ; case 99998: return ; default: break; } }, (error: any) => { return (error) }) } /* GET method*/ get<T>(url: string, params?: object, _object = {}): Promise<any> { return this.service.get(url, { params, ..._object }) } /* POST method*/ post<T>(url: string, params?: object, _object = {}): Promise<any> { return this.(url, params, _object) } /* PUT method*/ put<T>(url: string, params?: object, _object = {}): Promise<any> { return this.(url, params, _object) } /* DELETE method*/ delete<T>(url: string, params?: any, _object = {}): Promise<any> { return this.(url, { params, ..._object }) } } export default new Http(config)
The key points of the above code are commented out
in the following
import Http from '../http'; export const TestAutofac = function () { return Http.get('/api/SysUser/TestAutofac'); }
This is the address of the interface where we built the backend framework and the demo example before.
After doing the above work, the entire response interception and request interception of the basic code writing is completed, the next step is to test.
IV. Testing
Add the following code to the UI (you can also create a new vue page)
<template> <div>subscribers</div> </template> <script lang="ts"> import { defineComponent, onMounted } from "vue"; import { TestAutofac } from "../../api/module/user"; export default defineComponent({ setup() { //initial load onMounted(() => { TestAutofacMsg(); }); //invoke an interface const TestAutofacMsg = async () => { var result = await TestAutofac(); (result); }; return {}; }, components: {}, }); </script>
Click on the user menu to test if the request interception was successful
The interception is successful, but the following error occurs (cross-domain issue)
The above problem is caused by cross-domain issue, we have to configure the cross-domain address on the interface side.
Open our previous backend framework and create the following file, with the path in the same location as the jwt authentication, global exception catching plugin.
/// <summary> /// Cross Domain Configuration Plugin /// </summary> public static class CrossDomainPlugIn { /// <summary> /// cross-domain /// </summary> /// <param name="services"></param> public static void InitCors(this IServiceCollection services) { //Allow one or more sources to cross domains (options => { ("Access-Control-Allow-Origin", policy => { var result = ("CustomCorsPolicy:WhiteList").Split(','); // Set the sources that are allowed to cross domains, more than one can be separated by ',' (result) .AllowAnyHeader() .AllowAnyMethod() .AllowCredentials(); }); }); } }
Then in the file, add
// Cross-domain configuration
(); and ("Access-Control-Allow-Origin"); code
Add the following configuration to the configuration, the address is the front-end access address
/* across settings */
"AllowedHosts": "*",
"CustomCorsPolicy": {
"WhiteList": "http://localhost:8080"
},
Start the back-end interface, under test
That's all there is to this post, thanks for your patience!
Backend WebApiPreview at http://139.155.137.144:8880/swagger/
Frontend vue preview at http://139.155.137.144:8881
Follow the public number: send [permission], get the front and back end code
If you are interested, please pay attention to my weibo public number (*^▽^*).
Follow me: a full-stack multi-terminal treasure blogger, regularly sharing technical articles, irregularly sharing open source projects. Follow me to bring you to know a different program world!