配置拦截器(不拦截登录、注册请求),对所有请求进行拦截,验证session中保存的登录用户是否存在,如果不存在,说明用户已经下线,清空session,强制返回登录页面。
在SpringMVC配置文件中配置拦截器,对文件上传、用户登录、注册不作拦截。
<!-- 配置拦截器 -->
<mvc:interceptors>
<!-- 使用bean定义一个Interceptor,直接定义在mvc:interceptors根下面的Interceptor将拦截所有的请求 -->
<!-- session失效拦截器 -->
<mvc:interceptor>
<!-- 匹配的是url路径, 如果不配置或/**,将拦截所有的Controller请求 -->
<mvc:mapping path="/**" />
<!-- 不需要拦截的请求地址 -->
<mvc:exclude-mapping path="/file/**.html" /><!-- 文件上传请求 -->
<mvc:exclude-mapping path="/login.html" /><!-- 用户登录的请求 -->
<bean class="lxkj.zz07.interceptor.MyLoginInterceptor"></bean>
</mvc:interceptor>
</mvc:interceptors>
12345678910111213
通过实现HandleInterceptor接口,来定义用户拦截器类,重写preHandle方法,该方法将在Controller处理之前进行调用,SpringMVC中的Interceptor拦截器是链式的,可以同时存在 多个Interceptor,然后SpringMVC会根据声明的前后顺序一个接一个的执行,而且所有的Interceptor中的preHandle方法都会在 Controller方法调用之前调用。
SpringMVC的这种Interceptor链式结构也是可以进行中断的,这种中断方式是令preHandle的返 回值为false,当preHandle的返回值为false的时候整个请求就结束了。
Web应用的安全管理,主要包括两个方面的内容,一个是用户身份的认证,即用户登录的设计,二是用户授权,即一个用户在一个应用系统中能够执行哪些操作的权限管理。权限管理的设计一般使用角色来管理,即给一个用户赋予哪些角色,这个用户就具有哪些权限。
Spring框架体系中,经典的安全体系框架是Security。关于系统的安全管理及各种设计,Spring Security已经大体上都实现了,只需要一些配置和引用就能够正常使用。SpringBoot使用Security更加的简单,因为SpringBoot本身的简单配置使用加上Security的功能丰富全面,可用快速帮助我们构建完善的登陆认证服务。
关于Security,SpringBoot本身有spring-boot-starter-security依赖组件,Spring Cloud微服务全家桶中也有spring-cloud-starter-security依赖组件,并且spring-cloud-starter-security中也包含了spring-boot-starter-security,下面的学习中,会先使spring-boot-starter-security,然后再spring-cloud-starter-security学习安全管理的功能,从SpringBoot单体的登陆注册和权限管理,到Spring Cloud微服务中构建认证和授权服务,都会一一接触到。
关于版本的问题,我从SpringBoot1.3.x版的使用到2.1.x的使用,Security的配置也经历了不小的变化,最准确的配置建议去官网文档学习。下面的学习中,将使用2.1.5版本,官方文档地址是: https://docs.spring.io/spring-boot/docs/2.1.5.RELEASE/reference/htmlsingle/ 。 Security的源码非常复杂,因此我们后面再讨论深层次的东西,现在来用实例进行入门学习。
先来看一个入门例子,springboot项目结构我们都很熟悉,先来看依赖:
依赖很简单,除了一个web组件和thymeleaf视图组件,就是一个security。接下来看一下启动类:
可以看到启动类没有任何特殊的配置。至于配置文件,我们简单的配置一下端口,其它不做任何配置:
这样一个简单的入门例子就完成了,现在来启动项目,启动日志很短,可以看到有一行特殊的日志:
这是我们加入了security组件的依赖之后,引入了security的默认配置,此时就有了一个简单的登录功能,打印出的一行是默认密码的信息,这个密码是现在没有任何代码和配置的状态下每次启动随机生成的,security不仅会生成一个默认密码,依赖组件中还有一个默认的登陆链接/login,还有一个默认的用户名 user,而且在springboot2.1.x版本中,这个/login有一个非常不错的默认登录页面,下面进行测试:
用户名输入user,密码输入日志中打印出的随机密码,登录成功后,就会跳转到默认地址,默认成功的地址就是登录地址去掉/login,
现在没有定义任何链接匹配这个地址,我们来定义一个简单的页面,在resource下面,新建一个templates文件夹,在templates下面新建一个主页 home.html,内容如下:
然后定义一个controller跳转到这个页面:
这样我们登陆成功后,就能自动跳转到这个页面:
这样,一个最简单的登录流程就完成了,我们几乎没有做任何配置,只是引入了一个依赖而已。下面我们给security配置一个默认用户名密码,这样就不用每次启动都用随机密码,直接在springboot的默认配置文件中配置:
这样等登陆就可以使用 admin/admin登陆了。
代码地址 :https://gitee.com/blueses/spring-boot-security 01
权限控制,最常见的基本上有 2 种
这个两种到底有什么不同呢?
我们通过下图来分析一下
添加图片注释,不超过 140 字(可选)
ACL 是基于 用户 -> 权限,直接为每个用户分配权限 RBAC 基于 用户 -> 角色 -> 权限,以角色为媒介,来为每个用户分配权限 这样做的好处是,某个权限过于敏感时,想要将每个用户或者部分用户的权限去掉,就不需要每个用户的权限都操作一遍,只需要删除对应角色的权限即可 那在实际的开发中 RBAC 是最常用的权限控制方案,就前端而言,RBAC 主要如何实现的呢? 主要就两个部分
下面我们就来实现这两个部分
页面的访问,我们都是需要配置路由表的,根据配置路由表的路径来访问页面 那么,我们控制了路由表,不就能控制页面的访问了吗? 实现思路
基本环境
创建项目
npm install -g @vue/cli
vue --version # @vue/cli 5.0.8
vue create vue-router-dome
添加图片注释,不超过 140 字(可选)
打开项目,npm run serve运行一下
添加图片注释,不超过 140 字(可选)
代码初始化,删除不必要的一些文件
添加图片注释,不超过 140 字(可选)
我们创建几个新文件夹
添加图片注释,不超过 140 字(可选)
写下基本的页面
添加图片注释,不超过 140 字(可选)
<!-- home.vue -->
<template>
<div>主页</div>
</template>
<!-- menu.vue -->
<template>
<div>菜单管理</div>
</template>
<!-- user.vue -->
<template>
<div>用户管理</div>
</template>
写下路由配置
添加图片注释,不超过 140 字(可选)
// remaining.ts
import Layout from '@/layout/index.vue'
const remainingRouter: AppRouteRecordRaw[]=[
{
path: '/remaining',
component: Layout,
redirect: 'home',
children: [
{
path: '/remaining/home',
component: ()=> import('@/views/home.vue'),
name: '首页',
meta: {},
}
],
name: '主页管理',
meta: undefined
},
]
export default remainingRouter
remaining 主要为了存放一些公共路由,没有权限页可以访问,比如登录页、404页面这些
因为是用 typescript 编写的,我们需要加一下声明文件,定义下 remainingRouter 的类型
添加图片注释,不超过 140 字(可选)
// router.d.ts
import type { RouteRecordRaw } from 'vue-router'
import { defineComponent } from 'vue'
declare module 'vue-router' {
interface RouteMeta extends Record<string | number | symbol, unknown> {
hidden?: boolean
alwaysShow?: boolean
title?: string
icon?: string
noCache?: boolean
breadcrumb?: boolean
affix?: boolean
activeMenu?: string
noTagsView?: boolean
followAuth?: string
canTo?: boolean
}
}
type Component<T=any>=| ReturnType<typeof defineComponent>
| (()=> Promise<typeof import('*.vue')>)
| (()=> Promise<T>)
declare global {
interface AppRouteRecordRaw extends Omit<RouteRecordRaw, 'meta'> {
name: string
meta: RouteMeta
component?: Component | string
children?: AppRouteRecordRaw[]
props?: Recordable
fullPath?: string
keepAlive?: boolean
}
interface AppCustomRouteRecordRaw extends Omit<RouteRecordRaw, 'meta'> {
icon: any
name: string
meta: RouteMeta
component: string
componentName?: string
path: string
redirect: string
children?: AppCustomRouteRecordRaw[]
keepAlive?: boolean
visible?: boolean
parentId?: number
alwaysShow?: boolean
}
}
接下来编写,创建路由、导出路由
import type { App } from 'vue'
import type { RouteRecordRaw } from 'vue-router'
import { createRouter, createWebHashHistory } from 'vue-router'
import remainingRouter from './modules/remaining'
// 创建路由实例
const router=createRouter({
history: createWebHashHistory(), // createWebHashHistory URL带#,createWebHistory URL不带#
strict: true,
routes: remainingRouter as RouteRecordRaw[],
scrollBehavior: ()=> ({ left: 0, top: 0 })
})
// 导出路由实例
export const setupRouter=(app: App<Element>)=> {
app.use(router)
}
export default router
在main.ts中导入下
import { createApp } from 'vue'
import App from './App.vue'
import { setupRouter } from './router/index' // 路由
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
// 创建实例
const setupAll=async ()=> {
const app=createApp(App)
setupRouter(app)
app.mount('#app')
}
setupAll()
接下来写下 Layout 架构
我们要实现的效果,是一个后台管理页面的侧边栏,点击菜单右边就能跳转到对应路由所在页面
添加图片注释,不超过 140 字(可选)
创建
AppMain.vue 右边路由跳转页
Sidebar.vue 侧边栏
index.vue 作为 layout 架构的统一出口
添加图片注释,不超过 140 字(可选)
<!--
@description: AppMain
-->
<template>
<div>
<router-view v-slot="{ Component, route }">
<transition name="fade-transform" mode="out-in"> <!-- 设置过渡动画 -->
<keep-alive>
<component :is="Component" :key="route.fullPath" />
</keep-alive>
</transition>
</router-view>
</div>
</template>
上面是一种动态路由的固定写法,需要与的路由配置进行对应 其中最主要的就是 <component :is="Component" :key="route.fullPath" /> 中的 key,这是为确定路由跳转对应页面的标识,没这个就跳不了 有一个小知识点
//路径:http://127.0.0.1:3000/user?id=1
console.log(route.path) // 输出 /user
console.log(route.fullPath) // 输出 /user?id=1
为了实现右边侧边栏,需要引入element plus来快速搭建
pnpm install element-plus
main.ts改造一下,完整引入element-plus
import { createApp } from 'vue'
import App from './App.vue'
import ElementPlus from 'element-plus' // element-plus 组件库
import 'element-plus/dist/index.css' // element-plus 组件库样式文件
// 创建实例
const setupAll=async ()=> {
const app=createApp(App)
app.use(ElementPlus)
app.mount('#app')
}
setupAll()
我们来编写下 侧边栏
<!--
@description: Sidebar
-->
<template>
<div>
<el-menu active-text-color="#ffd04b" background-color="#304156" default-active="2" text-color="#fff" router>
<el-sub-menu :index="item.path" v-for="item in routers">
<template #title>{{ item.name }}</template>
<el-menu-item :index="child.path" v-for="child in item.children">{{ child.name }}</el-menu-item>
</el-sub-menu>
</el-menu>
</div>
</template>
<script setup lang='ts'>
import { filterRoutes } from '@/utils/router';
import { computed } from 'vue';
import { useRouter } from 'vue-router';
const router=useRouter()
// 通过计算属性,路由发生变化时更新路由信息
const routers=computed(()=> {
return filterRoutes(router.getRoutes()) // router.getRoutes() 用于获取路由信息
})
</script>
统一导出 layout 架构,加一点小样式
<!--
@description: layout index
-->
<template>
<div class="app-wrapper">
<Sidebar class="sidebar-container" />
<App-Main class="main-container" />
</div>
</template>
<script setup lang='ts'>
import { ref, reactive } from 'vue'
import Sidebar from './components/Sidebar.vue'
import AppMain from './components/AppMain.vue'
</script>
<style scoped>
.app-wrapper {
display: flex;
}
.sidebar-container {
width: 200px;
height: 100vh;
background-color: #304156;
color: #fff;
}
.main-container {
flex: 1;
height: 100vh;
background-color: #f0f2f5;
}
</style>
pnpm run serve运行一下
添加图片注释,不超过 140 字(可选)
通常我们实现页面权限管理,比较常见的方案是,有权限的路由信息由后端传给前端,前端再根据路由信息进行渲染
我们先安装下 pinia 模拟下后端传过来的数据
pnpm install pinia
添加图片注释,不超过 140 字(可选)
import { defineStore } from "pinia";
interface AuthStore {
// 菜单
menus: any[];
}
export const useAuthStore=defineStore("authState", {
state: (): AuthStore=> ({
menus: [
{
path: "/routing",
component: null,
redirect: "user",
children: [
{
path: "/routing/user",
component: "/user.vue",
name: "用户管理",
meta: {},
},
{
path: "/routing/menu",
component: "/menu.vue",
name: "菜单管理",
meta: {},
}
],
name: "系统管理",
meta: undefined,
},
]
}),
getters: {},
actions: {},
});
好了,我们把模拟的路由数据,加到本地路由中
添加图片注释,不超过 140 字(可选)
// permission.ts
import router from './router'
import type { RouteRecordRaw } from 'vue-router'
import { formatRoutes } from './utils/router'
import { useAuthStore } from '@/store';
import { App } from 'vue';
// 路由加载前
router.beforeEach(async (to, from, next)=> {
const { menus }=useAuthStore()
routerList.forEach((route)=> {
router.addRoute(menus as unknown as RouteRecordRaw) // 动态添加可访问路由表
})
next()
})
// 路由跳转之后调用
router.afterEach((to)=> { })
添加图片注释,不超过 140 字(可选)
添加图片注释,不超过 140 字(可选)
报错了,为什么呢?
对比路由表的数据,原来,组件模块的数据与公共路由的数据不一致
添加图片注释,不超过 140 字(可选)
我们需要把模拟后端传过来的数据处理一下
添加图片注释,不超过 140 字(可选)
// router.ts
import Layout from '@/layout/index.vue';
import type { RouteRecordRaw } from 'vue-router'
/* 处理从后端传过来的路由数据 */
export const formatRoutes=(routes: any[])=> {
const formatedRoutes: RouteRecordRaw[]=[]
routes.forEach(route=> {
formatedRoutes.push(
{
...route,
component: Layout, // 主要是将这个 null -> 组件
children: route.children.map((child: any)=> {
return {
...child,
component: ()=> import(`@/views${child.component}`), // 根据 本地路径配置页面路径
}
}),
}
)
})
return formatedRoutes;
}
再修改下permission.ts
import router from './router'
import type { RouteRecordRaw } from 'vue-router'
import { formatRoutes } from './utils/router'
import { useAuthStore } from '@/store';
import { App } from 'vue';
// 路由加载前
router.beforeEach(async (to, from, next)=> {
const { menus }=useAuthStore()
const routerList=menus
routerList.forEach((route)=> {
router.addRoute(route as unknown as RouteRecordRaw) // 动态添加可访问路由表
})
next()
})
// 路由跳转之后调用
router.afterEach((to)=> { })
main.ts引入一下
import './permission'
可以正常访问了
添加图片注释,不超过 140 字(可选)
除了页面权限,外我们还有按钮权限
可以通过自定义指令来完成,permission.ts 中定义一下
添加图片注释,不超过 140 字(可选)
/* 按钮权限 */
export function hasPermi(app: App<Element>) {
app.directive('hasPermi', (el, binding)=> {
const { permissions }=useAuthStore()
const { value }=binding
const all_permission='*:*:*'
if (value && value instanceof Array && value.length > 0) {
const permissionFlag=value
const hasPermissions=permissions.some((permission: string)=> {
return all_permission===permission || permissionFlag.includes(permission)
})
if (!hasPermissions) {
el.parentNode && el.parentNode.removeChild(el)
}
} else {
throw new Error('权限不存在')
}
})
}
export const setupAuth=(app: App<Element>)=> {
hasPermi(app)
}
需要挂载到main.ts
import { createApp } from 'vue'
import App from './App.vue'
import { setupRouter } from './router/index'
import ElementPlus from 'element-plus'
import { createPinia } from 'pinia'
import { setupAuth } from './permission'
import 'element-plus/dist/index.css'
import './permission'
// 创建实例
const setupAll=async ()=> {
const app=createApp(App)
setupRouter(app)
setupAuth(app)
app.use(ElementPlus)
app.use(createPinia())
app.mount('#app')
}
setupAll()
还是在store那里加一下模拟数据
export const useAuthStore=defineStore("authState", {
state: (): AuthStore=> ({
menus: [
{
path: "/routing",
component: null,
redirect: "user",
children: [
{
path: "/routing/user",
component: "/user.vue",
name: "用户管理",
meta: {},
},
{
path: "/routing/menu",
component: "/menu.vue",
name: "菜单管理",
meta: {},
}
],
name: "系统管理",
meta: undefined,
},
],
permissions: [
// '*:*:*', // 所有权限
'system:user:create',
'system:user:update',
'system:user:delete',
]
}),
});
user.vue加入几个按钮,使用自定义指令
<!-- user.vue -->
<template>
<div>
<el-button type="primary" v-hasPermi="['system:user:create']">创建</el-button>
<el-button type="primary" v-hasPermi="['system:user:update']">更新</el-button>
<el-button type="primary" v-hasPermi="['system:user:delete']">删除</el-button>
<el-button type="primary" v-hasPermi="['system:user:admin']">没权限</el-button>
</div>
</template>
system:user:admin这个权限没有配置,无法显示
添加图片注释,不超过 140 字(可选)
加一下权限
添加图片注释,不超过 140 字(可选)
添加图片注释,不超过 140 字(可选)
用户权限我们使用 v-hasPermi自定义指令,其原理是通过删除当前元素,来实现隐藏
如果使用 Element Plus 的标签页呢
我们在 src/views/home.vue 写一下基本样式
<!--
@description: 主页
-->
<template>
<div>
<el-tabs>
<el-tab-pane label="标签一" name="first">标签一</el-tab-pane>
<el-tab-pane label="标签二" name="second">标签二</el-tab-pane>
</el-tabs>
</div>
</template>
<script setup lang='ts'>
</script>
添加图片注释,不超过 140 字(可选)
我们加下按钮权限控制
<template>
<div>
<el-tabs v-model="activeName">
<el-tab-pane label="标签一" v-hasPermi="['system:tabs:first']" name="first">标签一</el-tab-pane>
<el-tab-pane label="标签二" name="second">标签二</el-tab-pane>
</el-tabs>
</div>
</template>
添加图片注释,不超过 140 字(可选)
因为这个权限我们没有配置,标签页内容隐藏了,这没问题
但是,标签没隐藏啊,通常要是标签一没权限,应该是标签项、和标签内容都隐藏才对
为什么会这样呢?
我们在 hasPermi 自定义指令中,打印下获取到的元素
添加图片注释,不超过 140 字(可选)
添加图片注释,不超过 140 字(可选)
id 为pane-first、pane-second元素对应位置在哪里,我们找一下 需要先把指令去掉,因为元素都被我们删除的话,我们看不到具体DOM结构
添加图片注释,不超过 140 字(可选)
添加图片注释,不超过 140 字(可选)
添加图片注释,不超过 140 字(可选)
对比一下,明显可以看出 hasPermi 自定义指令获取到只是标签内容的元素 那怎么办? 解决办法一:根据当前元素,一层层找到标签项,然后删除,这样是可以。但是这样太麻烦了,也只能用于标签页,那要是其他组件有这样的问题咋办 解决办法二:我们写一个函数判断权限是否存在,再通过 v-if 进行隐藏
*请认真填写需求信息,我们会在24小时内与您取得联系。