一、开发环境搭建(spring boot项目的创建过程):
在pom中加入依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
依赖加入后创建controller层测试:
@RestController
@RequestMapping(value = "/test")
public class UserController {
@GetMapping
public String test(){
return "TEST";
}
}
启动application类进行测试,可以在控制台看到security默认的密码:

测试,在浏览器中输入http://localhost:8080/test
页面如下:

用户默认为userr,密码为控制台默认的密码:

成功跳转后:

一个最简单的security项目实现,以上使用的是默认机制!
二、也可以自定义用户名密码,简单的方式:
spring:
security:
user:
name: user
password: 123
但是这种方式只能有一个用户,我们可以硬编码为2+的用户,写一个类extends WebSecurityConfigurerAdapter :
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
//防止报错:java.lang.IllegalArgumentException: There is no PasswordEncoder mapped for the id "null"
private PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.passwordEncoder(passwordEncoder())
.withUser("11")
.password(passwordEncoder().encode("11"))
.roles("user")
.and()
.withUser("22")
.password(passwordEncoder().encode("22"))
.roles("user");
}
}
启动项目可以进行测试,硬编码2+用户已经实现,但是这种不是很灵活:
我们可以实现读取数据库灵活添加用户的目的,创建User



详情见: https://www.jianshu.com/p/37ba0b016ca0
然后在WebSecurityConfig重写UserDetailsService:
@Autowired
private UserRepository userRepository;
@Override
@Bean
public UserDetailsService userDetailsService() {
return new UserDetailsService() {
@Override
public UserDetails loadUserByUsername(String name) throws UsernameNotFoundException {
User user = userRepository.getByName(name);
if (user == null) {
throw new UsernameNotFoundException("用户名未找到");
}
String password = user.getPassword();
PasswordEncoder passwordEncoder = PasswordEncoderFactories.createDelegatingPasswordEncoder();
String passwordAfterEncoder = passwordEncoder.encode(password);
return org.springframework.security.core.userdetails.User.withUsername(user.getName()).password(passwordAfterEncoder).roles("").build();
}
};
}
重写后在config中引入,
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// 数据库读取登录信息
auth.userDetailsService(userDetailsService());
// auth.inMemoryAuthentication()
// .passwordEncoder(passwordEncoder())
// .withUser("11")
// .password(passwordEncoder().encode("11"))
// .roles("user")
// .and()
// .withUser("22")
// .password(passwordEncoder().encode("22"))
// .roles("user");
}
网友评论