springsecurity提供了开箱即用的登录权限校验功能。
1. 开箱即用
首先,在springboot项目在pom文件加入springsecurity starter。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
启动服务后,会在日志中看到生成的password, 默认的用户是user。这样项目下所有的api都要经过登录后,才可以访问。
Using generated security password: 05ea4cc1-5eb7-4a8d-87dd-f82ca86d44f8
2. 配置用户名密码
在开发模式下,可以在内存中创建用户。这样就创建了一个名固定密码的user用户,角色是ADMIN。
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Bean
public PasswordEncoder myEncoder() {
return new BCryptPasswordEncoder();
}
@Override
public void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().withUser("user").password(myEncoder().encode("3389999c-8fc7-a211-897e-8f2d10aea7c2")).roles("ADMIN");
}
}
3. Http Post请求403错误解决
按照上述方法配置后,Http Get请求正常,但是Post请求总是返回403错误。这是因为http默认开启的csrf保护。可以按如下配置解决这个问题。
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable().httpBasic() //关闭csrf保护
.and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) //session配置成无状态模式,适用于REST API
.and().authorizeRequests().anyRequest().authenticated(); // 所有请求都要经过登录认知
}
4. 整体配置
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Bean
public PasswordEncoder myEncoder() {
return new BCryptPasswordEncoder();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable().httpBasic().and().sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS).and().authorizeRequests().anyRequest().authenticated();
}
@Override
public void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().withUser("user").password(myEncoder().encode("3666680c-2227-4401-222e-8f2d10aea222")).roles("ADMIN");
}
}