Spring, CORS, and j_spring_security_logout - java

I need to use CORS with Spring Security. I've succeeded in getting login and basic security working, using a OncePerRequestFilter that is configured in app-beans.xml as follows:
<bean id="corsAwareAuthenticationFilter"class="org.broadinstitute.portal.servlet.CorsAwareAuthenticationFilter"/>
<security:http use-expressions="true">
<security:custom-filter ref="corsAwareAuthenticationFilter" after="PRE_AUTH_FILTER"/>
...
I basically followed the approach in this question: Cross-Origin Resource Sharing with Spring Security
My configuration for logout in app-beans.xml is simply:
<security:logout delete-cookies="JSESSIONID"/>
This works fine without CORS.
My problem is logging out. CORS is stopping access to j_spring_security_logout. Any idea why my OncePerRequestFilter is being called when logging in, but not when logging out?
Edited to add:
Thanks to alain.janinm, I solved the problem. I needed to set my filter to be called before the LOGOUT_FILTER. The following configuration addition solved the problem:
<security:custom-filter ref="corsAwareAuthenticationFilter" before="LOGOUT_FILTER"/>
Note, using position="LOGOUT_FILTER" didn't work, as that put my filter in the same position as the Spring LOGOUT_FILTER. My filter doesn't do the same thing as the LOGOUT_FILTER -- all mine does is to add the CORS headers. So I actually need the Spring LOGOUT_FILTER to still be called.

Thanks to alain.janinm, I solved the problem. I needed to set my filter to be called before the LOGOUT_FILTER. The following configuration addition solved the problem:
<security:custom-filter ref="corsAwareAuthenticationFilter" before="LOGOUT_FILTER"/>
Note, using position="LOGOUT_FILTER" didn't work, as that put my filter in the same position as the Spring LOGOUT_FILTER. My filter doesn't do the same thing as the LOGOUT_FILTER -- all mine does is to add the CORS headers. So I actually need the Spring LOGOUT_FILTER to still be called.

Related

Stateless spring application - JSESSIONID still generated

I'm trying to make a java web application truly stateless (although still using basic authentication) but since now a JSESSIONID cookie is always generated by our servlet container (Tomcat).
This my stack:
Java: 1.8
Spring: 4.1.6.RELEASE
Spring Security: 4.0.2.RELEASE
Tomcat: 7.0.93
We use XML configuration, so this is my security config file, where I used the STATELESS option for session creation:
<beans:bean id="requestCache" class="org.springframework.security.web.savedrequest.NullRequestCache" />
<http use-expressions="true" create-session="stateless" pattern="/api/**">
<request-cache ref="requestCache"/>
<csrf disabled="true"/>
<!-- REST ENDPOINTS PATH BASED -->
<intercept-url pattern="...."/>
<intercept-url pattern="...."/>
</http>
As documented in this response this should be enough to ensure that Spring Security won't create a session, but other parts of my application could still create one.
The question is: how do I track who's requesting the session creation?
Basically what I'm trying to do is adapt a backend used by a stateful java application, to be consumed in a stateless way by other client applications that will only make calls to a particular path (/api/**) as detailed in my security config file.
This stateful part uses some beans that are session-scoped; I need to use those same beans but in a request-scope way, thus my need to ensure that a JSESSIONID cookie is never created.
Trying for example to disable cookies altogheter in Tomcat (or in the browser) accomplishes this, so I'm trying a way to do it directly with Spring.
If you want to be sure sessions are not created, create a filter and wrapper the HttpServletRequest with a class the blocks/fails/ignores the getSession(...) calls.

Thymeleaf's sec:authorize-url with Spring's #Secured

I'm developing application using Spring MVC 4.X, using spring security 4.X for authentication/authorization and Thymeleaf 2.1.2 for view layer. I'm controlling access to controllers using #Secured annotion. Problem is, that Thymeleaf ignores these annotations when resolving sec:authorize-url attributes. Does anyone has working setup for this?
My security config looks like this:
<http use-expressions="true" entry-point-ref="authEntryPoint" security-context-repository-ref="sessionRepository">
<intercept-url pattern="/login/**" access="isAnonymous()"/>
<intercept-url pattern="/**" access="hasRole('USER')" />
<custom-filter position="FORM_LOGIN_FILTER" ref="usernamePasswordDomainAuthenticationFilter"/>
<logout logout-url="/logout"/>
</http>
and in servlet config, there is
<security:global-method-security secured-annotations="enabled" />
Controllers look like this:
#Secured("ROLE_EXAMPLE")
#Controller
#RequestMapping("/example")
public class ExampleController {
}
We use this Setup so security protects all controllers globally plus every controller (or controller's method if needed) can restrict access more if needed.
Everything works fine, secured controllers are not accessible for user without speciified role, thymeleaf-extras-springsecurity4 is obviously configured correctly, because sec-authorize="hasRole('EXAMPLE')" works as expected (and it takes #Secured into account).
But I feel it is prone to error to declare role both in controller and in the template, so I'd much rather use sec:authorize-url. By debugging, I found out, that it checks
if user hasRole('USER'), as declared in Security's xml config file, but it completely ignores #Secured annotations when using sec:authorize-url. In worst case, I could declare all the access in security's config file, but I like #Secured annotation much more.
Is it possible to make this setup work?

#PreAuthorize not working correctly

My controller:
#RequestMapping("/createchar")
#PreAuthorize("hasRole('ROLE_USER')")
public String createCharacter(Map<String, Object> map, Principal principal) {
spring-security.xml
<global-method-security pre-post-annotations="enabled"
proxy-target-class="true" />
...
<intercept-url pattern="/game*" access="ROLE_USER" />
<form-login login-page="/account/login" ...
Page is always loaded, even after redeploying the application. I haven't even logged in. Why it doesn't redirect it to login page?
If you need any more info, feel free to ask.
The controller beans typically reside inside the servlet context, so they are not affected neither by the AOP declarations nor by the bean post processors in the root application context.
Difference between applicationContext.xml and spring-servlet.xml in Spring Framework
I believe that proxying the controller classes is not a good idea, see Spring-MVC Problem using #Controller on controller implementing an interface - so I prefer to avoid using AOP on controller classes to avoid surprises - and use it only on service/DAO beans i.e. the beans in the root application context.
In this case you should use intercept-url approach for the web pages.
Being on the internship I faced the same problem. It took me and my teammates 2 days of cranching Spring Security source codes. However, today we were told that the reason of not even seeing any exceptions are "OP mechanisms", which was mentioned earlier.
The reason is the proxy class must be created.
Spring Proxy Mechanisms
So all we needed to do in our particular situation is to add
<aop:config proxy-target-class="true" />
to the app-servlet.xml
If you try to debug your code and look for methods that are invoked by Spring you may solve even similar problems (as the real cause may be different) but it is a great challenge for your patience.
Hope this will help you and others.
I was facing the same issue. My problem solved when i moved the below element from applicationContext.xml to *-servlet.xml (my dispatcher's configuration xml).
<security:global-method-security secured-annotations="enabled"/>
You have to include this element on your dispatcher's xml NOT on your application's xml.
Spring FAQ

Disable Remember-Me in Spring Security & Tomcat

I wonder, is there any way to disable remember-me in Spring Security?
Scenario I want to implement is pretty common: after closing browser window I would like user's session to expire. Seems weird, but it doesn't work with Tomcat 7 & Spring Security 3.1.
We use auto-config in Spring Security configuration file, but there is no remember-me element.
What is the best solution to get it working? Thanks in advance!
Update Here is the usage scenario to clarify my problem:
User logs into restricted area, say, /secure.html
Then he closes the browser without logging out manually.
He opens the browser again and goes directly to /secure.html.
Current Spring's behaviour: page is displayed successfully. Expected behaviour: redirecting to login page.
New symptoms for differential diagnosis:
User is probable reathenticated because JSESSIONID in the same between browser close/open. How I could forse Tomcat or Spring to generate a new session for every browser session?
Update Fragment of Spring Security configuration:
<http auto-config="true">
<anonymous key="anonymous-security" />
<intercept-url pattern="/auth/**" access="IS_AUTHENTICATED_ANONYMOUSLY" />
<intercept-url pattern="/**" access="ROLE_ADMIN" />
<form-login login-page="/auth/login.html"
default-target-url="/auth/default.html"
authentication-failure-url="/auth/failed.html" />
<logout logout-success-url="/auth/logout.html" delete-cookies="JSESSIONID" />
</http>
Update Documentation claims that there is no default remember-me configuration in auto-config="true" since 3.0 (we use 3.1):
In versions prior to 3.0, this list also included remember-me
functionality. This could cause some confusing errors with some
configurations and was removed in 3.0.
What's wrong with my web app?
Why don't you just logout the existing user by redirecting to: /j_spring_security_logout?
In my implementation with latest Spring security and Tomcat 6, I am using the following configuration: Is it similar to yours?
<http use-expressions="true" access-denied-page="/Error.xhtml">
<intercept-url access="isAuthenticated()" pattern="/secure.xhtml"/>
<form-login />
<logout invalidate-session="true" logout-success-url="/search.xhtml"/>
</http>
You can try adding a logouthandler to teminate the local session:
<!-- Logout handler terminating local session -->
<bean id="logoutHandler" class="org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler">
<property name="invalidateHttpSession" value="true" />
</bean>
In reality it defaults to true so you probably don't need the property to be set.
Problem clarification:
I ran into the same issue: my browser would remember my user.
Typically: after logging in to access a restricted area, closing the browser, then reopen it and enter the same restricted area it would let me access it when I expected to be prompted for credentials.
After playing around I noticed one important thing: this behavior is NOT consistent across browsers:
Eclipse's underlying browser does remember after closing
Chrome does remember after closing
IE (9) does NOT remember after closing
Firefox (16.0.1) does NOT remember after closing
Safari (5.1.7 for windows) does NOT remember after closing
More browser types & versions could be tested...
Solution:
A work around may be to try detect when a user is closing his browser, and trigger a log-out when this happens. Not too sure how doable that is though.
There might be a better solution, I'll update this answer if I find it.

Unable to retrieve security context from within Spring-Jersey

I am trying to retrieve a security context within my spring-jersey bean, however I keep getting Null authentication. When I run the same command from within my spring application it correctly retrieves the current logged in users security context.
The configuration of spring-jersey requires creating a separate servlet to the main spring application, thus the web.xml has two servlet's - one for spring app, second for jersey rest api.
Assuming the problem is related to this, I tried setting the security context sharing mode to global, however I still unable to get the context information from within Jersey.
SecurityContextHolder.setStrategyName(SecurityContextHolder.MODE_GLOBAL)
Any help with this would be greatly appreciated!
Many thanks,
Nigel
Perhaps user is simply not authenticated, because your Jersey requests don't have a session cookie and therefore are not associated with the authenticated user's session?
You may check it by enabling anonymous authentication in Spring Security - you should get anonymous authentication instead of null if the guess is right.
#axtavt Thank you for the comment. This clue helped solve my problem, checking how my security filters were configured, I found this line in my spring security configuration
<security:intercept-url pattern="/api/**" filters="none" />
This line effectively disables all spring security filters, removing this fixed the problem.
Many thanks for your help :)

Categories