SpringBoot的Security安全控制—企业项目中的SpringSecurity操作
liuian 2025-07-27 21:59 84 浏览
企业项目中的Spring Security操作
面的章节从内置数据入手开始介绍Spring Security的入门案例。在实际的企业级开发中,一般不会把用户名和密码固定在代码或者配置文件中,而是直接在数据库中查询用户的账号和密码,再将其和用户输入的账号和密码进行对比并认证,最终完成用户的认证和授权查询。下面使用国内目前常用的两个数据库操作框架(Spring Data JPA和MyBatis)完成对SpringSecurity的查询和认证,读者只需要掌握其中的一个框架即可,建议优先选用自己熟悉的框架。
实战:基于JPA的Spring Boot Security操作
新建一个spring-security-db-demo项目,具体步骤如下:
(1)在pom.xml中添加Spring Security和JPA,即MySQL和Web开发所需要的依赖,代码如下:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.10.RELEASE</version>
<relativePath/>
</parent>
<groupId>com.example</groupId>
<artifactId>spring-security-db-demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>spring-security-db-demo</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>11</java.version>
</properties>
<dependencies>
<dependency> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<!--spring data jpa-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!--spring security-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--thymeleaf模板-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<!--thymeleaf中使用的Spring Security标签-->
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity5</artifactId>
<!-- <version>3.0.3.RELEASE</version>-->
</dependency>
<dependency>
<groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.5.7</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
(2)为了让项目开发具有多样性,本次使用的配置文件格式是yml,在application.yml中添加项目配置,用来配置数据库的连接信息。使用sys数据库的配置信息如下:
server:
port: 8080
spring:
datasource:
username: root
password: 123456
url: jdbc:mysql://127.0.0.1:3306/sys
driver-class-name: com.mysql.cj.jdbc.Driver
jpa:
hibernate: ddl-auto: update
database-platform: org.hibernate.dialect.MySQL5InnoDBDialect
open-in-view: false
(3)开始编写项目代码,新建Security的配置文件WebSecurityConfig.java:
package com.example.springsecuritydbdemo.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.Authentication
Provider;
import
org.springframework.security.authentication.dao.DaoAuthentication
Provider;
import org.springframework.security.config.annotation.authentication.
builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.
configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.
HttpSecurity;
import
org.springframework.security.config.annotation.web.configuration.
WebSecurityConfigurerAdapter;
import
org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.factory.PasswordEncoder
Factories;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.rememberme.
JdbcTokenRepositoryImpl;
import org.springframework.security.web.authentication.rememberme.
PersistentTokenRepository;
import javax.sql.DataSource;/**
* 开启security注解
*/
@Configuration
@EnableGlobalMethodSecurity(securedEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UserDetailsService userDetailsService;
@Autowired
private PersistentTokenRepository persistentTokenRepository;
@Override
protected void configure(AuthenticationManagerBuilder auth) throws
Exception {
auth.authenticationProvider(authenticationProvider());
}
@Override
protected void configure(HttpSecurity http) throws Exception {
//关闭csrf
http.csrf().disable();
// 自定义登录页面
http.formLogin()
.loginPage("/loginPage") // 登录页面的
URL
// 登录访问路径,不用自己处理逻辑,只需要定义URL即可
.loginProcessingUrl("/login")
.failureUrl("/exception") // 登录失败时跳
转的路径
.defaultSuccessUrl("/index", true); // 登录成功后跳
转的路径
// URL的拦截与放行,除//loginPage、/hello、/exception和/*.jpg之外的
路径都会被拦截
http.authorizeRequests()
.antMatchers("/loginPage", "/hello", "/exception",
"/*.jpg").permitAll()
.anyRequest().authenticated();
// 注销用户
http.logout().logoutUrl("/logout");
// 记住密码(自动登录) http.rememberMe().tokenRepository(persistentTokenRepository).
tokenValiditySeconds(60 * 60).userDetailsService(userDetailsService);
}
/**
* 登录提示
*/
@Bean
public AuthenticationProvider authenticationProvider() {
DaoAuthenticationProvider provider = new
DaoAuthenticationProvider();
// 显示用户找不到异常,默认不论用户名和密码哪个错误,都提示密码错误
provider.setHideUserNotFoundExceptions(false);
provider.setPasswordEncoder(passwordEncoder());
provider.setUserDetailsService(userDetailsService);
return provider;
}
/**
* 密码加密器
*/
@Bean
public PasswordEncoder passwordEncoder() {
return
PasswordEncoderFactories.createDelegatingPasswordEncoder();
}
/**
* 记住密码,并存储Token
*/
@Bean
public PersistentTokenRepository
persistentTokenRepository(DataSourcedataSource) {
// 数据存储在数据库中
JdbcTokenRepositoryImpl jdbcTokenRepository = new
JdbcTokenRepositoryImpl();
jdbcTokenRepository.setDataSource(dataSource);
return jdbcTokenRepository;
}
}
(4)新建Web请求的UserControllerjava入口文件,并定义其访问的URL:
package com.example.springsecuritydbdemo.controller;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.annotation.Secured;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.util.WebUtils;
import javax.servlet.http.HttpServletRequest;
@Controller
@Slf4j
public class UserController {
@ResponseBody
@RequestMapping("/hello")
public String hello() {
return "hello";
}
/**
* 登录页面
*/
@GetMapping("/loginPage")
public String login() {
return "login";
}
/**
* Security 认证异常处理
*/
@GetMapping("/exception")
public String error(HttpServletRequest request) {
// 获取Spring Security的AuthenticationException异常并抛出,由全局异
常统一处理
AuthenticationException exception = (AuthenticationException)
WebUtils.getSessionAttribute(request,
"SPRING_SECURITY_LAST_EXCEPTION");
if (exception != null) {
throw exception;
}
return "redirect:/loginPage";
}
@GetMapping({"/index", "/"})
public String index() {
return "index";
}
@ResponseBody
@GetMapping("/role/teacher")
@Secured({"ROLE_teacher", "ROLE_admin"})
public String teacher() {
return "模拟获取老师数据";
}
@ResponseBody
@GetMapping("/role/admin")
@Secured({"ROLE_admin"})
public String admin() {
return "模拟获取管理员数据";
}
@ResponseBody
@GetMapping("/role/student")
@Secured({"ROLE_student", "ROLE_admin"})
public String student() {
return "模拟获取学生数据";
}
}
(5)新建UserDao.java文件和AuthoritiesDao.java文件进行数据库的操作。
UserDao.java文件的内容如下:
package com.example.springsecuritydbdemo.dao;
import com.example.springsecuritydbdemo.entity.Authorities;
import org.springframework.data.jpa.repository.JpaRepository;
import
org.springframework.data.jpa.repository.JpaSpecificationExecutor;
public interface AuthoritiesDao extends
JpaRepository<Authorities, Integer>, JpaSpecificationExecutor
<Authorities> {
}
AuthoritiesDao.java文件的内容如下:
package com.example.springsecuritydbdemo.dao;
import com.example.springsecuritydbdemo.entity.Users;
import org.springframework.data.jpa.repository.JpaRepository;
import
org.springframework.data.jpa.repository.JpaSpecificationExecutor;
public interface UsersDao extends
JpaRepository<Users, Integer>, JpaSpecificationExecutor<Users>
{
Users findByUsername(String username);
}
(6)新建数据库的表对应的实体类Authorities、PersistentLogins和Users。Authorities类如下:
package com.example.springsecuritydbdemo.entity;
import lombok.Getter;
import lombok.Setter;
import javax.persistence.*;
import java.util.HashSet;
import java.util.Set;
@Getter
@Setter
@Entity
@Table(name = "authorities")
public class Authorities {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String authority;
@ManyToMany(mappedBy = "authorities", cascade = CascadeType.ALL)
private Set<Users> users = new HashSet<>();
}
PersistentLogins类的内容如下:
package com.example.springsecuritydbdemo.entity;
import lombok.Getter;
import lombok.Setter;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import java.util.Date;@Getter
@Setter
@Entity
@Table(name = "persistent_logins")
public class PersistentLogins {
@Id
private String series;
private String username;
private String token;
private Date last_used;
}
Users类的内容如下:
package com.example.springsecuritydbdemo.entity;
import lombok.Getter;
import lombok.Setter;
import javax.persistence.*;
import java.util.HashSet;
import java.util.Set;
@Getter
@Setter
@Entity
@Table(name = "users")
public class Users {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String username;
private String password;
@ManyToMany(targetEntity = Authorities.class, cascade =
CascadeType.ALL)
@JoinTable(name = "users_authorities", joinColumns = @JoinColumn(name = "users_id",
referencedColumnName = "id"),
inverseJoinColumns = @JoinColumn(name =
"authorities_id",referencedColumnName = "id"))
private Set<Authorities> authorities = new HashSet<>();
}
(7)设置项目的全局异常处理:
package com.example.springsecuritydbdemo.exception;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.authentication.BadCredentials
Exception;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;
/**
* 全局异常处理
*/
@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
@ExceptionHandler(RuntimeException.class)
public ModelAndView exception(Exception e) {
log.info(e.toString());
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("error");
if (e instanceof BadCredentialsException) {
// 密码错误
modelAndView.addObject("msg", "密码错误");
} else if (e instanceof AccessDeniedException) {
// 权限不足
modelAndView.addObject("msg", e.getMessage());
} else { // 其他
modelAndView.addObject("msg", "系统错误");
}
return modelAndView;
}
}
(8)设置用户的服务类,代码如下:
package com.example.springsecuritydbdemo.service;
import com.example.springsecuritydbdemo.dao.UsersDao;
import com.example.springsecuritydbdemo.entity.Authorities;
import com.example.springsecuritydbdemo.entity.Users;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGranted
Authority;
import org.springframework.security.core.userdetails.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.Set;
@Service("userDetailsService")
@Slf4j
public class UserDetailService implements UserDetailsService {
@Autowired
private UsersDao usersDao;
@Override
@Transactional
public UserDetails loadUserByUsername(String s) throws
UsernameNotFound
Exception {
Users users = usersDao.findByUsername(s); // 用户不存在
if (users == null) {
log.error("用户名:[{}]不存在", s);
throw new UsernameNotFoundException("用户名不存在");
}
// 获取该用户的角色信息
Set<Authorities> authoritiesSet = users.getAuthorities();
ArrayList<GrantedAuthority> list = new ArrayList<>();
for (Authorities authorities : authoritiesSet) {
list.add(new
SimpleGrantedAuthority(authorities.getAuthority()));
}
return new User(users.getUsername(), users.getPassword(),
list);
}
}
(9)新建Spring Boot项目的启动类:
package com.example.springsecuritydbdemo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import
org.springframework.security.config.annotation.web.configuration.
EnableWebSecurity;
@EnableWebSecurity
@SpringBootApplication
public class SpringSecurityDbDemoApplication {
public static void main(String[] args) {
SpringApplication.run(SpringSecurityDbDemoApplication.class,
args);
}
}
提示:在启动项目之前需要配置好数据库。本书使用MySQL 8。数据库的配置信息保存在application.yml文件中,读者可以根据实际情况修改数据库信息,确认无误后即可启动项目。
访问
http://localhost:8080/loginPage即可可以看到登录页面,如图5.10所示。使用账号admin和密码123456登录后,可以看到admin拥有的权限,如图5.11所示。退出admin后使用账号student和密码123456登录,查看student拥有的权限,如图5.12所示。可以看到,不同的用户拥有不同的权限,从而实现使用JPA控制不同用户权限的目的。
可以看到,不同的账号访问,拥有不同的权限,权限不同看到的数据也不同。
实战:基于MyBatis的Spring Boot Security操作
基于5.3.1小节的代码,全部注释掉UserDao.java文件和AuthoritiesDao.java文件,修改后缀名为UserDao.java.bak和AuthoritiesDao.java.bak,再修改entity包中的实体类。
主要步骤如下:
(1)移除pom.xml中的JPA依赖,在pom.xml中添加MyBatis的依赖:
<!--spring data jpa-->
<!--<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.1</version>
</dependency>
(2)修改
SpringSecurityDbDemoApplication.java文件,增加一个MyBatis的配置注解:
@MapperScan("com.example.springsecuritydbdemo.dao")
(3)修改entity包中所有的实体类,去除所有的JPA注解。
Authorities类的文件内容如下:
package com.example.springsecuritydbdemo.entity;
import lombok.Data;
@Data
public class Authorities {
private Integer id;
private String authority;
}
PersistentLogins类的文件内容如下:
package com.example.springsecuritydbdemo.entity;
import lombok.Data;
import java.util.Date;
@Data
public class PersistentLogins {
private String series;
private String username;
private String token;
private Date last_used;
}
Users类的文件内容如下:
package com.example.springsecuritydbdemo.entity;
import lombok.Data;
import java.util.HashSet;
import java.util.Set;
@Data
public class Users {
private Integer id;
private String username;
private String password;
private Set<Authorities> authorities = new HashSet<>();
}
(4)修改Dao包中的数据库操作接口,添加查询用户的方法:
package com.example.springsecuritydbdemo.dao;
import com.example.springsecuritydbdemo.entity.Authorities;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.ResultType;
import org.apache.ibatis.annotations.Select;
import java.util.Set;
@Mapper
public interface AuthoritiesDao {
@Select("select a.* from authorities a LEFT JOIN users_authorities
b " +
"on a.id=b.authorities_id where b.users_id=#{userId}")
@ResultType(Set.class)
Set<Authorities> findByUserId(@Param("userId") Integer userId);
}
(5)添加查询用户和保存用户的方法:
package com.example.springsecuritydbdemo.dao;
import com.example.springsecuritydbdemo.entity.Users;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
@Mapper
public interface UsersDao {
@Select("select * from users where username=#{username}")
Users findByUsername(@Param("username") String username);
void save(Users users);
}
(6)在sys数据库中执行SQL语句,用来创建3张表,代码如下:
CREATE TABLE `authorities` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`authority` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `persistent_logins` (
`series` varchar(100) NOT NULL,
`username` varchar(255) DEFAULT NULL,
`token` varchar(255) DEFAULT NULL,
`last_used` datetime DEFAULT NULL,
PRIMARY KEY (`series`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `users` (
`id` int(11) NOT NULL AUTO_INCREMENT, `username` varchar(255) DEFAULT NULL,
`password` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
修改完成后启动项目,再次访问http://localhost:8080,如同5.3.1小节的例子一样登录不同的账号,确认不同的用户拥有不同的权限。通过以上开发实践可以看到,在一些简单的数据库操作中,JPA不需要编写SQL语句,这样会明显地提高开发效率,使用起来也非常方便。
相关推荐
- 搭建一个20人的办公网络(适用于20多人的小型办公网络环境)
-
楼主有5台机上网,则需要一个8口路由器,组网方法如下:设备:1、8口路由器一台,其中8口为LAN(局域网)端口,一个WAN(广域网)端口,价格100--400元2、网线N米,这个你自己会看了:)...
- 笔记本电脑各种参数介绍(笔记本电脑各项参数新手普及知识)
-
1、CPU:这个主要取决于频率和二级缓存,频率越高、二级缓存越大,速度越快,现在的CPU有三级缓存、四级缓存等,都影响相应速度。2、内存:内存的存取速度取决于接口、颗粒数量多少与储存大小,一般来说,内...
- 汉字上面带拼音输入法下载(字上面带拼音的输入法是哪个)
-
使用手机上的拼音输入法打成汉字的方法如下:1.打开手机上的拼音输入法,在输入框中输入汉字的拼音,例如“nihao”。2.根据输入法提示的候选词,选择正确的汉字。例如,如果输入“nihao”,输...
- xpsp3安装版系统下载(windowsxpsp3安装教程)
-
xpsp3纯净版在采用微软封装部署技术的基础上,结合作者的实际工作经验,融合了许多实用的功能。它通过一键分区、一键装系统、自动装驱动、一键设定分辨率,一键填IP,一键Ghost备份(恢复)等一系列...
- 没有备份的手机数据怎么恢复
-
手机没有备份恢复数据方法如下1、使用数据线将手机与电脑连接好,在“我的电脑”中可以看到手机的盘符。 2、将手机开启USB调试模式。在手机设置中找到开发者选项,然后点击“开启USB调试模式”。 3、...
- 电脑怎么激活windows11专业版
-
win11专业版激活方法有多种,以下提供两种常用的激活方式:方法一:使用激活密钥激活。在win11桌面上右键点击“此电脑”,选择“属性”选项。进入属性页面后,点击“更改产品密钥或升级windows”。...
- 华为手机助手下载官网(华为手机助手app下载专区)
-
华为手机助手策略调整,已不支持从应用市场下载手机助手,目前华为手机助手是需要在电脑上下载或更新手机助手到最新版本,https://consumer.huawei.com/cn/support/his...
- 光纤线断了怎么接(宽带光纤线断了怎么接)
-
宽带光纤线断了可以重接,具体操作方法如下:1、光纤连接的时候要根据束管内,同色相连,同芯相连,按顺序进行连接,由大到小。一般有三种连接方法,分别是熔接、活动连接和机械连接。2、连接的时候要开剥光缆,抛...
- win7旗舰版和专业版区别(win7旗舰版跟专业版)
-
1、功能区别:Win7旗舰版比专业版多了三个功能,分别是Bitlocker、BitlockerToGo和多语言界面; 2、用途区别:旗舰版的功能是所有版本中最全最强大的,占用的系统资源,...
- 万能连接钥匙(万能wifi连接钥匙下载)
-
1、首先打开wifi万能钥匙软件,若手机没有开启WLAN,就根据软件提示打开WLAN开关;2、打开WLAN开关后,会显示附近的WiFi,如果知道密码,可点击相应WiFi后点击‘输入密码’连接;3、若不...
- 雨林木风音乐叫什么(雨林木风是啥)
-
雨林木风的创始人是陈年鑫先生。陈年鑫先生于1999年创立了雨林木风公司,其初衷是为满足中国市场对高品质、高性能电脑的需求。在陈年鑫先生的领导下,雨林木风以技术创新、产品质量和客户服务为核心价值,不断推...
- aics6序列号永久序列号(aics6破解序列号)
-
关于AICS6这个版本,虽然是比较久远的版本,但是在功能上也是十分全面和强大的,作为一名平面设计师的话,AICS6的现有的功能已经能够应付几乎所有的设计工作了……到底AICC2019的功能是不是...
- 手机可以装电脑系统吗(手机可以装电脑系统吗怎么装)
-
答题公式1:手机可以通过数据线或无线连接的方式给电脑装系统。手机安装系统需要一定的技巧和软件支持,一般需要通过数据线或无线连接的方式与电脑连接,并下载相应的软件和系统文件进行安装。对于大部分手机用户来...
- 一周热门
- 最近发表
- 标签列表
-
- python判断字典是否为空 (50)
- crontab每周一执行 (48)
- aes和des区别 (43)
- bash脚本和shell脚本的区别 (35)
- canvas库 (33)
- dataframe筛选满足条件的行 (35)
- gitlab日志 (33)
- lua xpcall (36)
- blob转json (33)
- python判断是否在列表中 (34)
- python html转pdf (36)
- 安装指定版本npm (37)
- idea搜索jar包内容 (33)
- css鼠标悬停出现隐藏的文字 (34)
- linux nacos启动命令 (33)
- gitlab 日志 (36)
- adb pull (37)
- python判断元素在不在列表里 (34)
- python 字典删除元素 (34)
- vscode切换git分支 (35)
- python bytes转16进制 (35)
- grep前后几行 (34)
- hashmap转list (35)
- c++ 字符串查找 (35)
- mysql刷新权限 (34)
