commit 91ecd20f66955c5fcb97efd5877d3c16ddb1cd0e Author: zhangfuping <1337425156@qq.com> Date: Fri Sep 20 18:22:01 2024 +0800 SpringSecurity测试 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..549e00a --- /dev/null +++ b/.gitignore @@ -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/ diff --git a/pom.xml b/pom.xml new file mode 100644 index 0000000..4d64dcf --- /dev/null +++ b/pom.xml @@ -0,0 +1,106 @@ + + + 4.0.0 + cc.bnblogs + SpringInit + 0.0.1-SNAPSHOT + SpringInit + SpringInit + + 1.8 + UTF-8 + UTF-8 + 2.7.6 + + + + org.springframework.boot + spring-boot-starter-web + + + + org.projectlombok + lombok + true + + + + org.springframework.boot + spring-boot-starter-security + + + + org.springframework.boot + spring-boot-starter-test + test + + + + org.springframework.boot + spring-boot-starter-jdbc + + + + com.mysql + mysql-connector-j + 8.0.32 + + + + com.baomidou + mybatis-plus-boot-starter + 3.5.3.1 + + + + com.baomidou + mybatis-plus-generator + 3.5.3.1 + + + + + + org.springframework.boot + spring-boot-dependencies + ${spring-boot.version} + pom + import + + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.8.1 + + 1.8 + 1.8 + UTF-8 + + + + org.springframework.boot + spring-boot-maven-plugin + ${spring-boot.version} + + cc.bnblogs.springinit.SpringInitApplication + true + + + + repackage + + repackage + + + + + + + + diff --git a/src/main/java/cc/bnblogs/springinit/DemoApplicationConfiguration.java b/src/main/java/cc/bnblogs/springinit/DemoApplicationConfiguration.java new file mode 100644 index 0000000..b92bd8c --- /dev/null +++ b/src/main/java/cc/bnblogs/springinit/DemoApplicationConfiguration.java @@ -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 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(); + } + +} diff --git a/src/main/java/cc/bnblogs/springinit/SpringInitApplication.java b/src/main/java/cc/bnblogs/springinit/SpringInitApplication.java new file mode 100644 index 0000000..f9299a8 --- /dev/null +++ b/src/main/java/cc/bnblogs/springinit/SpringInitApplication.java @@ -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); + } + +} diff --git a/src/main/java/cc/bnblogs/springinit/config/SecurityConfig.java b/src/main/java/cc/bnblogs/springinit/config/SecurityConfig.java new file mode 100644 index 0000000..3f74c46 --- /dev/null +++ b/src/main/java/cc/bnblogs/springinit/config/SecurityConfig.java @@ -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(); + } +} diff --git a/src/main/java/cc/bnblogs/springinit/controller/UserController.java b/src/main/java/cc/bnblogs/springinit/controller/UserController.java new file mode 100644 index 0000000..93e27be --- /dev/null +++ b/src/main/java/cc/bnblogs/springinit/controller/UserController.java @@ -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!"; + } +} diff --git a/src/main/java/cc/bnblogs/springinit/mapper/UserMapper.java b/src/main/java/cc/bnblogs/springinit/mapper/UserMapper.java new file mode 100644 index 0000000..2676b88 --- /dev/null +++ b/src/main/java/cc/bnblogs/springinit/mapper/UserMapper.java @@ -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 { + @Select("SELECT * FROM users WHERE username = #{username}") + MyUser selectByUsername(String username); +} diff --git a/src/main/java/cc/bnblogs/springinit/pojo/MyUser.java b/src/main/java/cc/bnblogs/springinit/pojo/MyUser.java new file mode 100644 index 0000000..0186ef2 --- /dev/null +++ b/src/main/java/cc/bnblogs/springinit/pojo/MyUser.java @@ -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; +} diff --git a/src/main/java/cc/bnblogs/springinit/service/CustomUserDetailsService.java b/src/main/java/cc/bnblogs/springinit/service/CustomUserDetailsService.java new file mode 100644 index 0000000..e2c8701 --- /dev/null +++ b/src/main/java/cc/bnblogs/springinit/service/CustomUserDetailsService.java @@ -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() + ); + } +} diff --git a/src/main/java/cc/bnblogs/springinit/service/UserService.java b/src/main/java/cc/bnblogs/springinit/service/UserService.java new file mode 100644 index 0000000..4890af3 --- /dev/null +++ b/src/main/java/cc/bnblogs/springinit/service/UserService.java @@ -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); + } +} diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml new file mode 100644 index 0000000..8e24ecd --- /dev/null +++ b/src/main/resources/application.yml @@ -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 + + + diff --git a/src/test/java/cc/bnblogs/springinit/SpringInitApplicationTests.java b/src/test/java/cc/bnblogs/springinit/SpringInitApplicationTests.java new file mode 100644 index 0000000..a21da5c --- /dev/null +++ b/src/test/java/cc/bnblogs/springinit/SpringInitApplicationTests.java @@ -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() { + } + +}