简体   繁体   English

即使使用@PreAuthorize(“permitAll()”),Spring Security也会阻止匿名请求

[英]Spring Security blocks anonymous requests even with @PreAuthorize(“permitAll()”)

I have a lot of API endpoints that need authenticated requests, and a few that are allowed for any request. 我有很多需要经过身份验证的请求的API端点,以及一些允许任何请求的端点。 I would like Spring Security to block anonymous requests by default, but to let me overwrite it: 我希望Spring Security默认阻止匿名请求,但是让我覆盖它:

aHttpSecurity.authorizeRequests().anyRequest().authenticated()

...

@PreAuthorize("permitAll()")
@RequestMapping("/foobar")
public ResponseEntity<FooBar> get() {
  ...
}

Unfortunately, this does not work: /foobar outputs 401. Any idea how to do? 不幸的是,这不起作用: /foobar输出401.任何想法怎么办?

@PreAuthorize is just an annotation which wraps method to check if user can execute annotated method. @PreAuthorize只是一个注释,它包装方法以检查用户是否可以执行带注释的方法。 It works not just with controllers. 它不仅适用于控制器。

When you have http requests, firstly requests go through some spring security filters and when you write .anyRequest().authenticated() you just do not go to some wrapped controller endpoint. 当你有http请求时,首先请求通过一些spring安全过滤器,当你编写.anyRequest().authenticated()你就不会去一些包装的控制器端点。

So, If you have a few endpoints you can exlude it 所以,如果你有几个端点,你可以将它排除在外

aHttpSecurity.authorizeRequests() .antMatchers(HttpMethod.GET, "/foobar/**").permitAll() .antMatchers("/**").authenticated()

and delete @PreAuthorize("permitAll()") 并删除@PreAuthorize("permitAll()")

Spring Security has two levels of Security. Spring Security有两个级别的安全性。

Filter Level and Method Level. 过滤级别和方法级别。

Filter Level would work with URL and If a URL is not configured to be accessed it will be denied access with 401 or 403 accordingly. 过滤级别适用于URL,如果未将URL配置为访问,则相应地拒绝访问401或403。 This is handled by FilterSecurityInterceptor 这由FilterSecurityInterceptor处理

Method Level is often used as a second level of defense to Authorize who can access a method and what operations or objects he/she can manipulate. 方法级别通常用作授权谁可以访问方法以及他/她可以操作哪些操作或对象的第二级防御。 This is handled by MethodSecurityInterceptor 这由MethodSecurityInterceptor处理

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM