SpringSecurity测试

master
zhangfuping 2 months ago
commit 91ecd20f66
  1. 33
      .gitignore
  2. 106
      pom.xml
  3. 52
      src/main/java/cc/bnblogs/springinit/DemoApplicationConfiguration.java
  4. 13
      src/main/java/cc/bnblogs/springinit/SpringInitApplication.java
  5. 68
      src/main/java/cc/bnblogs/springinit/config/SecurityConfig.java
  6. 26
      src/main/java/cc/bnblogs/springinit/controller/UserController.java
  7. 12
      src/main/java/cc/bnblogs/springinit/mapper/UserMapper.java
  8. 14
      src/main/java/cc/bnblogs/springinit/pojo/MyUser.java
  9. 37
      src/main/java/cc/bnblogs/springinit/service/CustomUserDetailsService.java
  10. 21
      src/main/java/cc/bnblogs/springinit/service/UserService.java
  11. 12
      src/main/resources/application.yml
  12. 13
      src/test/java/cc/bnblogs/springinit/SpringInitApplicationTests.java

33
.gitignore vendored

@ -0,0 +1,33 @@
HELP.md
target/
!.mvn/wrapper/maven-wrapper.jar
!**/src/main/**/target/
!**/src/test/**/target/
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
build/
!**/src/main/**/build/
!**/src/test/**/build/
### VS Code ###
.vscode/

@ -0,0 +1,106 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>cc.bnblogs</groupId>
<artifactId>SpringInit</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>SpringInit</name>
<description>SpringInit</description>
<properties>
<java.version>1.8</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<spring-boot.version>2.7.6</spring-boot.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<version>8.0.32</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.3.1</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>3.5.3.1</version>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>${spring-boot.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>${spring-boot.version}</version>
<configuration>
<mainClass>cc.bnblogs.springinit.SpringInitApplication</mainClass>
<skip>true</skip>
</configuration>
<executions>
<execution>
<id>repackage</id>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

@ -0,0 +1,52 @@
package cc.bnblogs.springinit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
//@Configuration
public class DemoApplicationConfiguration {
private Logger logger = LoggerFactory.getLogger(DemoApplicationConfiguration.class);
// @Bean
public UserDetailsService myUserDetailsService() {
InMemoryUserDetailsManager inMemoryUserDetailsManager = new InMemoryUserDetailsManager();
String[][] usersGroupsAndRoles = {
{ "zhangsan", "password", "ROLE_ACTIVITI_USER", "GROUP_activitiTeam" },
{ "lisi", "password", "ROLE_ACTIVITI_USER", "GROUP_activitiTeam" },
{ "wangwu", "password", "ROLE_ACTIVITI_USER", "GROUP_activitiTeam" },
{ "other", "password", "ROLE_ACTIVITI_USER", "GROUP_otherTeam" },
{ "admin", "password", "ROLE_ACTIVITI_ADMIN" },
};
for (String[] user : usersGroupsAndRoles) {
List<String> authoritiesStrings = Arrays.asList(Arrays.copyOfRange(user, 2, user.length));
logger.info("> Registering new user: " + user[0] + " with the following Authorities[" + authoritiesStrings + "]");
inMemoryUserDetailsManager.createUser(new User(user[0], passwordEncoder().encode(user[1]),
authoritiesStrings.stream().map(s -> new SimpleGrantedAuthority(s)).collect(Collectors.toList())));
}
return inMemoryUserDetailsManager;
}
// @Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}

@ -0,0 +1,13 @@
package cc.bnblogs.springinit;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringInitApplication {
public static void main(String[] args) {
SpringApplication.run(SpringInitApplication.class, args);
}
}

@ -0,0 +1,68 @@
package cc.bnblogs.springinit.config;
//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.authentication.builders.AuthenticationManagerBuilder;
//import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
//import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
//import org.springframework.security.crypto.password.PasswordEncoder;
//
//
//@Configuration
//public class SecurityConfig extends WebSecurityConfigurerAdapter {
//
// @Override
// protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
// auth.inMemoryAuthentication().
// withUser("lucy").
// password(passwordEncoder.encode("123")).roles("admin").
// and().
// withUser("tom")
// .password(passwordEncoder.encode("123")).roles("admin");
// }
//
// @Bean
// PasswordEncoder password() {
// return new BCryptPasswordEncoder();
// }
//}
import cc.bnblogs.springinit.service.CustomUserDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
@EnableWebSecurity
public class SecurityConfig {
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests()
.antMatchers("/login", "/register").permitAll()
.anyRequest().authenticated() // 默认所有请求需登录
.and()
.formLogin()
.defaultSuccessUrl("/hello", true) // 登录成功后跳转到 /hello
.permitAll()
.and()
.logout()
.permitAll();
return http.build();
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}

@ -0,0 +1,26 @@
package cc.bnblogs.springinit.controller;
import cc.bnblogs.springinit.pojo.MyUser;
import cc.bnblogs.springinit.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class UserController {
@Autowired
private UserService userService;
@GetMapping("/hello")
public String hello() {
return "Hello World";
}
@PostMapping("/register")
public String register(@RequestBody MyUser user) {
userService.register(user);
return "User registered successfully!";
}
}

@ -0,0 +1,12 @@
package cc.bnblogs.springinit.mapper;
import cc.bnblogs.springinit.pojo.MyUser;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
@Mapper
public interface UserMapper extends BaseMapper<MyUser> {
@Select("SELECT * FROM users WHERE username = #{username}")
MyUser selectByUsername(String username);
}

@ -0,0 +1,14 @@
package cc.bnblogs.springinit.pojo;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
@Data
@TableName("users")
public class MyUser {
@TableId
private Long id;
private String username;
private String password;
private Boolean enabled;
}

@ -0,0 +1,37 @@
package cc.bnblogs.springinit.service;
import cc.bnblogs.springinit.mapper.UserMapper;
import cc.bnblogs.springinit.pojo.MyUser;
import org.springframework.beans.factory.annotation.Autowired;
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 org.springframework.security.core.userdetails.User;
import java.util.Collections;
@Service
public class CustomUserDetailsService implements UserDetailsService {
@Autowired
private UserMapper userMapper;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
MyUser user = userMapper.selectByUsername(username);
if (user == null) {
throw new UsernameNotFoundException("User not found with username: " + username);
}
// 如果不需要处理权限,直接返回用户信息,默认赋予一个角色
return new User(
user.getUsername(),
user.getPassword(),
user.getEnabled(),
true,
true,
true,
Collections.emptyList()
);
}
}

@ -0,0 +1,21 @@
package cc.bnblogs.springinit.service;
import cc.bnblogs.springinit.mapper.UserMapper;
import cc.bnblogs.springinit.pojo.MyUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
@Service
public class UserService {
@Autowired
private PasswordEncoder passwordEncoder;
@Autowired
private UserMapper userMapper;
public void register(MyUser user) {
user.setPassword(passwordEncoder.encode(user.getPassword()));
userMapper.insert(user);
}
}

@ -0,0 +1,12 @@
server:
port: 8090
spring:
datasource:
username: root
password: 123456
url: jdbc:mysql://192.168.175.130:3307/db?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf-8
driver-class-name: com.mysql.cj.jdbc.Driver

@ -0,0 +1,13 @@
package cc.bnblogs.springinit;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class SpringInitApplicationTests {
@Test
void contextLoads() {
}
}
Loading…
Cancel
Save