isAuthenticated注释不会阻止访问 [英] isAuthenticated annotation does not prevent access
问题描述
我有一个以下控制器:
@RestController
@RequestMapping("/payments")
public class PaymentController {
@Autowired
PaymentService paymentService;
@Autowired
private Environment env;
@PostMapping("/create")
@PreAuthorize("isAuthenticated()")
public ResponseEntity<String> create(@Valid @RequestBody DownPayment downpayment) {
Customer customer;
Charge charge;
User user = new User();
............
}
}
WebSecurity配置:
WebSecurity config:
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SpringSecurityWebAppConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
}
}
我想使用preAuthorize注释(方法级别)代替http安全性.付款/创建终结点是可公开访问的,可以正常运行而不会引发任何未经授权的错误.
I want to use preAuthorize annotation (method level) instead of http security. The payments/create endpoint is publicly accessible which works without throwing any unauthorised error.
推荐答案
设置断点并检查SecurityContextHolder
中包含的内容,例如像这样:SecurityContextHolder.getContext().getAuthentication()
.建议您将SecurityContextHolder
中包含的内容添加到您的问题中,以便人们可以更好地帮助您.
Set a breakpoint and check what is contained in the SecurityContextHolder
, e.g. like that: SecurityContextHolder.getContext().getAuthentication()
. I suggest you add what is contained in the SecurityContextHolder
to your question so that people can help you better.
我的假设是您具有匿名访问已启用,这意味着如果未设置其他身份验证(例如,通过AuthenticationTokenFilter
),则将匿名身份验证对象放置在SecurityContextHolder
中. Spring将其检测为身份验证,因此@PreAuthorize("isAuthenticated()")
批注不会阻止对API的访问.通常,您应该考虑使用基于角色的访问规则是否会更好,因为这些规则更细粒度.
My assumption is that you have anonymous access enabled, which means that an anonymous authentication object is placed in the SecurityContextHolder
if no other authentication was set (e.g. by a AuthenticationTokenFilter
). Spring detects this as an authentication, so that the access to your API is not prevented by the @PreAuthorize("isAuthenticated()")
annotation. Generally you should consider if it might not be better to use role-based access rules, as these are more fine-granular.
您可以按以下方式禁用匿名访问:
You can disable anonymous access as follows:
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.anonymous().disable()
.csrf().disable();
}
这篇关于isAuthenticated注释不会阻止访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!