isAuthenticated annotation does not prevent access

谁说我不能喝 提交于 2020-01-30 11:01:25

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!