简体   繁体   中英

Spring security return 401/403 instead of redirecting the user to the login page

I have some URLs that are protected. When you try to access a protected URL, spring security will intercept the request and will redirect you to the login page. When you successfully login you will be forwarded to the URL that you originally requested.

I would like for some URLs to be excluded from this behavior and instead to get an error either 401 or 403 status code. A good example would be when you do an AJAX POST to a protected URL. With the current configuration you will be redirected to login page and get a 200 response code when you are not authenticated. The jQuery code that initiated the request will execute the success handler which is wrong since the request is not completed.

How can I achieve this different behavior for only certain pages?

First, are you using annotations or xml config for Spring?

If you are using XML config, you have to order your URLs in your config from the less secured to the most secured.

If you are using Annotation and Java config, you can add an antMatchers for your AJAX URLs and you'll add something like permitAll(), so they won't be "secured" and filtered by Spring

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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