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

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?

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.

Spring, CORS, and j_spring_security_logout

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.

Spring Security - Java Based Configuration AuthenticationManager and Http403ForbiddenEntryPoint

I've updated my spring security to 3.2 to be able to use Java based annotations to configure the project, without need to have an XML.
I almost configure all things, but there is 2 issues I didn't (and don't know how) to configure.
How can I configure the Http403ForbiddenEntryPoint?
How can I configure my custom AuthenticationManager?
<security:http entry-point-ref="entryPoint" >
...
</security:http>
<bean id="entryPoint" class="org.springframework.security.web.authentication.Http403ForbiddenEntryPoint" />
<security:authentication-manager alias="myAuthenticationManagerImpl" />
Here is my custom authentication class:
#Service ("authenticationManager")
public class AuthenticationManagerImpl implements AuthenticationManager {
...
}
Apparently there is something in the works to address this but as it currently stands there is no way of doing this through annotations. This question seems to seeking the same answer. The standalone project in the works is here and apparently they are merging it into spring security 3.2.X sometime in the near future.

#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

security:http and properties (Spring Security)

I am using Spring Security 3.0.6. for modularity reasons, I would like to use properties in the security:http context.
<security:http>
...
<security:intercept-url pattern="/path/to/my/url/*" access="${token}" />
...
</security:http>
Is that possible ?
If not, if there any workaround that could be used to obtain the same behavior ?
You can use the standard PropertyPlaceholderConfigurer.

Categories