[英]Spring Boot Security configuring HttpSecurity
为了授权请求,我们覆盖了我们提到访问 API 我们想要哪个角色的configure(HttpSecurity)
方法。 但是我们没有提到的 API 无需登录即可访问。 为什么会出现这种行为?
我没有为 API 编写permitAll()
为什么这是默认行为?
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/admin").hasRole("ADMIN")
.antMatchers("/user").hasAnyRole("ADMIN", "USER")
.antMatchers("/").hasRole("USER")
.and()
.formLogin();
}
}
In this code admin
API can be accessed by admin role, user
API can be accessed by admin as well as user role, /
API can be accessed by user role and there is one more API /student
which I didn't mention and I can无需登录即可访问。
问题是我怎么没有为学生 API 编写permitAll()
方法。
将此行: .antMatchers("/").hasRole("USER")
更改为: .anyRequest().hasRole("USER")
。
仅检查配置的 URL。 如果你不配置一个URL,根本不会检查。
因此,您应该添加一个检查所有其他 URL 的配置,请参阅Spring 安全参考:
11.2. 使用 FilterSecurityInterceptor 授权 HttpServletRequest
[...]
protected void configure(HttpSecurity http) throws Exception { http //... .authorizeRequests(authorize -> authorize 1.mvcMatchers("/resources/**", "/signup", "/about").permitAll() 2.mvcMatchers("/admin/**").hasRole("ADMIN") 3.mvcMatchers("/db/**").access("hasRole('ADMIN') and hasRole('DBA')") 4.anyRequest().denyAll() 5 ); }
1 指定了多个授权规则。 每个规则都按照它们被声明的顺序来考虑。
2 我们指定了多个 URL 模式,任何用户都可以访问。 具体来说,如果 URL 以“/resources/”开头、等于“/signup”或等于“/about”,则任何用户都可以访问请求。
3 任何以“/admin/”开头的 URL 将仅限于具有“ROLE_ADMIN”角色的用户。 您会注意到,由于我们正在调用 hasRole 方法,因此我们不需要指定“ROLE_”前缀。
4 任何以“/db/”开头的 URL 都要求用户同时拥有“ROLE_ADMIN”和“ROLE_DBA”。 您会注意到,由于我们使用了 hasRole 表达式,我们不需要指定“ROLE_”前缀。
5 任何尚未匹配的 URL 都将被拒绝访问。 如果您不想意外忘记更新授权规则,这是一个很好的策略。
为了保护未在configure方法中配置的API,必须添加行.anyRequest().denyAll()
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/admin").hasRole("ADMIN")
.antMatchers("/user").hasAnyRole("ADMIN", "USER")
.antMatchers("/").hasRole("USER")
.anyRequest().denyAll()
.and()
.formLogin();
}
}
对于每个请求进行保护而不在配置方法中配置它
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests(authorize -> authorize
.anyRequest().authenticated()
);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.