How can I return a 401 instead of a 403 while using Spring Security

692 views
Skip to first unread message

Gregg Bolinger

unread,
Jun 8, 2015, 10:56:01 AM6/8/15
to grails-de...@googlegroups.com
I'm using spring security 2.0-RC4 in my grails 2.4.4 application. When attempting to access a secured resource, Spring Security always returns a 403. If I'm logged in, I would expect a 403. However, if I'm not logged in / my session has expired, I'd expect to get a 401. I asked about this on Stackoverflow and was pointed towards this class:


And I also received an answer to implement my own BeanPostProcessor which looks like code below. this (with relative bits converted to Groovy).

I'm unable to get the following code to actually trigger in the right place, so I'm not even 100% this is the right approach. Can anyone point me in the correct direction to return a 401 when accessing a secure resource while not logged in?

Thanks

@Configuration
public class WebCtxConfig  implements BeanPostProcessor {

        @Override
        public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
            if (bean instanceof SessionManagementFilter) {
                SessionManagementFilter filter = (SessionManagementFilter) bean;
                filter.setInvalidSessionStrategy(new InvalidSessionStrategy() {

                    @Override
                    public void onInvalidSessionDetected(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
                        response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
                    }
                });
            }
            return bean;
        }

        @Override
        public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
            return bean;
        }
    }
Reply all
Reply to author
Forward
0 new messages