建立项目:


这是完成后的目录结构:

源代码:
SecurityConfig.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
| package com.laisc.securitydemo002.config;
import com.laisc.securitydemo002.security.MyUserDetailsService; import org.springframework.beans.factory.annotation.Autowired; 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.web.SecurityFilterChain;
@Configuration public class SecurityConfig {
@Autowired private MyUserDetailsService userDetailsService;
@Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { http .authorizeHttpRequests(auth -> auth .requestMatchers("/admin").hasRole("ADMIN") .requestMatchers("/hello").hasAnyRole("USER", "ADMIN") .anyRequest().authenticated() ) .formLogin() .and() .userDetailsService(userDetailsService);
return http.build(); } }
|
HelloController.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| package com.laisc.securitydemo002.controller;
import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody;
@Controller public class HelloController {
@ResponseBody @RequestMapping("/hello") public String hello() { return "Hello, Spring Security!"; }
@ResponseBody @RequestMapping("/admin") public String admin() { return "Admin Area!"; } }
|
Role.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
| package com.laisc.securitydemo002.entity;
import jakarta.persistence.*;
import java.util.HashSet; import java.util.Set;
@Entity @Table(name = "roles") public class Role { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id;
private String name;
@ManyToMany(mappedBy = "roles") private Set<User> users = new HashSet<>();
public Long getId() { return id; }
public void setId(Long id) { this.id = id; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public Set<User> getUsers() { return users; }
public void setUsers(Set<User> users) { this.users = users; } }
|
User.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
| package com.laisc.securitydemo002.entity;
import jakarta.persistence.*;
import java.util.HashSet; 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 = new HashSet<>();
public Long getId() { return id; }
public void setId(Long id) { this.id = id; }
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 boolean isEnabled() { return enabled; }
public void setEnabled(boolean enabled) { this.enabled = enabled; }
public Set<Role> getRoles() { return roles; }
public void setRoles(Set<Role> roles) { this.roles = roles; } }
|
UserRepository.java
1 2 3 4 5 6 7 8 9 10 11
| package com.laisc.securitydemo002.repository;
import com.laisc.securitydemo002.entity.User; import org.springframework.data.jpa.repository.JpaRepository;
import java.util.Optional;
public interface UserRepository extends JpaRepository<User, Long> { Optional<User> findByUsername(String username); }
|
MyUserDetailsService.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
| package com.laisc.securitydemo002.security;
import com.laisc.securitydemo002.entity.User; import com.laisc.securitydemo002.repository.UserRepository; import org.springframework.beans.factory.annotation.Autowired; 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.stream.Collectors;
@Service public class MyUserDetailsService implements UserDetailsService {
@Autowired private UserRepository userRepository;
@Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { User user = userRepository.findByUsername(username) .orElseThrow(() -> new UsernameNotFoundException("用户不存在"));
return new org.springframework.security.core.userdetails.User( user.getUsername(), user.getPassword(), user.isEnabled(), true, true, true, user.getRoles().stream() .map(role -> new SimpleGrantedAuthority(role.getName())) .collect(Collectors.toList()) ); } }
|
Securitydemo002Application.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| package com.laisc.securitydemo002;
import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication public class Securitydemo002Application {
public static void main(String[] args) { SpringApplication.run(Securitydemo002Application.class, args); System.out.println("ok!"); }
}
|
application.properties
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| spring.application.name=securitydemo002
server.port=8001
spring.datasource.url=jdbc:mysql://localhost:3306/test005?useSSL=false&serverTimezone=UTC spring.datasource.username=root spring.datasource.password=your_mysql_password spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.jpa.hibernate.ddl-auto=update spring.jpa.show-sql=true spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL8Dialect
|
初始化数据库:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| CREATE DATABASE test_db CHARACTER SET utf8mb4;
CREATE TABLE users ( id BIGINT PRIMARY KEY AUTO_INCREMENT, username VARCHAR(50) NOT NULL UNIQUE, password VARCHAR(100) NOT NULL, enabled BOOLEAN DEFAULT TRUE );
CREATE TABLE roles ( id BIGINT PRIMARY KEY AUTO_INCREMENT, name VARCHAR(50) NOT NULL UNIQUE );
CREATE TABLE user_roles ( user_id BIGINT, role_id BIGINT, PRIMARY KEY (user_id, role_id), FOREIGN KEY (user_id) REFERENCES users(id), FOREIGN KEY (role_id) REFERENCES roles(id) );
|
初始化数据:
1 2 3 4 5 6 7 8
| INSERT INTO users(username, password) VALUES ('user', '{noop}123456'); INSERT INTO users(username, password) VALUES ('admin', '{noop}admin123');
INSERT INTO roles(name) VALUES ('ROLE_USER'), ('ROLE_ADMIN');
INSERT INTO user_roles(user_id, role_id) VALUES (1, 1), (2, 2);
|
完成!