SpringSecurity
1. SpringSecurity 框架简介
Spring 是非常流行和成功的 Java 应用开发框架,Spring Security 正是 Spring 家族中的成员。Spring Security 基于 Spring 框架,提供了一套 Web 应用安全性的完整解决方 案。
正如你可能知道的关于安全方面的两个主要区域是“认证”和“授权”(或者访问控 制),一般来说,Web 应用的安全性包括用户认证(Authentication)和用户授权 **(Authorization)**两个部分,这两点也是 Spring Security 重要核心功能。
(1)用户认证指的是:验证某个用户是否为系统中的合法主体,也就是说用户能否访问 该系统。用户认证一般要求用户提供用户名和密码。系统通过校验用户名和密码来完成认 证过程。通俗点说就是系统认为用户是否能登录
(2)用户授权指的是验证某个用户是否有权限执行某个操作。在一个系统中,不同用户 所具有的权限是不同的。比如对一个文件来说,有的用户只能进行读取,而有的用户可以 进行修改。一般来说,系统会为不同的用户分配不同的角色,而每个角色则对应一系列的 权限。通俗点讲就是系统判断用户是否有权限去做某些事情。
2. SpringSecurity入门案例 (认证)
2.1. 创建maven工程(web工程)加入依赖
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<spring.version>5.0.4.RELEASE</spring.version>
<spring.security.version>5.0.1.RELEASE</spring.security.version>
</properties>
<dependencies>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.6</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>5.1.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>${spring.security.version}</version>
</dependency>
<dependency>
<groupId>javax.annotation</groupId>
<artifactId>jsr250-api</artifactId>
<version>1.0</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>${spring.security.version}</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<plugins>
<!-- java编译插件 -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<configuration>
<!-- 指定端口 -->
<port>8080</port>
<!-- 请求路径 -->
<path>/</path>
</configuration>
</plugin>
</plugins>
</build>
2.2 创建页面
-
登录页面(login.jsp)
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> <link rel="icon" href="图标路径;base64,aWNv"> </head> <body> <h1>login.jsp</h1> <form action="/login" method="post"> 用户名:<input type="text" name="username" value=""><br> 密码:<input type="password" name="password" value=""><br> <input type="submit" value="登录"> </form> </body> </html>
-
登录失败页面(fail.jsp)
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <h1>登录失败</h1> </body> </html>
-
登录成功页面(index.jsp)
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <h1>登录成功</h1> </body> </html>
2.3 resource下创建spring-security.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:security="http://www.springframework.org/schema/security"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security.xsd">
<!-- 配置不过滤的资源(静态资源及登录相关) -->
<security:http pattern="/login.jsp" security="none"/>
<security:http pattern="/fail.jsp" security="none"/>
<security:http pattern="/css/**" security="none"/>
<security:http pattern="/img/**" security="none"/>
<security:http pattern="/js/**" security="none"/>
<!--
http:用于定义相关权限控制
auto-config:是否自动配置
设置为true时框架会提供默认的一些配置,例如提供默认的登录页面、登出处理等
设置为false时需要显示提供登录表单配置,否则会报错
use-expressions:用于指定intercept-url中的access属性是否使用SPEL表达式-->
<security:http auto-config="true" use-expressions="false">
<!--intercept-url: 指定哪些资源不需要进行权限校验,可以使用通配符-->
<!-- 配置资源连接,访问任何资源,都需要拥有ROLE_USER或者ROLE_ADMIN任意一个角色 -->
<security:intercept-url pattern="/**" access="ROLE_USER,ROLE_ADMIN"/>
<!--登录:
1. login-page 自定义登录页url,默认为/login
2. login-processing-url form表单提交时指定的action
3. default-target-url 默认登录成功后跳转的url
4. authentication-failure-url 登录失败后跳转的url
5. username-parameter 用户名的请求字段 默认为userName
6. password-parameter 密码的请求字段 默认为password-->
<security:form-login login-page="/login.jsp"
login-processing-url="/login" username-parameter="username"
password-parameter="password"
authentication-failure-url="/fail.jsp"
default-target-url="/index.jsp" />
<!-- 登出:
invalidate-session 是否删除session
logout-url:登出处理链接
logout-success-url:登出成功页面
注:登出操作 只需要链接到 logout即可登出当前用户 -->
<security:logout invalidate-session="true" logout-url="/logout"
logout-success-url="/login.jsp"/>
<!-- 关闭CSRF,默认是开启的 跨域攻击-->
<!--csrf:对应CsrfFilter过滤器
disabled:是否启用CsrfFilter过滤器,如果使用自定义登录页面需要关闭此项,
否则登录操作会被禁用(403)
(自定义登录页面,,框架认为我们的页面不安全,
需要关闭验证过滤器,默认登录页面有隐藏域,_scrf ,如果使用自定义登录页面,
没有关闭验证过滤器,框架会拒绝访问.)
-->
<security:csrf disabled="true"/>
</security:http>
<!--authentication-manager:认证管理器,用于处理认证操作-->
<security:authentication-manager>
<!--authentication-provider:认证提供者,执行具体的认证逻辑-->
<security:authentication-provider>
<!-- user-service:用于获取用户信息,提供给authentication-provider进行认证-->
<security:user-service>
<!--自定义用户名密码-->
<!--
user:定义用户信息,可以指定用户名、密码、角色,后期可以改为从数据库查询用户信息
{noop}:表示当前使用的密码为明文
-->
<!--{noop}:spring security默认是加密认证,添加此字段表示不加密认证。
user用户拥有book:add权限和ROLE_USER角色-->
<security:user name="user" password="{noop}user123"
authorities="book:add,ROLE_USER"/>
<security:user name="admin" password="{noop}admin123"
authorities="ROLE_ADMIN"/>
</security:user-service>
</security:authentication-provider>
</security:authentication-manager>
</beans>
2.4 web.xml配置
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<display-name>Archetype Created Web Application</display-name>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-security.xml</param-value>
</context-param>
<!--
1. DelegatingFilterProxy用于整合第三方框架
整合Spring Security时过滤器的名称必须为springSecurityFilterChain,
否则会抛出NoSuchBeanDefinitionException异常
2. DelegatingFilterProxy是Spring的Web模块中的一个类,
它提供了让HTTP请求在到达实际目的地之前通过过滤器的功能。
-->
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
</web-app>
2.5 项目结构
2.6 启动tomcat
2.7 访问页面
登录成功后跳转到:http://localhost:8080/ 根路径中,展示的是index.jsp页面:
3. 权限管理
3.1 创建maven的web工程并加入依赖
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<spring.version>5.0.4.RELEASE</spring.version>
<spring.security.version>5.0.1.RELEASE</spring.security.version>
</properties>
<dependencies>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.6</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>5.1.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>${spring.security.version}</version>
</dependency>
<dependency>
<groupId>javax.annotation</groupId>
<artifactId>jsr250-api</artifactId>
<version>1.0</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>${spring.security.version}</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<plugins>
<!-- java编译插件 -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<configuration>
<!-- 指定端口 -->
<port>8080</port>
<!-- 请求路径 -->
<path>/</path>
</configuration>
</plugin>
</plugins>
</build>
</project>
3.2 创建springmvc.xml文件
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<context:component-scan base-package="com.jz" use-default-filters="false">
<context:include-filter type="annotation"
expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<mvc:annotation-driven></mvc:annotation-driven>
<mvc:default-servlet-handler></mvc:default-servlet-handler>
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
<!--
支持AOP的注解支持,AOP底层使用代理技术
JDK动态代理,要求必须有接口
cglib代理,生成子类对象,proxy-target-class="true" 默认使用cglib的方式
-->
<aop:aspectj-autoproxy proxy-target-class="true"/>
</beans>
3.3 spring-security.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:security="http://www.springframework.org/schema/security"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security.xsd">
<!-- 配置不过滤的资源(静态资源及登录相关) -->
<security:http pattern="/login.jsp" security="none"/>
<security:http pattern="/fail.jsp" security="none"/>
<security:http pattern="/css/**" security="none"/>
<security:http pattern="/img/**" security="none"/>
<security:http pattern="/js/**" security="none"/>
<!--
http:用于定义相关权限控制
auto-config:是否自动配置
设置为true时框架会提供默认的一些配置,例如提供默认的登录页面、登出处理等
设置为false时需要显示提供登录表单配置,否则会报错
use-expressions="false":禁用spEL表达式-->
<security:http auto-config="true" use-expressions="false">
<!-- 配置资源连接,访问任何资源,都需要拥有ROLE_USER或者ROLE_ADMIN任意一个角色 -->
<security:intercept-url pattern="/**" access="ROLE_USER,ROLE_ADMIN"/>
<!--登录:
1. login-page 自定义登录页url,默认为/login
2. login-processing-url form表单提交时指定的action
3. default-target-url 默认登录成功后跳转的url
4. authentication-failure-url 登录失败后跳转的url
5. username-parameter 用户名的请求字段 默认为userName
6. password-parameter 密码的请求字段 默认为password-->
<security:form-login login-page="/login.jsp"
login-processing-url="/login" username-parameter="username"
password-parameter="password" authentication-failure-url="/fail.jsp"
default-target-url="/index.jsp" />
<!-- 登出:
invalidate-session 是否删除session
logout-url:登出处理链接
logout-success-url:登出成功页面
注:登出操作 只需要链接到 logout即可登出当前用户 -->
<security:logout invalidate-session="true" logout-url="/logout"
logout-success-url="/login.jsp"/>
<!-- 关闭CSRF,默认是开启的 跨域攻击-->
<security:csrf disabled="true"/>
<!-- 尝试访问没有权限的页面时跳转的页面 -->
<security:access-denied-handler error-page="/error-noauth.jsp"/>
</security:http>
<!--SpringSecurity认证管理器-->
<security:authentication-manager>
<security:authentication-provider>
<security:user-service>
<!--自定义用户名密码-->
<!--{noop}:spring security默认是加密认证,添加此字段表示不加密认证。-->
<security:user name="user" password="{noop}user123"
authorities="book:add,ROLE_USER"/>
<security:user name="admin" password="{noop}admin123"
authorities="ROLE_ADMIN"/>
</security:user-service>
</security:authentication-provider>
</security:authentication-manager>
<!--开启jsr250注解-->
<security:global-method-security jsr250-annotations="enabled"
pre-post-annotations="enabled"
secured-annotations="enabled"/>
</beans>
3.4 创建以下页面
-
index.jsp (登录成功主页)
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <span style="color: blue;font-size: 20px"> 【当前登录用户[${sessionScope.SPRING_SECURITY_CONTEXT.authentication.principal.username}]】 </span> <h1>主页--->登录成功</h1> <a href="/logout">退出</a><br/><hr> <a href="/book/list">书籍列表</a><br/><hr> <a href="/book/add">新增书籍</a><br/><hr> <a href="/book/update">书籍用户</a><br/><hr> <a href="/book/delete">删除书籍</a><br/><hr> </body> </html>
-
login.jsp(登录页面)
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> <link rel="icon" href="图标路径;base64,aWNv"> </head> <body> <h1>login.jsp</h1> <form action="/login" method="post"> 用户名:<input type="text" name="username" value=""><br> 密码:<input type="password" name="password" value=""><br> <input type="submit" value="登录"> </form> </body> </html>
-
main.jsp(书籍管理主页)
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <h1>书籍管理页面</h1> <h2>${msg}</h2> </body> </html>
-
fail.jsp(登录失败页面)
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <h1 style="background: hotpink">登录失败</h1> </body> </html>
-
error-noauth.jsp(没有权限跳转页面)
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <h1 style="color: red">您无权访问</h1> </body> </html>
3.5 创建BookController
package com.jz.controller;
import org.springframework.security.access.annotation.Secured;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("book")
public class BookController {
@GetMapping("/list")
//@PreAuthorize("hasAnyAuthority('book:list')")
public String bookList(Model model) {
System.out.println("访问书籍查询界面成功!");
model.addAttribute("msg","访问书籍查询界面成功!");
return "main";
}
@GetMapping("/add")
//@PreAuthorize("hasAnyAuthority('book:add','book:insert')")
public String bookAdd(Model model) {
System.out.println("访问书籍新增界面成功!");
model.addAttribute("msg","访问书籍新增界面成功!");
return "main";
}
@GetMapping("/update")
//必须有book:edit权限才能访问bookUpdate方法
//@PreAuthorize("hasAnyAuthority('book:edit')")
public String bookUpdate(Model model) {
System.out.println("访问书籍修改界面成功!");
model.addAttribute("msg","访问书籍修改界面成功!");
return "main";
}
@GetMapping("/delete")
//只要具有"ROLE_USER","ROLE_ADMIN"任意一种角色就可以访问。
//@Secured({"ROLE_USER", "ROLE_ADMIN"})
public String bookDelete(Model model) {
System.out.println("访问书籍删除界面成功!");
model.addAttribute("msg","访问书籍删除界面成功!");
return "main";
}
}
3.6 web.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<display-name>Archetype Created Web Application</display-name>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-security.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<!--
DelegatingFilterProxy是Spring的Web模块中的一个类,
它提供了让HTTP请求在到达实际目的地之前通过过滤器的功能。
-->
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter
</filter-class>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<servlet>
<servlet-name>dispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
3.7 测试
登录:
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-0p78F2Pz-1687834244153)(image/1686296507798.png)]
主页:
权限测试:点击书籍列表由于user用户没有book:list权限所以访问失败:
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-QIlWoTTs-1687834244154)(image/1686296621698.png)]
4. 数据库读取用户、权限、角色信息
由于用户名和密码都是设置的固定的,正常我们应该从数据库读取用户名密码信息;
由于权限角色也是设置的固定的,正常也应该从数据库中读取;下面说一下如何从数据库读取用户名、密码、角色、权限信息;
4.1 表结构
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-IFwQY7dv-1687834244154)(image/1686493595955.png)]
4.2 创建表
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-sARELHbb-1687834244155)(image/1686493657040.png)]
4.3 创建maven的web工程并加入依赖
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<spring.version>5.0.4.RELEASE</spring.version>
<spring.security.version>5.0.1.RELEASE</spring.security.version>
</properties>
<dependencies>
<!--mysql的驱动包-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.38</version>
</dependency>
<!--mybatis核心-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.6</version>
</dependency>
<!--spring整合mybatis-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.2</version>
</dependency>
<!--加入分页的依赖-->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>5.1.10</version>
</dependency>
<!--导入C3P0连接池-->
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.2</version>
</dependency>
<!--junit-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<!--日志包-->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.6</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<!--Jackson依赖-->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.9</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>5.1.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>${spring.security.version}</version>
</dependency>
<dependency>
<groupId>javax.annotation</groupId>
<artifactId>jsr250-api</artifactId>
<version>1.0</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>${spring.security.version}</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<plugins>
<!-- java编译插件 -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<configuration>
<!-- 指定端口 -->
<port>8080</port>
<!-- 请求路径 -->
<path>/</path>
</configuration>
</plugin>
</plugins>
</build>
</project>
4.3 创建实体类
user类:
package com.jz.pojo;
import java.io.Serializable;
public class User implements Serializable {
private Integer id;
private String email;
private String username;
private String password;
private String phoneNum;
private Integer status;//是否可用(1 可用 2不可用)
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getPhoneNum() {
return phoneNum;
}
public void setPhoneNum(String phoneNum) {
this.phoneNum = phoneNum;
}
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
}
Permission类
package com.jz.pojo;
import java.io.Serializable;
public class Permission implements Serializable {
private Integer id;
private String permissionName;
private String url;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getPermissionName() {
return permissionName;
}
public void setPermissionName(String permissionName) {
this.permissionName = permissionName;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
}
Role类:
package com.jz.pojo;
import java.io.Serializable;
public class Role implements Serializable {
private Integer id;
private String roleName;
private String roleDesc;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getRoleName() {
return roleName;
}
public void setRoleName(String roleName) {
this.roleName = roleName;
}
public String getRoleDesc() {
return roleDesc;
}
public void setRoleDesc(String roleDesc) {
this.roleDesc = roleDesc;
}
}
4.4 mapper接口
UserMapper
package com.jz.mapper;
import com.jz.pojo.User;
public interface UserMapper {
//登录的方法
public User getUserByUsernamePassword(String username);
}
RoleMapper
package com.jz.mapper;
import com.jz.pojo.Role;
import java.util.List;
public interface RoleMapper {
/**
* 根据用户ID查询角色信息
* @param userId
* @return
*/
List<Role> selectRolesByUserId(Integer userId);
}
PermissionMapper
package com.jz.mapper;
import com.jz.pojo.Permission;
import java.util.List;
public interface PermissionMapper {
/**
* 根据用户ID查询权限
* @param userId
* @return
*/
List<Permission> selectPermissionsByUserId(Integer userId);
}
4.5 mapper.xml文件
UserMapper.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.jz.mapper.UserMapper">
<!--根据用户名和密码查询可用的用户-->
<select id="getUserByUsernamePassword" resultType="User">
select * from users where username=#{username}
and status=1
</select>
</mapper>
RoleMapper.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.jz.mapper.RoleMapper">
<select id="selectRolesByUserId" resultType="Role">
SELECT * FROM role WHERE id
IN (SELECT r.id FROM role r,users_role ur
WHERE r.id=ur.roleId AND userId=#{userId})
</select>
</mapper>
Permission.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.jz.mapper.PermissionMapper">
<select id="selectPermissionsByUserId" resultType="Permission">
SELECT * FROM permission WHERE id IN(
SELECT permissionId FROM role_permission WHERE roleId IN(
SELECT roleId FROM users_role WHERE userId=#{userId}));
</select>
</mapper>
4.6 权限角色查询的配置类
MyUserDetailsService.java
package com.jz.service;
import com.jz.mapper.PermissionMapper;
import com.jz.mapper.RoleMapper;
import com.jz.mapper.UserMapper;
import com.jz.pojo.Permission;
import com.jz.pojo.Role;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
@Service("myUserDetailsService")
public class MyUserDetailsService implements UserDetailsService {
@Autowired
private UserMapper userMapper;
@Autowired
private RoleMapper roleMapper;
@Autowired
private PermissionMapper permissionMapper;
//数据库查询权限角色信息
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
//认证用户
com.jz.pojo.User user= userMapper.getUserByUsernamePassword(username);
//判断用户名是否存在
if(user==null){
throw new UsernameNotFoundException("用户不存在!");
}
ArrayList<GrantedAuthority> authorities = new ArrayList<>();
//用户存在的话查询角色
List<Role> roles = roleMapper.selectRolesByUserId(user.getId());
System.out.println("============角色================");
for (Role role : roles) {
System.out.println(role.getRoleDesc());
SimpleGrantedAuthority authority=new
SimpleGrantedAuthority(role.getRoleDesc());
authorities.add(authority);
}
//查询权限
List<Permission> permissions =
permissionMapper.selectPermissionsByUserId(user.getId());
System.out.println("============权限================");
for (Permission permission : permissions) {
System.out.println(permission.getUrl());
SimpleGrantedAuthority authority=
new SimpleGrantedAuthority(permission.getUrl());
authorities.add(authority);
}
return new User(username,user.getPassword(), authorities);
}
}
4.7 相关配置文件
db.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/securitydemo
jdbc.username=root
jdbc.password=1704
applicationContext.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<context:component-scan base-package="com.jz">
<context:exclude-filter type="annotation"
expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<!--配置数据源-->
<context:property-placeholder location="classpath:db.properties"/>
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driver}"></property>
<property name="jdbcUrl" value="${jdbc.url}"></property>
<property name="user" value="${jdbc.username}"></property>
<property name="password" value="${jdbc.password}"></property>
</bean>
<!--配置事务控制器-->
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!--开启注解事务管理-->
<tx:annotation-driven transaction-manager="transactionManager"/>
<!--mybatis相关配置-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!--配置数据源-->
<property name="dataSource" ref="dataSource"></property>
<!--加载sql映射文件-->
<property name="mapperLocations" value="classpath:mappers/*.xml"></property>
<!--设置别名-->
<property name="typeAliasesPackage" value="com.jz"></property>
</bean>
<bean id="scannerConfigurer"
class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.jz.mapper"></property>
</bean>
<!-- 配置加密类 -->
<bean id="passwordEncoder"
class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder"/>
</beans>
springmvc.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<context:component-scan base-package="com.jz" use-default-filters="false">
<context:include-filter type="annotation"
expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<mvc:annotation-driven></mvc:annotation-driven>
<mvc:default-servlet-handler></mvc:default-servlet-handler>
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
<!--
支持AOP的注解支持,AOP底层使用代理技术
JDK动态代理,要求必须有接口
cglib代理,生成子类对象,proxy-target-class="true" 默认使用cglib的方式
-->
<aop:aspectj-autoproxy proxy-target-class="true"/>
</beans>
spring-security.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:security="http://www.springframework.org/schema/security"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security.xsd">
<!-- 配置不过滤的资源(静态资源及登录相关) -->
<security:http pattern="/login.jsp" security="none"/>
<security:http pattern="/fail.jsp" security="none"/>
<security:http pattern="/css/**" security="none"/>
<security:http pattern="/img/**" security="none"/>
<security:http pattern="/plugins/**" security="none"/>
<!--
http:用于定义相关权限控制
auto-config:是否自动配置
设置为true时框架会提供默认的一些配置,例如提供默认的登录页面、登出处理等
设置为false时需要显示提供登录表单配置,否则会报错
use-expressions="false":禁用spEL表达式-->
<security:http auto-config="true" use-expressions="false">
<!-- 配置资源连接,访问任何资源,都需要拥有ROLE_USER -->
<security:intercept-url pattern="/**" access="ROLE_USER"/>
<!--登录:
1. login-page 自定义登录页url,默认为/login
2. login-processing-url form表单提交时指定的action
3. default-target-url 默认登录成功后跳转的url
4. authentication-failure-url 登录失败后跳转的url
5. username-parameter 用户名的请求字段 默认为userName
6. password-parameter 密码的请求字段 默认为password-->
<security:form-login login-page="/login.jsp"
login-processing-url="/login"
username-parameter="username"
password-parameter="password"
authentication-failure-url="/fail.jsp"
default-target-url="/index.jsp"
/>
<!-- 登出:
invalidate-session 是否删除session
logout-url:登出处理链接
logout-success-url:登出成功页面
注:登出操作 只需要链接到 logout即可登出当前用户 -->
<security:logout invalidate-session="true" logout-url="/logout"
logout-success-url="/login.jsp"/>
<!-- 关闭CSRF,默认是开启的 跨域攻击-->
<security:csrf disabled="true"/>
<!-- 尝试访问没有权限的页面时跳转的页面 -->
<security:access-denied-handler error-page="/error-noauth.jsp"/>
</security:http>
<!--认证管理器-->
<security:authentication-manager>
<security:authentication-provider user-service-ref="myUserDetailsService">
<!-- 配置加密的方式 -->
<security:password-encoder ref="passwordEncoder"/>
</security:authentication-provider>
</security:authentication-manager>
<!--开启jsr250注解-->
<security:global-method-security jsr250-annotations="enabled"
pre-post-annotations="enabled"
secured-annotations="enabled"/>
</beans>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<display-name>Archetype Created Web Application</display-name>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml,classpath:spring-security.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!--
DelegatingFilterProxy是Spring的Web模块中的一个类,
它提供了让HTTP请求在到达实际目的地之前通过过滤器的功能。
-->
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<servlet>
<servlet-name>dispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
4.8 创建页面
index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<span style="color: blue;font-size: 20px">
【当前登录用户[${sessionScope.SPRING_SECURITY_CONTEXT.authentication.principal.username}]】
</span>
<h1>主页--->登录成功</h1>
<a href="/logout">退出</a><br/><hr>
<a href="/book/list">书籍列表</a><br/><hr>
<a href="/book/add">新增书籍</a><br/><hr>
<a href="/book/update">书籍修改</a><br/><hr>
<a href="/book/delete">删除书籍</a><br/><hr>
</body>
</html>
login.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
<link rel="icon" href="图标路径;base64,aWNv"/>
</head>
<body>
<h1>login.jsp</h1>
<form action="/login" method="post">
用户名:<input type="text" name="username" value=""><br>
密码:<input type="password" name="password" value=""><br>
<input type="submit" value="登录">
</form>
</body>
</html>
fail.jsp(登录失败页面)
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h1 style="background: hotpink">登录失败</h1>
</body>
</html>
error-noauth.jsp(没有权限页面)
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h1 style="color: red">您无权访问</h1>
</body>
</html>
main.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h1>书籍管理页面</h1>
<h2>${msg}</h2>
</body>
</html>
4.9 创建controller
package com.jz.controller;
import org.springframework.security.access.annotation.Secured;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("book")
public class BookController {
@GetMapping("/list")
@PreAuthorize("hasAnyAuthority('book:list')")
public String bookList(Model model) {
System.out.println("访问书籍查询界面成功!");
model.addAttribute("msg","访问书籍查询界面成功!");
return "main";
}
@GetMapping("/add")
@PreAuthorize("hasAnyAuthority('book:add','book:insert')")
public String bookAdd(Model model) {
System.out.println("访问书籍新增界面成功!");
model.addAttribute("msg","访问书籍新增界面成功!");
return "main";
}
@GetMapping("/update")
//必须有book:edit权限才能访问bookUpdate方法
@PreAuthorize("hasAnyAuthority('book:edit')")
public String bookUpdate(Model model) {
System.out.println("访问书籍修改界面成功!");
model.addAttribute("msg","访问书籍修改界面成功!");
return "main";
}
@GetMapping("/delete")
//只要具有"ROLE_USER","ROLE_ADMIN"任意一种角色就可以访问。
@Secured({"ROLE_USER", "ROLE_ADMIN"})
public String bookDelete(Model model) {
System.out.println("访问书籍删除界面成功!");
model.addAttribute("msg","访问书籍删除界面成功!");
return "main";
}
}
5.1 项目结构
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-GawiOlgH-1687834244156)(image/1686498532587.png)]
5.2 ssm整合springsecurity流程
1. 加入依赖包
2. 创建包结构(pojo、mapper、service、controller)
3. spring整合springmvc(springmvc.xml、applicationContext.xml)
4. 在web.xml文件中配置spring监听器、前端控制器、解决中文乱码的过滤器、DelegatingFilterProxy
5. spring整合mybatis(db.properties指定数据源,applicationContext.xml文件中配置整合mybatis)
6. 创建securitydemo数据库和表
7. 创建表对应的实体类
8. 创建实体类对应的mapper接口和xml文件
9. 在mapper接口和xml文件中写用户查询、角色查询、权限查询
10. 自定义认证管理器类:MyUserDetailsService(查询用户、角色、权限)进行认证
11. 创建spring-security.xml文件配置认证和授权
12. 创建BookController和一些jsp页面进行测试
5. 获取当前登陆了用户的方式
https://www.freesion.com/article/79481159731/
6. springsecurity认证流程
https://blog.csdn.net/msq16021/article/details/126143791