百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 技术文章 > 正文

SpringBoot的Security安全控制—企业项目中的SpringSecurity操作

haoteby 2025-06-23 19:10 11 浏览

企业项目中的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语句,这样会明显地提高开发效率,使用起来也非常方便。

相关推荐

谷歌开源大模型评测框架正式发布,AI模型评测难题迎刃而解

近日科技巨头谷歌正式推出其开源大模型评测框架LMEval,这一创新工具为全球AI开发者和企业提供了标准化的模型评估解决方案。LMEval的发布不仅标志着AI模型评测迈入透明化时代,更通过多项核心技术...

Android 开发中文引导-动画和图形概述

安卓系统提供了各种强大的API,用来将动画应用于界面元素和自定义2D和3D图形的绘制当中。下面的小节大概的描述了可用的API和系统功能并帮助你决定那个方案最适合你的需要。动画安卓框架提供了两种动画系统...

Qt5 C++入门教程-第12章 绘图(QPainter)

QPainter类在Qt5中进行绘图时起着重要作用。绘图操作是通过QPainter类在响应paintEvent方法时完成的。线条在第一个示例中,我们在窗口的客户区绘制了一些线条。line...

文创测评︱《如意琳琅图籍》:本土原创解谜书的胜利?

设想这样一个场景,你打开一本书,就化身为乾隆三十六年紫禁城中的画画人周本,有一天你在故纸堆中找到一本神秘的《如意琳琅图籍》,踏上寻宝旅程,历经各种离奇复杂的故事……这是故宫与奥秘之家联手打造的创意解谜...

gif动图制作攻略!快快收藏(求gif制作的动图)

有事没事斗图玩是当下人们乐此不疲的事情,手里的gif动图也渐渐成为了人们抬杠互怼的一大资本。好有趣,好炫酷,gif是怎么做出来的?我也想做。什么?你不会?没关系,我来教你!首先介绍一下制作gif动图需...

eduis未能初始化界面 无法启动 问题解决办法

1.如果edius安装后启动后出现failedtoinitializeskin中文提示无法初始化界面的错误。这说明你的电脑安装了双显卡,而edius所使用的是图形显卡。可以选择edius图标右键...

写真一周:水岛美结水着解禁、长滨祢瑠婚纱写真等

...

Flash Player模拟器更新:Rufffle(flash模拟器安卓下载高版本)

Ruffle是一个适用于WindowsPC的FlashPlayer模拟器,用Rust编写。Ruffle作为一个独立的应用程序在所有现代操作系统上原生运行,并通过使用WebAssembly在所有现代...

支持终身免费4G流量,星星充电7kW星际智能交流充电桩拆解

前言近期星星充电推出了一款星际智能交流充电桩,在正面设有灯条,可根据灯条颜色和显示直观了解充电状态,并设有屏幕显示充电状态和ui表情。充电桩支持220V/7kW充电功率,适配主流新能源车型。并支持终身...

乐动随心之fancy pop(乐动随心壶多少钱一个)

跳动飞扬的音符像是连通人与人之间心电感应的通关密码,融化陌生,拉近彼此。此次我们邀请到宅男女神江语晨,化身音乐精灵。在歌手、演员身份间游刃自如的她,为我们生动诠释了三种不同的音乐时尚风格,娴静可爱,灵...

Asus Zenflash 手机也能玩引闪,从此相机是路人

在讲解Zenflash之前,不得不提索爱的K750c,这个机器采用了氙气闪光灯,让手机的拍摄上了档次,可玩性更高,不过,说实话,当时手机的摄像头像素低,成像一般,没有掀起太大的波澜,可现在,手机的Cm...

Axure有哪些鲜为人知的使用技巧?(axure的使用教程)

阿拓带你飞:不管是想入门产品经理还是已经是PM的人对AXURE都很关注,它是制作产品原型的重要工具,但是有多少人了解AXURE的使用技巧?本文是来自“知乎问答”整理的回答,一起来看看那些不常用的使用技...

挑战黑夜 华硕ZenFlash氙气闪光灯评测

【机锋配件】说到摄影,相信许多朋友都非常喜欢,不管是外出游玩拍拍风景,还是和朋友之间聚会,都会掏出手机拍两张,在餐前拍照晒朋友圈更是成为了许多用户的日常爱好,就算不是专业的摄影爱好者,大家也都有一颗热...

WPS 演示倒计时 3 步设置!从数字动画到进度条全场景教程

做PPT时想添加倒计时却找不到入口?WPS演示自带的"动画+计时"功能就能轻松实现——无论是课堂互动的30秒答题倒计时、商务汇报的5分钟限时讲解,还是活动暖场的动...

flash动画an制作MG动画元素如何调节透明度,小白...

如何在flash动画软件里面调节mg动画元素的透明?因为flash动画软件现在已经升级为flash动画软件,所以直接用新版flash动画软件开工,基本功能都差不多,只是flash增加很多智能化、人性...