当前位置: 首页 > news >正文

Spring Boot 实现不同用户不同访问权限

前提

近期在使用 Spring Boot,用户角色被分为管理者和普通用户;角色不同,权限也就存在不同。

在 Spring Boot 里实现不同用户拥有不同访问权限,可借助 Spring Security 框架达成。

实现

1. 添加必要依赖

首先要在 pom.xml 里添加 Spring Security 和 JPA 的依赖。

<dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-security</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-jpa</artifactId></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><scope>runtime</scope></dependency>
</dependencies>

2. 数据库表设计

创建三张表,分别是用户表、角色表以及用户角色关联表:

CREATE TABLE users (id INT PRIMARY KEY AUTO_INCREMENT,username VARCHAR(50) NOT NULL UNIQUE,password VARCHAR(100) NOT NULL,enabled BOOLEAN DEFAULT true
);CREATE TABLE roles (id INT PRIMARY KEY AUTO_INCREMENT,name VARCHAR(50) NOT NULL UNIQUE
);CREATE TABLE user_roles (user_id INT NOT NULL,role_id INT NOT NULL,PRIMARY KEY (user_id, role_id),FOREIGN KEY (user_id) REFERENCES users(id),FOREIGN KEY (role_id) REFERENCES roles(id)
);

3. 实体类设计

创建与数据库表对应的实体类:

// User.java
import javax.persistence.*;
import java.util.Set;@Entity
@Table(name = "users")
public class User {@Id@GeneratedValue(strategy = GenerationType.IDENTITY)private Long id;private String username;private String password;private boolean enabled;@ManyToMany(fetch = FetchType.EAGER)@JoinTable(name = "user_roles",joinColumns = @JoinColumn(name = "user_id"),inverseJoinColumns = @JoinColumn(name = "role_id"))private Set<Role> roles;// getters and setters
}// Role.java
import javax.persistence.*;@Entity
@Table(name = "roles")
public class Role {@Id@GeneratedValue(strategy = GenerationType.IDENTITY)private Long id;private String name;// getters and setters
}

4. 创建 Repository 接口

为 User 和 Role 分别创建 Repository 接口,用于数据访问:

// UserRepository.java
import org.springframework.data.jpa.repository.JpaRepository;public interface UserRepository extends JpaRepository<User, Long> {User findByUsername(String username);
}// RoleRepository.java
import org.springframework.data.jpa.repository.JpaRepository;public interface RoleRepository extends JpaRepository<Role, Long> {Role findByName(String name);
}

5. 实现 UserDetailsService

实现 Spring Security 的 UserDetailsService 接口,从数据库加载用户信息:

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;import java.util.ArrayList;
import java.util.List;
import java.util.Set;@Service
public class CustomUserDetailsService implements UserDetailsService {private final UserRepository userRepository;public CustomUserDetailsService(UserRepository userRepository) {this.userRepository = userRepository;}@Overridepublic UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {User user = userRepository.findByUsername(username);if (user == null) {throw new UsernameNotFoundException("User not found with username: " + username);}return new org.springframework.security.core.userdetails.User(user.getUsername(),user.getPassword(),user.isEnabled(),true,true,true,getAuthorities(user.getRoles()));}private List<GrantedAuthority> getAuthorities(Set<Role> roles) {List<GrantedAuthority> authorities = new ArrayList<>();for (Role role : roles) {authorities.add(new SimpleGrantedAuthority("ROLE_" + role.getName()));}return authorities;}
}

6. 配置 Spring Security

对 Spring Security 进行配置,设置不同 URL 的访问权限:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;@Configuration
@EnableWebSecurity
public class SecurityConfig {@Beanpublic PasswordEncoder passwordEncoder() {return new BCryptPasswordEncoder();}@Beanpublic SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {http.authorizeRequests().antMatchers("/public/**").permitAll().antMatchers("/admin/**").hasRole("ADMIN").antMatchers("/user/**").hasAnyRole("USER", "ADMIN").anyRequest().authenticated().and().formLogin().loginPage("/login").permitAll().and().logout().permitAll();return http.build();}
}

7. 创建控制器

创建不同权限的控制器示例:

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;@RestController
public class HelloController {@GetMapping("/public/hello")public String publicHello() {return "Public Hello!";}@GetMapping("/user/hello")public String userHello() {return "User Hello!";}@GetMapping("/admin/hello")public String adminHello() {return "Admin Hello!";}
}

8. 测试用户数据

创建测试用户数据,以便进行测试:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;import java.util.Collections;
import java.util.HashSet;@Component
public class DataInitializer implements CommandLineRunner {@Autowiredprivate UserRepository userRepository;@Autowiredprivate RoleRepository roleRepository;@Autowiredprivate PasswordEncoder passwordEncoder;@Overridepublic void run(String... args) throws Exception {// 创建角色Role adminRole = roleRepository.findByName("ADMIN");if (adminRole == null) {adminRole = new Role();adminRole.setName("ADMIN");roleRepository.save(adminRole);}Role userRole = roleRepository.findByName("USER");if (userRole == null) {userRole = new Role();userRole.setName("USER");roleRepository.save(userRole);}// 创建管理员用户User adminUser = userRepository.findByUsername("admin");if (adminUser == null) {adminUser = new User();adminUser.setUsername("admin");adminUser.setPassword(passwordEncoder.encode("admin123"));adminUser.setEnabled(true);adminUser.setRoles(new HashSet<>(Collections.singletonList(adminRole)));userRepository.save(adminUser);}// 创建普通用户User normalUser = userRepository.findByUsername("user");if (normalUser == null) {normalUser = new User();normalUser.setUsername("user");normalUser.setPassword(passwordEncoder.encode("user123"));normalUser.setEnabled(true);normalUser.setRoles(new HashSet<>(Collections.singletonList(userRole)));userRepository.save(normalUser);}}
}

权限控制说明

  • @PreAuthorize 注解:能在方法级别进行权限控制。例如:
    @PreAuthorize("hasRole('ADMIN')")
    @GetMapping("/admin/hello")
    public String adminHello() {return "Admin Hello!";
    }
    
  • 角色继承:可以让 ADMIN 角色继承 USER 角色的权限,配置如下:
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {http.authorizeRequests().antMatchers("/public/**").permitAll().antMatchers("/user/**").hasRole("USER").antMatchers("/admin/**").hasRole("ADMIN").anyRequest().authenticated().and().roleHierarchy(roleHierarchy());return http.build();
    }@Bean
    public RoleHierarchy roleHierarchy() {RoleHierarchyImpl roleHierarchy = new RoleHierarchyImpl();roleHierarchy.setHierarchy("ROLE_ADMIN > ROLE_USER");return roleHierarchy;
    }
    
http://www.dtcms.com/a/263001.html

相关文章:

  • 基于uniapp的老年皮肤健康管理微信小程序平台(源码+论文+部署+安装+售后)
  • 跨时间潜运动迁移以实现操作中的多帧预测
  • Instrct-GPT 强化学习奖励模型 Reward modeling 的训练过程原理实例化详解
  • nifi1.28.1集群部署详细记录
  • 大语言模型LLM在训练/推理时的padding
  • 用户行为序列建模(篇十一)-小结篇(篇一)
  • 如何读取运行jar中引用jar中的文件
  • C++ --- list
  • 《Effective Python》第十一章 性能——使用 timeit 微基准测试优化性能关键代码
  • 分发糖果
  • Spring Boot 集成 tess4j 实现图片识别文本
  • Springboot + vue + uni-app小程序web端全套家具商场
  • Serverless 架构入门与实战:AWS Lambda、Azure Functions、Cloudflare Workers 对比
  • 人工智能参与高考作文写作的实证研究
  • 华为物联网认证:开启万物互联的钥匙
  • 设计模式-观察者模式(发布订阅模式)
  • YOLOv12_ultralytics-8.3.145_2025_5_27部分代码阅读笔记-torch_utils.py
  • 现代JavaScript前端开发概念
  • spring-ai-alibaba官方 Playground 示例
  • 使用pyflink进行kafka实时数据消费
  • 电脑开机加速工具,优化启动项管理
  • 【Unity】MiniGame编辑器小游戏(七)贪吃蛇【Snake】
  • Java项目:基于SSM框架实现的云端学习管理系统【ssm+B/S架构+源码+数据库+毕业论文】
  • 离线环境安装elk及设置密码认证
  • 通过案例来了解let、const、var的区别
  • DAY 47 注意力热图可视化
  • 有些Android旧平台,在Settings菜单里的,设置-电池菜单下,没有电池使用数据,如何处理
  • RK3568平台开发系列讲解:HDMI显示驱动
  • 六自由度按摩机器人 MATLAB 仿真
  • HarmonyOS NEXT仓颉开发语言实战案例:电影App