Spring boot —— Basic 认证
basic认证咋说呢,最不安全,但却是是最简单的,我以为不会有问题,结果碰了一堆坑,在这里记录一下:
1 引包:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
2 创建一个config的类,记得继承 WebSecurityConfigurerAdapter,并且加上这两个注解@Configuration,@EnableWebSecurity
3 需要加上这个,要不然密码输入正确也会报错,我当时不太记得什么报错了,搜到的解决方法是这个
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
4 配置哪些被拦截:
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests() .antMatchers("/api/**").access("hasRole('ROLE_ADMIN')").and().httpBasic();
全都拦截:http.authorizeRequests() .anyRequest().authenticated() .and().httpBasic();
}
这里当时遇到了问题就是url访问失败,后来加了这个好了http.csrf().disable(),我大概查了一下,这个是关于跨域保护,API调用的话,关闭是没有问题的。
5 认证用户设置:
a 最简单实现,在内存中,只有一组用户名和密码可以选择:
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication().withUser("admin").password(passwordEncoder().encode("123456")).authorities("ROLE_USER");
}
b 内存+数据库查询方式,这个就是把a中的用户名和密码通过查询数据库的方式预先读到内存中,但我觉得,既然使用了数据库,应该不是想一次性读取的方式,而是可以动态控制,所以用数据库的小伙伴应该看方式c。
c 定义一个类实现UserDetailsService,然后在这个类中写DB查询的代码,并且把这个类注入到config中。
1 UserDetailsService实现:
public class MyUserDetailsService implements UserDetailsService {
@Override
public UserDetails loadUserByUsername(String username )throws UsernameNotFoundException {
//根据用户名查询DB
if (user ==null) {
throw new UsernameNotFoundException("User not found by name: "+ username);
}
return toUserDetails(user);
}
private UserDetails toUserDetails(User user) { return User.withUsername(user.getUserId()).password(new BCryptPasswordEncoder().encode(user.getUserSecret())).roles("ADMIN").build();
}
}
2 config 注入
@Bean
public UserDetailsService myUserDetailsService() {
return new MyUserDetailsService();
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(myUserDetailsService());
}
差不多就这些了,就是记录一下,其实里面我也有不太清楚的,慢慢学习慢慢补充。