package com.yan.springsecdemo01.config;
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.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
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 org.springframework.security.web.SecurityFilterChain;
/**
* @program: springSec
* @description:
* @author: Mr.Yan
* @create: 2024-08-27 21:09
**/
@Configuration
@EnableWebSecurity // 开启WebSecurity
public class SecurityConfig {
@Bean
public UserDetailsService userDetailsService() {
//定义用户信息
UserDetails build1 = User.withUsername("admin").password("{noop}123456").roles("user", "admin").build();
//构建第二个普通用户
UserDetails build2 = User.withUsername("user").password("{noop}123456").roles("user").build();
//将用户信息添加springSecurity
InMemoryUserDetailsManager UserDetailsManager = new InMemoryUserDetailsManager();
UserDetailsManager.createUser(build1);
UserDetailsManager.createUser(build2);
return UserDetailsManager;
}
@Bean
public PasswordEncoder passwordEncoder() {
//密码加密
return new BCryptPasswordEncoder();
}
}
package com.yan.springsecdemo01;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.security.crypto.password.PasswordEncoder;
@SpringBootTest
class SpringSecdemo01ApplicationTests {
@Autowired
private PasswordEncoder passwordEncoder;
@Test
// 生成密码加密后的字符串
public void test01() {
//编码-》之后解不出来
String password = passwordEncoder.encode("123456");
System.out.println(password); //$2a$10$Xy/18r9kAVsmo4axTGqt...MvPocGE.NIF0SQMifmt/UtMweGbpPm
//匹配密码
System.out.println(passwordEncoder.matches("123456",password)); //true
}
}
<!-- 集成spring-security-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>