活动地址:CSDN21天学习挑战赛
目前Spring官网给出的Security的最新版本为5.7.2,所以这里也以最新版作为整合,SpringBoot采用2.7.2版本.
引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- Spring健康检查-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<!-- Security依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
配置类
注意点: 最新版Security 官方已经决定淘汰SpringSecurityConfigurationAdapter,也就是说最新版配置不需要再继承WebSecurityConfigurerAdapter这个类做配置,取而代之的是配置相应的过滤器链来进行相关配置, 配置方式以及属性保持不变.
Security认证方式有两种: 基于内存的方式和基于数据库的方式;
基于内存
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.formLogin(form->{
// 指定登录成功默认跳转url
form.defaultSuccessUrl("/hello");
//这里有两个登陆成功路径跳转 下面这个见名知意,登录成功后请求转发,url并不会改变,并且 为post请求,需要注意.而上面则是Url重定向.根据实际需求选用即可.
//form.successForwardUrl("/hello");
});
// 开启"记住我"功能
http.rememberMe();
//禁用缓存
http.headers().cacheControl();
return http.build();
}
@Bean
public UserDetailsService userDetailsService(){
UserDetails user = User.builder()
.username("demo")
.password(new BCryptPasswordEncoder().encode("123"))
.roles("USER")
.build();
// 采用内存模式
return new InMemoryUserDetailsManager(user);
}
}
之前版本配置方式对比
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("demo")
.password(passwordEncoder().encode("123"))
.authorities("123","ROLE_ADMIN");
}
}
完成配置重启项目,观察启动日志,可以看到由于手动配置了账户密码,Spring已经不再打印默认的密码,并且登录页较之前多了一个Remember me的勾选框,说明配置类成功.
登录成功后,成功跳转
基于数据库JDBC
与之前用法相同, 实现UserDetailsService接口即可,这里我模拟了一下数据库的查询,实际操作中替换即可.
@Slf4j
@Service
public class UserService implements UserDetailsService {
public HashMap dbMap = new HashMap();
public void setDbMap(){
ArrayList<GrantedAuthority> authorities = new ArrayList<>();
authorities.add(new SimpleGrantedAuthority("ROLE_admin"));
dbMap.put("demo",new User("demo",new BCryptPasswordEncoder().encode("123"),authorities));
dbMap.put("cat",new User("cat",new BCryptPasswordEncoder().encode("321"),authorities));
dbMap.put("tom",new User("tom",new BCryptPasswordEncoder().encode("456"),authorities));
}
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
setDbMap();
return (UserDetails) dbMap.get(username);
}
}
相应的基于内存方式需要注释掉
同时添加登陆成功后相应的Handler,可以选择将用户不敏感信息,组装Token进行返回.
自此SpringBoot可以正常使用Security.
需要其他配置可以看下这个博客,根据需要重即可 SpringSecurity认证流程