2

I am using Spring and Spring-Security in a Vaadin application.

I want to check if the user has a certain role using SecurityContextHolderAwareRequestWrapper.isUserInRole(...) but cannot figure out how to get a reference to the wrapper (I tried injecting this using @Autowired, NB: I did not manually configure an instance of it as I believe the DelegatingFilterProxy is already doing this behind the scenes).

This stack overflow issue provided me with the solution, but I cannot uncover how to access or instantiate the wrapper properly.

My other alternative is to access the SecurityContext directly and iterate though the GrantedAuthorities as per the other suggestions in the linked SO issue.

How should I access/instantiate the wrapper?

Community
  • 1
  • 1
Syntax
  • 2,155
  • 2
  • 23
  • 34

1 Answers1

5

It should work out of the box, at least in Spring Security 3.1 (every HttpServletRequest in security chain should be instance of SecurityContextHolderAwareRequestWrapper).

servlet-api-provision attribute of <http> element adds to stack:

Provides versions of HttpServletRequest security methods such as isUserInRole() and getPrincipal() which are implemented by adding a SecurityContextHolderAwareRequestFilter bean to the stack. Defaults to true.

The filter SecurityContextHolderAwareRequestFilter is simple and only wraps HttpServletRequest in SecurityContextHolderAwareRequestWrapper:

public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
        throws IOException, ServletException {
    chain.doFilter(new SecurityContextHolderAwareRequestWrapper(
            (HttpServletRequest) req, rolePrefix), res);
}

(Watch out bug #SEC-1943 - the filter has wrong name assigned to alias SERVLET_API_SUPPORT_FILTER.)

Grzegorz Rożniecki
  • 27,415
  • 11
  • 90
  • 112
  • Hmm I'm using 3.0.2 and unable to upgrade. – Syntax Jul 04 '12 at 11:00
  • Just checked 3.0.X docs and code - [should be the same](http://static.springsource.org/spring-security/site/docs/3.0.x/reference/springsecurity-single.html#nsa-servlet-api-provision). Can you explicitly add `` to your security bean config? – Grzegorz Rożniecki Jul 04 '12 at 11:12
  • Cool, so my Application is an HttpServletRequestListener and I receive a reference to the HttpServletRequest on onRequestStart; through which I can check/cast to the SecurityContextHolderAwareRequestWrapper and make the appropriate call. Thanks for your help! – Syntax Jul 04 '12 at 11:20