springboot+maven整合spring security

时间:2024-01-14 13:33:44

springboot+maven整合spring security已经做了两次了,然而还是不太熟悉,这里针对后台简单记录一下需要做哪些事情,具体的步骤怎么操作网上都有,不再赘述。
1.pom.xml中添加spring security的起步依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
2.创建spring security的配置类,继承WebSecurityConfigurerAdapter类,重写里面的configure(HttpSecurity http)和configure(AuthenticationManagerBuilder auth)两个方法。这两个方法即自定义配置的内容。
3.对于configure(AuthenticationManagerBuilder auth)方法,有从内存获取和从数据库获取两种方式。如果采用后者,需要实现UserDetailsService接口,并将此实现类的对象传入auth.userDetailsService()方法中,后面跟上加密方式(不跟上加密方式可能会报java.lang.IllegalArgumentException: There is no PasswordEncoder mapped for the id "null"的错误),实例如下:
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
MyUserDetailsService userService = new MyUserDetailsService();
auth.userDetailsService(userService).passwordEncoder(new BCryptPasswordEncoder());
}

另外,之前版本的springboot(2.0之前)可以在application.properties中使用security.basic.enable=false属性来禁用默认验证,新版本的springboot(2.0以上)移除了这一属性。spring security似乎是自行判断是启用默认配置还是自定义配置。在自定义配置的过程中如果只重写了configure(HttpSecurity http)方法,虽然此方法的自定义配置会起作用,但是登录验证依然是默认的,即用户名为user,密码为自动生成,后台会打印出来(这是默认情况,也可以自行设置),此时需要实现configure(AuthenticationManagerBuilder auth)方法来自定义验证策略。

ps:技巧是在一遍又一遍的重复中得以掌握,又在一遍又一遍的重复中得以精深。