Spring 3 Security: AccessDeniedHandler is not being invoked - java

I have a spring 3 application with the configurations given below. When any user tries to access a page and he/she isn't logged in, I get an Access is Denied exception with an ugly stack trace. How do I handle this exception and not let it dump out a stack trace. I implemented my own access-denied-handler but that doesn't get invoked.
Based on the type of the requested resource, I would like to show custom error messages or pages. Here is my spring configuration.
How do I get Spring to invoke my access-denied-handler . Here is my spring configuration
<security:http auto-config='true'>
<security:intercept-url pattern="/static/**" filters="none"/>
<security:intercept-url pattern="/login" filters="none"/>
<security:intercept-url pattern="/**" access="ROLE_USER" />
<security:form-login login-page="/index"
default-target-url="/home" always-use-default-target="true"
authentication-success-handler-ref="AuthenticationSuccessHandler"
login-processing-url="/j_spring_security_check"
authentication-failure-url="/index?error=true"/>
<security:remember-me key="myLongSecretCookieKey" token-validity-seconds="1296000"
data-source-ref="jdbcDataSource" user-service-ref="AppUserDetailsService" />
<security:access-denied-handler ref="myAccessDeniedHandler" />
</security:http>
<bean id="myAccessDeniedHandler"
class="web.exceptions.handlers.AccessDeniedExceptionHandler">
<property name="errorPage" value="/public/403.htm" />
</bean>
The custom class for handling this exception is given below
public class AccessDeniedExceptionHandler implements AccessDeniedHandler
{
private String errorPage;
#Override
public void handle(HttpServletRequest request, HttpServletResponse response,
AccessDeniedException arg2) throws IOException, ServletException {
response.sendRedirect(errorPage);
}
public void setErrorPage(String errorPage) {
if ((errorPage != null) && !errorPage.startsWith("/")) {
throw new IllegalArgumentException("errorPage must begin with '/'");
}
this.errorPage = errorPage;
}
}
When I run this application, this is the error that I get. I am only pasting a part of the stacktrace and the Spring Debug logs.
20:39:46,173 DEBUG AffirmativeBased:53 - Voter: org.springframework.security.access.vote.RoleVoter#5b7da0d1, returned: -1
20:39:46,173 DEBUG AffirmativeBased:53 - Voter: org.springframework.security.access.vote.AuthenticatedVoter#14c92844, returned: 0
20:39:46,178 DEBUG ExceptionTranslationFilter:154 - Access is denied (user is anonymous); redirecting to authentication entry point
org.springframework.security.access.AccessDeniedException: Access is denied
at org.springframework.security.access.vote.AffirmativeBased.decide(AffirmativeBased.java:71)
at org.springframework.security.access.intercept.AbstractSecurityInterceptor.beforeInvocation(AbstractSecurityInterceptor.java:204)
How do I fix this problem? Firstly, I want to stop spring from Throwing that exception. If it still throws it, I want to handle it and not raise any flags.
Update: I have attached a part of my web.xml as well.
<!-- Hibernate filter configuration -->
<filter>
<filter-name>HibernateFilter</filter-name>
<filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>HibernateFilter</filter-name>
<url-pattern>/*</url-pattern>
<dispatcher>FORWARD</dispatcher>
<dispatcher>REQUEST</dispatcher>
</filter-mapping>
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!--Dispatcher Servlet -->
<servlet>
<servlet-name>rowz</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>

In your configuration You require the user to be always authenticated when entering any URL on Your site:
<security:intercept-url pattern="/**" access="ROLE_USER" />
I think You should allow the user to be unauthenticated when entering the login page:
<security:intercept-url pattern="/your-login-page-url" access="ROLE_ANONYMOUS" />
<security:intercept-url pattern="/your-login-process-url" access="ROLE_ANONYMOUS" />
<security:intercept-url pattern="/your-login-failure-url" access="ROLE_ANONYMOUS" />
<security:intercept-url pattern="/**" access="ROLE_USER" />
If You use URL's like: /login/start, /login/error and /login/failure You can have:
<security:intercept-url pattern="/login/**" access="ROLE_ANONYMOUS" />
<security:intercept-url pattern="/**" access="ROLE_USER" />
Update:
Having this configuration should make the framework to redirect all unauthenticated (anonymous) users to login page, and all authenticated to AccessDeniedHandler. The AccessDeniedException is one of the core parts of the framework and ignoring it is not a good idea. It's hard to help more if You only provide parts of Your Spring Security configuration.
Be sure to read the JavaDoc for ExceptionTranslationFilter for detailed explanation of what exceptions are thrown by the framework, why and how are the handled by default.
If possible, try removing as many custom parts You added, like AuthenticationSuccessHandler, RememberMeAuthenticationFilter and AccessDeniedHandler and see if the problem pesist? Try to get the minimal congiuration and add new features step by step to see where the error comes from.
One important thing that You don't mention in Your question is what is the result of this error message? Do You get HTTP 500? Or HTTP 403? Or do You get redirected to login page?
If, as You mentioned in the question, the user is unauthenticated and he/she gets redirected to login page, than that's how it's intended to work. It looks like You get the error message logged by ExceptionTranslationFilter:172 only because You have DEBUG level set to Spring Security classes. If so, than that's also how it's intended to work, and if You don't want the error logged, than simply rise the logging level for Spring Secyruty classes.
Update 2:
The patterns with filters="none" must match the login-page, login-processing-url and authentication-failure-ur attributes set in <security:form-login /> to skip all SpringSecurity checks on pages that display the login page and process the logging in.
<security:http auto-config='true'>
<security:intercept-url pattern="/static/**" filters="none"/>
<security:intercept-url pattern="/index" filters="none"/>
<security:intercept-url pattern="/j_spring_security_check" filters="none"/>
<security:intercept-url pattern="/**" access="ROLE_USER" />
<security:form-login login-page="/index"
default-target-url="/home" always-use-default-target="true"
authentication-success-handler-ref="AuthenticationSuccessHandler"
login-processing-url="/j_spring_security_check"
authentication-failure-url="/index?error=true"/>
<security:remember-me key="myLongSecretCookieKey" token-validity-seconds="1296000"
data-source-ref="jdbcDataSource" user-service-ref="AppUserDetailsService" />
<security:access-denied-handler ref="myAccessDeniedHandler" />
</security:http>

AccessDeniedHandler is invoked when user is logged in and there is no permissions to resource (source here). If you want to handle request for login page when user is not logged in, just configure in security-context:
<http ... entry-point-ref="customAuthenticationEntryPoint">
And define customAuthenticationEntryPoint:
<beans:bean id="customAuthenticationEntryPoint" class="pl.wsiadamy.webapp.controller.util.CustomAuthenticationEntryPoint">
</beans:bean>
TIP, don't try to fight with ExceptionTranslationFilter.
I have tried to override org.springframework.security.web.access.ExceptionTranslationFilter, without effects:
<beans:bean id="exceptionTranslationFilter" class="org.springframework.security.web.access.ExceptionTranslationFilter">
<beans:property name="authenticationEntryPoint" ref="customAuthenticationEntryPoint"/>
<beans:property name="accessDeniedHandler" ref="accessDeniedHandler"/>
</beans:bean>
<beans:bean id="accessDeniedHandler"
class="org.springframework.security.web.access.AccessDeniedHandlerImpl">
<beans:property name="errorPage" value="/accessDenied.htm"/>
</beans:bean>
The ref="customAuthenticationEntryPoint" just didn't invoked.

I have added Spring Access denied page in follwing way:
Spring Frame Work: 3.1
Spring Security: 3.1, Java 1.5+
Entry in *-security.xml:
<security:access-denied-handler error-page="/<My Any error page controller name>" />
Example:
<security:access-denied-handler error-page="/accessDeniedPage.htm" />
Error page will always start with "/"
Entry for controller:
#Controller
public class RedirectAccessDenied {
#RequestMapping(value = "/accessDeniedPage.htm", method = RequestMethod.GET)
public String redirectAccessDenied(Model model) throws IOException, ServletException {
System.out.println("############### Redirect Access Denied Handler!");
return "403";
}
}
Here 403 is my JSP name.

Spring Security uses an AuthenticationEntryPoint object to decide what to do when a user requires authentication. You can create your own AuthenticationEntryPoint bean ( see javadoc ), and then set the entryPoint attribute in the http element:
<http entry-point-ref="entryPointBean" .... />
However, by default, the form-login element creates a LoginUrlAuthenticationEntryPoint which redirects all of your unauthenticated users to the login page, so you shouldn't have to do this yourself. In fact, the log you posted claims it is forwarding the user to the authentication entry point: "Access is denied (user is anonymous); redirecting to authentication entry point".
I wonder if the problem is that you turned off the filter chain for the login url. Instead of setting filters to none, which means spring security is bypassed entirely, try keeping the filters on but allowing unrestricted access like this:
<security:intercept-url pattern="/login" access="permitAll" />
If that still doesn't help, please post the rest of the log so we can see what happens after the request is transferred to the entry point.

Programmatically solution:
#Order(1)
#Configuration
#EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
//
// ...
//
#Override
protected void configure(HttpSecurity http) throws Exception {
http.exceptionHandling().accessDeniedHandler(new AccessDeniedHandlerImpl() {
#Override
public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
super.handle(request, response, accessDeniedException);
accessDeniedException.printStackTrace();
}
});
//
// ...
//
}
}

Can you check your web.xml is supporting forward request?
errorPage is a FORWARD request and mostly in web.xml we support REDIRECTS only. Just a thought else your code looks ok to me.
Edited
A different point of view and This is been taken from working code only.
Have a look at Authenticated Voter class
Disable the annotations
<global-method-security pre-post-annotations="disabled"
secured-annotations="disabled" access-decision-manager-ref="accessDecisionManager">
</global-method-security>
bypassing filters
<http auto-config="true" use-expressions="true"
access-decision-manager-ref="accessDecisionManager"
access-denied-page="/accessDenied">
<intercept-url pattern="/appsecurity/login.jsp" filters="none" />
<intercept-url pattern="/changePassword" filters="none" />
<intercept-url pattern="/pageNotFound" filters="none" />
<intercept-url pattern="/accessDenied" filters="none" />
<intercept-url pattern="/forgotPassword" filters="none" />
<intercept-url pattern="/**" filters="none" />
<form-login login-processing-url="/j_spring_security_check"
default-target-url="/home" login-page="/loginDetails"
authentication-failure-handler-ref="authenticationExceptionHandler"
authentication-failure-url="/?login_error=t" />
<logout logout-url="/j_spring_security_logout"
invalidate-session="true" logout-success-url="/" />
<remember-me />
<!-- Uncomment to limit the number of sessions a user can have -->
<session-management invalid-session-url="/">
<concurrency-control max-sessions="1"
error-if-maximum-exceeded="true" />
</session-management>
</http>
custom Decision Voter
<bean id="customVoter" class="xyz.appsecurity.helper.CustomDecisionVoter" />
Access Decision Manager
<!-- Define AccessDesisionManager as UnanimousBased -->
<bean id="accessDecisionManager" class="org.springframework.security.access.vote.UnanimousBased">
<property name="decisionVoters">
<list>
<ref bean="customVoter" />
<!-- <bean class="org.springframework.security.access.vote.RoleVoter"
/> -->
<bean class="org.springframework.security.access.vote.AuthenticatedVoter" />
</list>
</property>
</bean>
Authentiation Exception Handler
<bean id="authenticationExceptionHandler"
class="org.springframework.security.web.authentication.ExceptionMappingAuthenticationFailureHandler">
<property name="exceptionMappings">
<props>
<!-- /error.jsp -->
<prop
key="org.springframework.security.authentication.BadCredentialsException">/?login_error=t</prop>
<!-- /getnewpassword.jsp -->
<prop
key="org.springframework.security.authentication.CredentialsExpiredException">/changePassword</prop>
<!-- /lockedoutpage.jsp -->
<prop key="org.springframework.security.authentication.LockedException">/?login_error=t</prop>
<!-- /unauthorizeduser.jsp -->
<prop
key="org.springframework.security.authentication.DisabledException">/?login_error=t</prop>
</props>
</property>
</bean>

It looks like spring tries to redirect users who have not logged in to the login page, which is "/index", but that itself is a protected url.
The other possibility is, it tries to display /public/403.html, but that is again protected by security configuration.
Can you add the following entries and try?
<security:intercept-url pattern="/login" filters="none" />
<security:intercept-url pattern="/public/**" filters="none" />

Related

Spring Security Custom Filter Never Called

The problem is that my custom Spring Security filter is never invoked when a request comes in. During debugging, I found that in doFilter() in FilterChainProxy, my filter (JwtAuthenticationFilter) can be fetched:
But it's skipped. Then I found it's due to:
So the superclass of my filer, which is AbstractAuthenticationProcessingFilter thinks the request doesn't need authentication and it just calls doFilter() to pass it down. I think my configs specified that auth is needed. This specific request is /ui/home/index.jsp, where \ui is the context.
My security configs:
<http use-expressions="true" pattern="/**" entry-point-ref="JwtAuthenticationEntryPoint" create-session="stateless">
<custom-filter before="CONCURRENT_SESSION_FILTER" ref="jwtAuthenticationFilter" />
<intercept-url pattern="/home/**" access="isAuthenticated()"/>
// some other intercept-url definitions
</http>
<authentication-manager alias="authenticationManager">
<authentication-provider ref="authenticationProvider"/>
</authentication-manager>
And bean configs:
<bean id="jwtAuthenticationFilter" class="com.pk.jjwt.JwtAuthenticationTokenFilter" >
<property name="authenticationManager" ref="authenticationManager"/>
<property name="authenticationSuccessHandler" ref="jwtAuthenticationSuccessHandler" />
</bean>
<bean id="JwtAuthenticationEntryPoint" class="com.pk.jjwt.JwtAuthenticationEntryPoint" />
<bean id="authenticationProvider" class="com.pk.jjwt.JwtAuthenticationProvider" />
<bean id="jwtAuthenticationSuccessHandler" class="com.pk.jjwt.JwtAuthenticationSuccessHandler" />
I wonder what might cause the filters getting skipped? I think I specified that every url pattern needs to be authenticated. I'm not sure why it thinks that request doesn't need authentication from my custom filter.
Edit:
So I debugged the requiresAuthentication() method, and found:
Basically it's evaluating uri.endsWith("/ui/**") and uri is /ui/home/index.jsp. It returned false, so the filter is skipped.

Accessing user name in the socket controller method while Integrating spring security with spring websocket and

I am implementing spring web socket into our web application and I want to access the user name in the socket controller method but I am getting it as null.
Here is the code
#MessageMapping("/user/sockettest" )
#SendTo("/topic/sockettestresult")
public String sockAdd(ListId[] listIds) {
..
SecurityContextHolder.getContext().getAuthentication().getPrincipal();
return stringRet;
}
The spring-security xml looks like this
<sec:intercept-url pattern="/topic/**" access="permitAll" />
<sec:intercept-url pattern="/" access="permitAll" />
<sec:intercept-url pattern="/login*" access="permitAll" />
<sec:intercept-url pattern="/resources/**" access="permitAll" />
<sec:form-login login-page="/login" default-target-url="/user/home" always-use-default-target="true" authentication-failure-url="/login?error"/>
<sec:logout logout-success-url="/login?logout" delete-cookies="JSESSIONID" />
<sec:access-denied-handler error-page="/denied"/>
<sec:intercept-url pattern="denied/*" access="permitAll" />
<sec:csrf disabled="true" />
</sec:http>
The socket configuration looks like this
<websocket:stomp-endpoint path="/user/sockettest">
<websocket:sockjs/>
</websocket:stomp-endpoint>
<websocket:simple-broker prefix="/topic"/>
<websocket:message-converters register-defaults="false">
<bean id="mappingJackson2MessageConverter" class="org.springframework.messaging.converter.MappingJackson2MessageConverter">
<property name="objectMapper" ref="objectMapper"></property>
</bean>
</websocket:message-converters>
</websocket:message-broker>
I have looked at some examples and most of them are in java config, however the problem that I have with that is that when I use java config, it is adding an extra /info to the destination url and it is not even connecting to the socket so I am taking the xml route.
I am pretty new to spring web sockets and I am thinking that I am missing something while integrating it with spring security but that's just me. Let me know what I am doing wrong here?
You can access current user by adding java.security.Principal parameter to socket controller method.
#MessageMapping("/user/sockettest" )
#SendTo("/topic/sockettestresult")
public String sockAdd(ListId[] listIds, Principal principal) {
//do whatever you want
return stringRet;
}
docs

Spring Security authentication is ignored

Hello Stackoverflower,
i've got a Issue with the Spring Security stuff. The Login Box that should appear before you can proceed to your application dont appear and i can access to my application without any authentication. I dont have any clue why this happen.
It would be very important to know why no User and Password are asked.
I test my app with the RESTCLient Add on for firefox.
The important entry in the web.xml looks like:
<!-- Security Configuration -->
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/</url-pattern>
</filter-mapping>
<!-- Spring Json Init -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>json</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>json</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
My spring-security is:
<!-- Security Propertie Configuration -->
<security:http use-expressions="true">
<security:http-basic/>
</security:http>
<security:authentication-manager>
<security:authentication-provider
ref="springUserService" />
</security:authentication-manager>
The springUserService looks like this:
#Component
public class springUserService implements AuthenticationProvider {
#Override
public Authentication authenticate(Authentication authentication)
throws AuthenticationException {
String name = authentication.getName();
String password = authentication.getCredentials().toString();
List<GrantedAuthority> grantedAuths = new ArrayList<>();
return new UsernamePasswordAuthenticationToken(name, password, grantedAuths);
}
#Override
public boolean supports(Class<?> authentication) {
return authentication.equals(UsernamePasswordAuthenticationToken.class);
}
}
Im very thankfull for every Hint or answer.
I think you need to add some intercept url tag in your spring security config:
<security:intercept-url pattern="/securedUrl" access="isAuthenticated()" />
<security:intercept-url pattern="/login" access="permitAll" />
So change your code in something like this:
<security:http use-expressions="true">
<security:intercept-url pattern="/securedUrl" access="isAuthenticated()" />
<security:intercept-url pattern="/login" access="permitAll" />
</security:http>
You can also use wildcard in pattern-attribute or custom access evaluation:
<intercept-url pattern="/url1/**" access="hasAnyRole('ROLE_ADMIN', 'ROLE_USER')"/>
<intercept-url pattern="/url2/**" access="isAuthenticated()" />
<intercept-url pattern="/resources/**" access="permitAll" />
<intercept-url pattern="/**" access="permitAll" />
Try this:
<security:http auto-config="true" use-expressions="true" path-type="regex">
<security:intercept-url pattern="/admin/.*" access="hasRole('ROLE_ADMIN')" />
<security:intercept-url pattern="/.*" access="isAuthenticated()" />
</security:http>
Here is a more detailed example with explanations:
<http auto-config="true" use-expressions="true" path-type="regex">
<form-login
password-parameter="password" -- password field name in your form
username-parameter="username" -- username field name in your form
login-processing-url="/security/j_spring_security_check" -- where your login form should submit to, no need to map this to anything, Spring Security handles it
login-page="/login" -- where you'll be taken to when not logged in
authentication-failure-url="/login?login_error=t" -- if your login fails, security will redirect you with login_error set to t
default-target-url="/router" -- if you want to route people based on roles, etc, you can map a controller ot this URL
always-use-default-target="false" -- this will send logged in users to your router URL
/>
<headers>
<xss-protection/> -- inserts header to prevent prevents cross site scripting
</headers>
<logout logout-url="/security/j_spring_security_logout" /> -- logout url, no need ot map it to anything, handled by Spring Security
<intercept-url pattern="/admin/.*" access="hasRole('ROLE_ADMIN')" /> -- security URLs by roles
<intercept-url pattern="/register" access="permitAll"/> -- let new users register by allowing everyone access to the registration page
<intercept-url pattern="/.*" access="isAuthenticated()" requires-channel="https" /> -- require users to be authenticated for the rest of the page and require HTTPS (optional) for ALL urls
</http>

How do I create a logout with Spring Security?

I am trying to find a way just to setup a URL that will logout my user from the system. this is only for testing. Right now we are using the default login page in spring secuirty
here is my spring-secuirty.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-3.1.xsd">
<global-method-security pre-post-annotations="enabled" />
<http use-expressions="true">
<intercept-url access="hasRole('ROLE_VERIFIED_MEMBER')" pattern="/ask-union**" />
<intercept-url access="hasRole('ROLE_VERIFIED_MEMBER')" pattern="/ask-welfare**" />
<intercept-url pattern='/*' access='permitAll' />
<form-login default-target-url="/ask-union" />
<logout logout-success-url="/" />
<session-management session-fixation-protection="newSession">
<concurrency-control max-sessions="1"/>
</session-management>
</http>
<authentication-manager>
<authentication-provider>
<user-service>
<user name="xxxxx#aol.com.dev" password="testing" authorities="ROLE_VERIFIED_MEMBER" />
ser-service>
</authentication-provider>
</authentication-manager>
</beans:beans>
Add this line to your config
<logout logout-url="/sign-out"/>
Then if you have a link to that URL, then it will sign you out
(Add it just below your logout success config)
I am a bit late on this. But answer may help others.
Use following code. logout-success-url is the URL you want take user after logging out.
<http auto-config="true" use-expressions="true" access-denied-page="/denied">
<logout invalidate-session="true" logout-success-url="/landing" delete-cookies="JSESSIONID" />
</http>
Double-check the URL you're using -- the absolute path should be your-domain/projectPath/sign-out, per SJS's example. If the relevant portion of your spring-security.xml file looks like the following, it should work:
<http use-expressions="true">
. . .
<logout
logout-success-url="/"
logout-url="/sign-out"/>
If you're able to authenticate, then simply browse to that path, and it should log you out. If it still doesn't try experimenting with the intermediary subdirectories specified in the URL, i.e. your-domain/projectPath/some-subdirectory/log-out.
Are you able to authenticate? It may not just be the logout aspect that's failing...
Late to the party, but for future reference -- if you are interested in seeing how the security filters are instantiated and configured from XML, take a look at the following package:
org.springframework.security.config.annotation.web.configurers
For the logout filter configuration, this will be the LogoutConfigurer class. If you review the LogoutConfigurer.createLogoutFilter() method, you'll see how the default Logout filter is created. This implies that you can do the following in an #Configuration class:
#Bean
public LogoutFilter logoutFilter() {
// NOTE: See org.springframework.security.config.annotation.web.configurers.LogoutConfigurer
// for details on setting up a LogoutFilter
SecurityContextLogoutHandler securityContextLogoutHandler = new SecurityContextLogoutHandler();
securityContextLogoutHandler.setInvalidateHttpSession(true);
LogoutFilter logoutFilter = new LogoutFilter("/", securityContextLogoutHandler);
logoutFilter.setLogoutRequestMatcher(new AntPathRequestMatcher("/logout"));
return logoutFilter;
}
If you have that, you can then either configure further by beans or have that bean picked up automatically since its method name is logoutFilter()

Using Spring Security 3.1 to secure the same RESTful resources with both form-login and http-basic security

I have a java web application running on Tomcat 7.
I am using Spring 3.2 with Spring Security 3.1 on the backend, and am exposing an API via RESTful URLs following the /api/** pattern.
The UI for the web application is built using BackboneJS. I am using Backbone models mapped directly to the RESTful URLS.
The UI is locked down using form-login authentication, so the user is always redirected to the login screen if they have are not currently authenticated.
I am now attempting to expose the same RESTful URLs to another external service using http-basic authentication. Unfortunately, when securing the same URL pattern, it seems Spring will not allow me to use more than one filter chain. Whichever is defined first in the configuration file seems to take precedence.
I would hate to have to map to separate URL patterns for the same RESTful resources, but it seems like I may not have a choice.
Here is the important sample of my (currently broken) spring security configuration:
<!-- configure basic http authentication -->
<http pattern="/api/**" create-session="stateless">
<intercept-url pattern="/**" access="ROLE_USER"/>
<http-basic/>
</http>
<!-- configure form-login authentication -->
<http auto-config="true" use-expressions="true">
<intercept-url pattern="/ui/login" access="permitAll" />
<intercept-url pattern="/ui/logout" access="permitAll" />
<intercept-url pattern="/ui/loginfailed" access="permitAll" />
<intercept-url pattern="/**" access="ROLE_USER" />
<custom-filter ref="ajaxTimeoutRedirectFilter" after="EXCEPTION_TRANSLATION_FILTER" />
<form-login login-page="/ui/login" default-target-url="/" authentication-failure-url="/ui/loginfailed" />
<logout logout-success-url="/ui/logout" />
<session-management invalid-session-url="/ui/login"/>
</http>
My question is:
Is it possible to configure two different types of security (http-basic and form-login) for the same URL patterns using Spring Security? Is there a best practice for this type of scenario?
Thank you.
Why don't you just merge the two <http> elements like this:
<http pattern="/api/**" use-expressions="true">
<intercept-url pattern="/ui/login" access="permitAll" />
<intercept-url pattern="/ui/logout" access="permitAll" />
<intercept-url pattern="/ui/loginfailed" access="permitAll" />
<intercept-url pattern="/**" access="ROLE_USER" />
<http-basic/>
<custom-filter ref="ajaxTimeoutRedirectFilter" after="EXCEPTION_TRANSLATION_FILTER" />
<form-login login-page="/ui/login" default-target-url="/" authentication-failure-url="/ui/loginfailed" />
<logout logout-success-url="/ui/logout" />
<session-management invalid-session-url="/ui/login"/>
</http>
This would set up both a UsernamePasswordAuthenticationFilter and a BasicAuthenticationFilter in the same filter chain which could serve the ui client, and the external service as well.
Not possible out of the box to apply 2 different filter chain for a single URL pattern.
But it is a advisable to have unique URL patterns as UI and API, as you would have to apply a completely different filter chain in future.
For example the SecurityContextRepository hold the session information and is retrieved for each request. You don't want to apply the same for UI and API access through basic auth
Try to replace pattern="/" by pattern="/api/" in API config:
<http pattern="/api/**" create-session="stateless">
<intercept-url pattern="/api/**" access="ROLE_USER"/>
<http-basic/>
</http>

Categories

Resources