问题
I have a following controller:
@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 config:
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SpringSecurityWebAppConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
}
}
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.
回答1:
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.
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();
}
来源:https://stackoverflow.com/questions/59489558/isauthenticated-annotation-does-not-prevent-access