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

做环评需要关注哪些网站陕西住房城乡建设厅网站

做环评需要关注哪些网站,陕西住房城乡建设厅网站,深圳网址排名,正规漫画网站开发流程前提 近期在使用 Spring Boot,用户角色被分为管理者和普通用户;角色不同,权限也就存在不同。 在 Spring Boot 里实现不同用户拥有不同访问权限,可借助 Spring Security 框架达成。 实现 1. 添加必要依赖 首先要在 pom.xml 里…

前提

近期在使用 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/580091.html

相关文章:

  • 简单网站制作教程怎么做网站数据分析
  • 石家庄哪里有做网站的南昌企业自助建站
  • 美食攻略网站建设课程设计注册免费的网站有吗
  • 安阳网站怎么优化威海网站定制
  • 建站行业有哪些桂林生活网招聘
  • 泉州网站排名优化教育行业手机wap网站
  • 彩票网站的建设网络推广外包公司干什么的
  • 企业网站 建设 流程温岭做鞋子的网站
  • 创意设计公司架构陕西seo排名
  • 机械设备网站源码学会网站制作要多久
  • 一流的企业网站建设wordpress 不能查看站点
  • 在建设局网站上怎么样总监解锁网页设计6种布局方式
  • 做网站多少钱 网络服务创业谷网站建设规划
  • 吉水县建设局网站网站规划应遵循的原则有哪些
  • 公司网站建设一般要多少钱asp源码下载
  • 江门微信网站建设东莞企业网站建设开发
  • 如何建立网站赚钱互联网创业项目
  • 重庆奉节网站建设公司哪家专业网站教程制作
  • 整站优化包年wordpress前台构架图
  • 公司网站开发费分录是h5网页制作方法
  • 黄埭网站建设网站图片放大特效怎么做
  • 百度站内搜索 wordpress中国十大erp公司
  • 合肥高端网站建设广州网站建设推广公司
  • 网站改版会影响排名吗蚌埠网站建设蚌埠
  • 网站正在建设中请稍后网页设计实验报告html
  • php就是做网站吗装修公司做自己网站
  • 如何在大网站做外链手机网站开发 教程
  • 免费商标查询官网网站优化建设兰州
  • 赣州网站seo传奇网页游戏制作
  • 深圳前50强网站建设公司常德网站定制