Spring-Security
Spring Security 笔记
Spring Security 的底层是通过一系列的 Filter 来管理的,每个 Filter 都有其自身的功能,它们的顺序也非常重要。
默认配置
添加依赖后,不作任何配置,默认全部接口都需要认证才能访问,否则报错
{
"timestamp": "2023-02-03 15:07:54",
"status": 403,
"error": "Forbidden",
"path": "/path-to-api"
}
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
HttpSecurity 配置
anyRequest 匹配所有请求路径
access SpringEl 表达式结果为 true 时可以访问
anonymous 匿名可以访问
denyAll 用户不能访问
fullyAuthenticated 用户完全认证可以访问(非remember-me下自动登录)
hasAnyAuthority 如果有参数,参数表示权限,则其中任何一个权限可以访问
hasAnyRole 如果有参数,参数表示角色,则其中任何一个角色可以访问
hasAuthority 如果有参数,参数表示权限,则其权限可以访问
hasIpAddress 如果有参数,参数表示IP地址,如果用户IP和参数匹配,则可以访问
hasRole 如果有参数,参数表示角色,则其角色可以访问
permitAll 用户可以任意访问
rememberMe 允许通过remember-me登录的用户访问
authenticated 用户登录后可访问
CSRF 不支持 POST 导致 permitAll() 不起作用
httpSecurity.permitAll 并不会绕开 springsecurity 的过滤器验证,配置的 url 还是会通过 spring security 过滤器。
webSecurity.ignoring 是完全绕过了spring security 的所有 filter,相当于不走 spring security
@Configuration
public class SpringSecurityConfiguration extends WebSecurityConfigurerAdapter {
private static final String[] NEED_AUTH_URLS = {
"/hello1",
"/hello2/**"
};
@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity.authorizeRequests()
.antMatchers(NEED_AUTH_URLS).authenticated()
.anyRequest().permitAll()
.and()
.formLogin();
}
}
下面并不能实现只认证某些接口,放行其他接口,全部接口都会经过 filter,导致 403 未授权,意味着已经登录认证成功(否则报401),但没有访问对应api的权限
打开debug日志,看到
Invalid CSRF token found for http://localhost:8080/path-to-api
org.springframework.security.web.csrf.CsrfFilter 中
原因:RESTful 技术与 CSRF(Cross-site request forgery跨站请求伪造)的冲突造成的,CSRF 默认支持的方法: GET|HEAD|TRACE|OPTIONS,不支持POST。可以在security在配置中禁用
解决:
禁用 csrf
@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity.authorizeRequests()
.antMatchers(NEED_AUTH_URLS).authenticated()
.anyRequest().permitAll()
.and()
.formLogin()
.and()
.csrf().disable();
}
上一篇 Tesseract
下一篇 Mockito
页面信息
location:
protocol
: host
: hostname
: origin
: pathname
: href
: document:
referrer
: navigator:
platform
: userAgent
: