Spring security duplicated RemeberMeProvider - java

I build an application with GWT on client side (in future I rewrite interface to JS) and duplicate functionality by REST requests. Based on Spring framework.
Now I need to implement authorization.
Here is my security-context.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
..........>
<security:http auto-config="false">
<security:form-login login-page="/login.html"/>
<security:intercept-url pattern="/login" access="IS_AUTHENTICATED_ANONYMOUSLY"/>
<security:intercept-url pattern="/mainGWT.html**" access="ROLE_USER"/>
<security:remember-me services-ref="rememberMeServices" />
</security:http>
<bean id="userDetailsService" class="com.damintsev.servlet.UserDetailsServiceImpl"/>
<bean id="daoAuthenticationProvider" class="org.springframework.security.authentication.dao.DaoAuthenticationProvider">
<property name="userDetailsService" ref="userDetailsService"/>
</bean>
<bean id="rememberMeAuthenticationProvider" class="org.springframework.security.authentication.RememberMeAuthenticationProvider">
<constructor-arg name="key" value="rock"/>
</bean>
<context:component-scan base-package="com.login"/>
<bean id="rememberMeServices" class=
"org.springframework.security.web.authentication.rememberme.TokenBasedRememberMeServices">
<property name="userDetailsService" ref="userDetailsService"/>
<property name="key" value="rock"/>
<property name="tokenValiditySeconds" value="5000"/>
<property name="alwaysRemember" value="true"/>
</bean>
<bean id="rememberMeFilter" class=
"org.springframework.security.web.authentication.rememberme.RememberMeAuthenticationFilter">
<property name="rememberMeServices" ref="rememberMeServices"/>
<property name="authenticationManager" ref="authenticationManager"/>
</bean>
<bean id="providerManager" class="org.springframework.security.authentication.ProviderManager">
<property name="providers">
<list>
<ref bean="daoAuthenticationProvider"/>
<ref bean="org.springframework.security.authentication.RememberMeAuthenticationProvider#0"/>
</list>
</property>
</bean>
<security:authentication-manager alias="authenticationManager">
</security:authentication-manager>
But rememberMe services didnt work. So I start to debug this and I found that rememberMeAuthenticationProvider initializes twise!!
At first time initializes with name org.springframework.security.authentication.RememberMeAuthenticationProvider#0 and strange (autogenerated maybe) key.
The second provider initializes with propertly name rememberMeAuthenticationProvider with propertly key.
Later there is a problem because key in TokenBasedRememberMeServices didnt match with rememberMeAuthenticationProvider.
But when I change name of bean to org.springframework.security.authentication.RememberMeAuthenticationProvider#0 it works fine.
What am I doing wrong ? Who initialize provider twise ?
<spring.version>3.2.3.RELEASE</spring.version>
Second part of question: I dont understand how set RememberMe cookie to client so I write class. And if from client I receive remember = true I call that methood. And It works. If You provide some exmples with remeber me + REST it will helps.
#Component
public class Security {
#Autowired
private RememberMeServices rememberMeServices;
public void remeberMe(HttpServletRequest request, HttpServletResponse response, Authentication authentication1) {
rememberMeServices.setAlwaysRemember(true);
rememberMeServices.loginSuccess(request, response, authentication1);
}
}

You have a bean called rememberMeAuthenticationProvider and you are also using the namespace remember-me element which will also create one, hence the duplicate. You've also declared a filter which won't be used unless you actually insert it into the filter chain.
Either remove the namespace element and declare all the beans fully yourself, or stick with the namespace and let it do the work. If you want to customize the RememberMeServices you can you can retain that and the services-ref as you have it, but it's not clear from your question why you need to customize things.
If a remember-me cookie is sent by the client then the server will process it regardless of the type of client. How it is set in the first place depends on the login mechanism. Form login processing will automatically invoke the RememberMeServices and set the cookie if appropriate.

Related

Pre-authentication in Spring Security + LDAP

Here is what I want to achieve:
I am using Websphere and I want to rely on the container to do the authentication (using Kerberos+SPNEGO). When it come to Spring Security, I want to rely on the pre-authentication, and use LDAP to retrieve user details (roles etc) for authorization checking.
Here is the part of Spring app context config I have (tried to only include related parts)
<s:global-method-security secured-annotations="enabled" pre-post-annotations="enabled" proxy-target-class="true" />
<bean id="springSecurityFilterChain" class="org.springframework.security.web.FilterChainProxy">
<s:filter-chain-map path-type="ant">
<s:filter-chain pattern="/**"
filters="securityContextPersistenceFilter,preAuthenticatedFilter" />
</s:filter-chain-map>
</bean>
<s:http use-expressions="true" create-session="stateless" auto-config="true">
<!--
<s:http-basic />
-->
</s:http>
<bean id="securityContextPersistenceFilter"
class="org.springframework.security.web.context.SecurityContextPersistenceFilter">
<property name='securityContextRepository'>
<bean class='org.springframework.security.web.context.HttpSessionSecurityContextRepository'>
<property name='allowSessionCreation' value='true' />
</bean>
</property>
</bean>
<bean id="preAuthenticatedFilter"
class="org.springframework.security.web.authentication.preauth.j2ee.J2eePreAuthenticatedProcessingFilter">
<property name="authenticationManager" ref="authenticationManager" />
</bean>
<s:authentication-manager alias="authenticationManager">
<s:authentication-provider ref="preAuthenticatedAuthenticationProvider" />
</s:authentication-manager>
<bean id="preAuthenticatedAuthenticationProvider"
class="org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationProvider">
<property name="preAuthenticatedUserDetailsService" >
<bean class="org.springframework.security.core.userdetails.UserDetailsByNameServiceWrapper" >
<property name="userDetailsService" ref="userDetailsService" />
</bean>
</property>
</bean>
<bean id="userDetailsService" class="org.springframework.security.ldap.userdetails.LdapUserDetailsService" >
<constructor-arg index="0" ref="ldapUserSearch"/>
<constructor-arg index="1" ref="ldapAuthoritiesPopulator"/>
<property name="userDetailsMapper" >
<bean class="com.foo.MyUserDetailsMapper" />
</property>
</bean>
<bean id="ldapContextSource"
class="org.springframework.security.ldap.DefaultSpringSecurityContextSource">
<!-- some setting skipped here -->
</bean>
<bean id="ldapUserSearch" class="org.springframework.security.ldap.search.FilterBasedLdapUserSearch">
<!-- some setting skipped here -->
</bean>
<bean id="ldapAuthoritiesPopulator"
class="org.springframework.security.ldap.userdetails.DefaultLdapAuthoritiesPopulator">
<!-- some setting skipped here -->
</bean>
<bean id="ldapTemplate" class="org.springframework.ldap.core.simple.SimpleLdapTemplate">
<constructor-arg ref="ldapContextSource" />
</bean>
It mostly worked, I can see correct user name and role coming in for my custom UserDetailsMapper (com.foo.MyUserDetailsMapper) which comes from LDAP, and inside that I am returning a new UserDetails with updated roles.
The problem is, in my controller, when I tried to do
SecurityContextHolder.getContext().getAuthentication()
It is returning null. (For which works before I change to pre-authentication)
Is there anything I missed?
Found the problem. Sorry that is mostly because of my own implementation fault which is not visible in the question itself.
My custom UserDetails impl is incorrectly having getEnabled() returning false. In LdapAuthenticationProvider, it is working fine as there is no checking on the user status.
However, in PreAuthenticatedAuthenticationProvider, by default there is a UserDetailsChecker which checks the status of user, for which getEnabled() returning false will cause the user details checker to fail silently, and causing authentication not populated to SecurityContext (i.e. treating that account as not authenticated)
Although it is mostly my implementation issue, I think still worth leaving here as a reference for difference of LdapAuthenticationProvider and PreAuthenticatedAuthenticationProvider

How to add a value from a cookie to the HTTP header in Spring WebServiceTemplate?

I am using Spring WebServiceTemplate in my client side code to send request to an existing 3rd party web service.
<bean id="vehicleQuotationWebServiceTemplate" class="org.springframework.ws.client.core.WebServiceTemplate">
<constructor-arg ref="messageFactory"/>
<property name="marshaller" ref="vehicleQuotationMarshaller" />
<property name="unmarshaller" ref="vehicleQuotationMarshaller" />
<property name="faultMessageResolver" ref="vehicleServiceClientFaultMessageResolver" />
<property name="defaultUri" value="http://localhost:8080/quote/endpoints"/>
</bean>
Everything was working fine until they added security check from the server side. Right now, in order to pass the server side security authenication, I need to pass some values from a cookie to the server. This I can do easily in SoapUI by modifying the http header (adding the cookie's value there), but my question is how can I do it in Java code with the Spring's WebServiceTemplate?
You can extend the WebServiceTemplate or in a more easy way use a custom sender who extends Spring's
org.springframework.ws.transport.http.CommonsHttpMessageSender
and set in your bean definition
<bean id="vehicleQuotationWebServiceTemplate" class="org.springframework.ws.client.core.WebServiceTemplate">
<constructor-arg ref="messageFactory"/>
<property name="marshaller" ref="vehicleQuotationMarshaller" />
<property name="unmarshaller" ref="vehicleQuotationMarshaller" />
<property name="faultMessageResolver" ref="vehicleServiceClientFaultMessageResolver" />
<property name="defaultUri" value="http://localhost:8080/quote/endpoints"/>
<property name="messageSender">
<bean class="org.springframework.ws.transport.http.MyHttpComponentsMessageSender"/>
</property>
</bean>
take a look at Spring forums
JSESSIONID and setting cookie for WebServiceTemplate

CAS + Spring Security Detect localhost

I am trying to implement an application with Spring security and CAS, it works fine on localhost but when I try to access it from an outside machine it and the application needs authentication it redirect to localhost too.
meaning
I access the application using https://172.16.1.50:8443/isxannouncements/
and when it needs authentication it should go to https://172.16.1.50:8443/cas/login/
but instead it goes to https://localhost:8443/isxannouncements/
which ofcourse breaks the application flow.
my config is
security-cas.xml
<bean id="serviceProperties"
class="org.springframework.security.cas.ServiceProperties">
<property name="service"
value="https://localhost:8443/isxannouncements/login"/>
</bean>
<!--
Allows changing where the CAS Server and CAS Service are easily
by specifying System Arguments or replacing the values only in one place.
Could also use external properties file -->
<context:property-placeholder
system-properties-mode="OVERRIDE" properties-ref="environment"/>
<util:properties id="environment">
<prop key="cas.service.host">localhost:8443</prop>
<prop key="cas.server.host">localhost:8443</prop>
</util:properties>
<!-- sends to the CAS Server, must be in entry-point-ref of security.xml -->
<bean id="casEntryPoint"
class="org.springframework.security.cas.web.CasAuthenticationEntryPoint">
<property name="serviceProperties" ref="serviceProperties"/>
<property name="loginUrl" value="https://localhost:8443/cas/login" />
</bean>
<!-- authenticates CAS tickets, must be in custom-filter of security.xml -->
<bean id="casFilter"
class="org.springframework.security.cas.web.CasAuthenticationFilter">
<property name="authenticationManager" ref="authenticationManager"/>
<property name="filterProcessesUrl" value="/login"/>
</bean>
<bean id="casAuthProvider" class="org.springframework.security.cas.authentication.CasAuthenticationProvider">
<property name="ticketValidator" ref="ticketValidator"/>
<property name="serviceProperties" ref="serviceProperties"/>
<property name="key" value="isxannouncements"/>
<property name="authenticationUserDetailsService" ref="DBUserServiceDetails"/>
<property name="statelessTicketCache" ref="statelessTicketCache"/>
</bean>
<bean id="statelessTicketCache" class="org.springframework.security.cas.authentication.EhCacheBasedTicketCache">
<property name="cache">
<bean class="net.sf.ehcache.Cache"
init-method="initialise" destroy-method="dispose">
<constructor-arg value="casTickets"/>
<constructor-arg value="50"/>
<constructor-arg value="true"/>
<constructor-arg value="false"/>
<constructor-arg value="3600"/>
<constructor-arg value="900"/>
</bean>
</property>
</bean>
<bean id="ticketValidator" class="org.jasig.cas.client.validation.Saml11TicketValidator">
<constructor-arg value="https://localhost:8443/cas" />
<property name="encoding" value="utf8" />
</bean>
<!-- Handles a Single Logout Request from the CAS Server must be in custom-filter of security.xml -->
<bean id="singleLogoutFilter" class="org.jasig.cas.client.session.SingleSignOutFilter"/>
and my security.xml
<security:http pattern="/resources/images" security="none"/>
<security:http use-expressions="true" entry-point-ref="casEntryPoint">
<security:intercept-url pattern="/login/*"
access="permitAll"/>
<security:intercept-url pattern="/resources/**"
access="permitAll"/>
<security:intercept-url pattern="/logout"
access="permitAll"/>
<security:intercept-url pattern="/errors/**"
access="permitAll"/>
<security:intercept-url pattern="/approve-announcement**"
access="hasRole('ROLE_USER')"/>
<security:intercept-url pattern="/delete-announcement**"
access="hasRole('ROLE_USER')"/>
<security:intercept-url pattern="/edit-announcement**"
access="hasRole('ROLE_USER')"/>
<security:intercept-url pattern="/admin/**"
access="hasRole('ROLE_ADMIN')"/>
<security:intercept-url pattern="/META-INF"
access="hasRole('ROLE_USER')"/>
<security:access-denied-handler error-page="/errors/403"/>
<security:custom-filter ref="singleLogoutFilter" before="LOGOUT_FILTER"/>
<security:custom-filter ref="casFilter" position="CAS_FILTER"/>
<security:port-mappings>
<security:port-mapping http="8080" https="8443"/>
</security:port-mappings>
<security:logout logout-url="/logout"
logout-success-url="https://localhost:8443/cas/logout"/>
</security:http>
<security:authentication-manager alias="authenticationManager">
<security:authentication-provider ref="casAuthProvider" />
</security:authentication-manager>
how to fix this ??
Ok I found a workaround but I did not test it properly,
Inspired by this answer I did the following
since I have two domains that the user might use to access my application, the only way to get the domain the user used was to get from the request and then return it to the security provider.
I created a bean named serviceProperties and used it instead of the serviceproperties of spring, and I overrided the method of getService to return the service based on the domain name that the user to access the application.
Then I made this bean available at Web Application Context, and I passed in the session, I had already extracted the domain from the Request and put it in the Session.
So when the CasAuthenticationEntryPoint tries to get the service, I pass the service URL that I created from the session appended to it is the service name.
We handle this with property files. Anything that is specific to a certain environment (i.e. your local machine versus your test server) should be in a property file.
For example, create properties files for each environment with something like this:
localhost.properties:
cas.service.url=http://localhost/login
test.properties:
cas.service.url=http://mytestserver/login
And then configure spring security with the value from the properties file instead of directly as you have it above:
Your build process would then have a target for each environment to shuffle the appropriate files into place in the final artifact.
CAS works under domain. so you should use cas.example.com and define it in the cas.properties

Using the Flash scope ( and RedirectAttributes ) without <mvc:annotation-driven /> in Spring MVC 3.1

In my Spring MVC 3.1 application, I think I can't use "<mvc:annotation-driven />". Why? Because I want to apply an interceptor to all mappings except to the "<mvc:resources" elements. So I can't use :
<mvc:annotation-driven />
<mvc:resources order="-10" mapping="/public/**" location="/public/" />
<mvc:resources order="-10" mapping="/favicon.ico" location="/public/favicon.ico" />
<mvc:resources order="-10" mapping="/robots.txt" location="/public/robots.txt" />
<mvc:resources order="-10" mapping="/humans.txt" location="/public/humans.txt" />
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/**"/>
<bean class="com.my.Interceptor" />
</mvc:interceptor>
</mvc:interceptors>
Because I don't want the interceptor to apply to the resources and there is no way (I think) to specify a path for the mapping which would apply the interceptor to everything except this and that.
So I have to add my own RequestMappingHandlerMapping to be able to specify the interceptor on it, and not globally. Because of this and this, it seems I can't simply define my own RequestMappingHandlerMapping while keeping the <mvc:annotation-driven /> element!
So... With some help, I've been able to get rid of the <mvc:annotation-driven /> element and pretty much everything works well now. I have my interceptor applied on everything but my resources. Everything works well, except the flash scope!
#RequestMapping(value="/test", method=RequestMethod.POST)
public String test(Model model, RedirectAttributes redirectAttrs)
{
redirectAttrs.addFlashAttribute("myKey", "my message");
return "redirect:test2";
}
#RequestMapping(value="/test2")
public String test2(Model model, HttpServletRequest request)
{
Map<String, ?> map = RequestContextUtils.getInputFlashMap(request); // map is NULL
System.out.println(model.containsAttribute("myKey")); // Prints FALSE
}
The flash map is NULL and my model doesn't contain my variable. When I try with the <mvc:annotation-driven /> element it works well! So my question is: what is missing from my context to make the flash scope work?
I also did try to set "org.springframework.web" to a DEBUG logging level, and after the redirect there is nothing logged related to a FlashMap or FlashMapManager. It seems some required bean is definitely missing.
Here are the interesting parts of my context file:
<!-- commented! -->
<!-- <mvc:annotation-driven /> -->
<bean id="baseInterceptor" class="com.my.Interceptor" />
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping">
<property name="order" value="0" />
<property name="interceptors">
<list>
<ref bean="conversionServiceExposingInterceptor" />
<ref bean="baseInterceptor" />
</list>
</property>
</bean>
<bean id="myRequestMappingHandlerAdapter" class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
<property name="webBindingInitializer">
<bean class="org.springframework.web.bind.support.ConfigurableWebBindingInitializer">
<property name="conversionService" ref="conversionService" />
<property name="validator" ref="validator" />
</bean>
</property>
<property name="messageConverters">
<list>
<bean class="org.springframework.http.converter.ByteArrayHttpMessageConverter" />
<bean class="org.springframework.http.converter.StringHttpMessageConverter" />
<bean class="org.springframework.http.converter.FormHttpMessageConverter" />
<bean class="org.springframework.http.converter.xml.SourceHttpMessageConverter" />
</list>
</property>
</bean>
<bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean" />
<bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean" />
<bean id="conversionServiceExposingInterceptor" class="org.springframework.web.servlet.handler.ConversionServiceExposingInterceptor">
<constructor-arg ref="conversionService" />
</bean>
<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="classpath:/messages/messages" />
<property name="defaultEncoding" value="UTF-8" />
</bean>
<bean class="org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver"></bean>
<mvc:resources order="-10" mapping="/public/**" location="/public/" />
<mvc:resources order="-10" mapping="/favicon.ico" location="/public/favicon.ico" />
<mvc:resources order="-10" mapping="/robots.txt" location="/public/robots.txt" />
<mvc:resources order="-10" mapping="/humans.txt" location="/public/humans.txt" />
What is missing for the flash scope to work?
UPDATE : See my answer for the solution... Nothing was missing actually. Only the Session was not working correctly and I found a way to make it work.
I finally found what was missing for the flash scope to work!
In the action where I access the flash variables (on the page the redirect leads to), I have to use this:
public String test2(Model model, HttpServletRequest request, HttpSession session)
instead of this :
public String test2(Model model, HttpServletRequest request)
It seems that this makes the Session to work correctly and therefore makes the flash scope to work correctly too! Why? I don't know...
It looks like all you need to do is to register a flash map manager with a bean name of flashMapManager and it should get automatically initialized and used by your Dispatcher Servlet:
<bean name="flashMapManager" class="org.springframework.web.servlet.support.DefaultFlashMapManager/>

Configuring Spring Security 3.x to have multiple entry points

I have been using Spring Security 3.x for handling user authentication for my projects, and so far, it has worked flawlessly.
I recently received the requirements for a new project. In this project, it requires 2 sets of user authentication: one to authenticate employees against LDAP, and another to authenticate customer against database. I'm a little stumped on how to configure that in Spring Security.
My initial idea was to create a login screen that has the following fields:-
radio button field - for users to choose whether they are employees or customers.
j_username user field.
j_password password field.
If the user selects "employee", then I want Spring Security to authenticate them against LDAP, otherwise the credential will be authenticated against database. However, the problem is the form will be submitted to /j_spring_security_check and there's no way for me to send the radio button field to my implemented custom authentication provider. My initial thought is I probably need two form submission URLs rather than relying on the default /j_spring_security_check. Each URL will be handled by different authentication providers, but I'm not sure how to configure that in Spring Security.
I know in Spring Security, I can configure fall back authentication, for example if LDAP authentication fails, then it will fall back to database authentication, but this is not what I'm shooting for in this new project.
Can someone share how exactly I should configure this in Spring Security 3.x?
Thank you.
UPDATE - 01-28-2011 - #EasyAngel's technique
I'm trying to do the following:-
Employee form login submits to /j_spring_security_check_for_employee
Customer form login submits to /j_spring_security_check_for_customer
The reason I want 2 different form logins is to allow me to handle the authentication differently based on the user, instead of doing a fall-back authentication. It is possible that employee and customer have same user ID, in my case.
I incorporated #EasyAngel's idea, but have to replace some deprecated classes. The problem I'm currently facing is neither filter processes URLS seem registered in Spring Security because I keep getting Error 404: SRVE0190E: File not found: /j_spring_security_check_for_employee. My gut feeling is the springSecurityFilterChain bean is not wired properly, thus my custom filters are not used at all.
By the way, I'm using WebSphere and I do have com.ibm.ws.webcontainer.invokefilterscompatibility=true property set in the server. I'm able to hit the default /j_spring_security_check without problem.
Here's my complete security configuration:-
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:sec="http://www.springframework.org/schema/security" 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.xsd
http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security.xsd">
<sec:http auto-config="true">
<sec:form-login login-page="/login.jsp" authentication-failure-url="/login.jsp?login_error=1" default-target-url="/welcome.jsp"
always-use-default-target="true" />
<sec:logout logout-success-url="/login.jsp" />
<sec:intercept-url pattern="/employee/**" access="ROLE_EMPLOYEE" />
<sec:intercept-url pattern="/customer/**" access="ROLE_CUSTOMER" />
<sec:intercept-url pattern="/**" access="IS_AUTHENTICATED_ANONYMOUSLY" />
</sec:http>
<bean id="springSecurityFilterChain" class="org.springframework.security.web.FilterChainProxy">
<sec:filter-chain-map path-type="ant">
<sec:filter-chain pattern="/**" filters="authenticationProcessingFilterForEmployee, authenticationProcessingFilterForCustomer" />
</sec:filter-chain-map>
</bean>
<bean id="authenticationProcessingFilterForEmployee" class="org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter">
<property name="authenticationManager" ref="authenticationManagerForEmployee" />
<property name="filterProcessesUrl" value="/j_spring_security_check_for_employee" />
</bean>
<bean id="authenticationProcessingFilterForCustomer" class="org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter">
<property name="authenticationManager" ref="authenticationManagerForCustomer" />
<property name="filterProcessesUrl" value="/j_spring_security_check_for_customer" />
</bean>
<bean id="authenticationManagerForEmployee" class="org.springframework.security.authentication.ProviderManager">
<property name="providers">
<list>
<ref bean="employeeCustomAuthenticationProvider" />
</list>
</property>
</bean>
<bean id="authenticationManagerForCustomer" class="org.springframework.security.authentication.ProviderManager">
<property name="providers">
<list>
<ref bean="customerCustomAuthenticationProvider" />
</list>
</property>
</bean>
<bean id="employeeCustomAuthenticationProvider" class="ss.EmployeeCustomAuthenticationProvider">
<property name="userDetailsService">
<bean class="ss.EmployeeUserDetailsService"/>
</property>
</bean>
<bean id="customerCustomAuthenticationProvider" class="ss.CustomerCustomAuthenticationProvider">
<property name="userDetailsService">
<bean class="ss.CustomerUserDetailsService"/>
</property>
</bean>
<sec:authentication-manager>
<sec:authentication-provider ref="employeeCustomAuthenticationProvider" />
<sec:authentication-provider ref="customerCustomAuthenticationProvider" />
</sec:authentication-manager>
</beans>
I'm starting a bounty here because I can't seem to get this working for several days already... frustration is the word. I'm hoping someone will point out the problem(s), or if you can show me a better or cleaner way to handle this (in code).
I'm using Spring Security 3.x.
Thank you.
UPDATE 01-29-2011 - #Ritesh's technique
Okay, I managed to get #Ritesh's approach to work very closely to what I wanted. I have the radiobutton that allows user to select whether they are customer or employee. It seems like this approach is working fairly well, with one problem...
If employee logs in with right credential, they are allowed in... WORK AS EXPECTED.
If employee logs in with wrong credential, they are not allowed in... WORK AS EXPECTED.
If customer logs in with right credential, they are allowed in... WORK AS EXPECTED.
If customer logs in with wrong credential, the authentication falls back to employee authentication... DOESN'T WORK. This is risky because if I select customer authentication, and punch it the employee credential, it will allow the user in too and this is not what I want.
<sec:http auto-config="false" entry-point-ref="loginUrlAuthenticationEntryPoint">
<sec:logout logout-success-url="/login.jsp"/>
<sec:intercept-url pattern="/employee/**" access="ROLE_EMPLOYEE"/>
<sec:intercept-url pattern="/customer/**" access="ROLE_CUSTOMER"/>
<sec:intercept-url pattern="/**" access="IS_AUTHENTICATED_ANONYMOUSLY"/>
<sec:custom-filter position="FORM_LOGIN_FILTER" ref="myAuthenticationFilter"/>
</sec:http>
<bean id="myAuthenticationFilter" class="ss.MyAuthenticationFilter">
<property name="authenticationManager" ref="authenticationManager"/>
<property name="authenticationFailureHandler" ref="failureHandler"/>
<property name="authenticationSuccessHandler" ref="successHandler"/>
</bean>
<bean id="loginUrlAuthenticationEntryPoint"
class="org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint">
<property name="loginFormUrl" value="/login.jsp"/>
</bean>
<bean id="successHandler"
class="org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler">
<property name="defaultTargetUrl" value="/welcome.jsp"/>
<property name="alwaysUseDefaultTargetUrl" value="true"/>
</bean>
<bean id="failureHandler"
class="org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler">
<property name="defaultFailureUrl" value="/login.jsp?login_error=1"/>
</bean>
<bean id="employeeCustomAuthenticationProvider" class="ss.EmployeeCustomAuthenticationProvider">
<property name="userDetailsService">
<bean class="ss.EmployeeUserDetailsService"/>
</property>
</bean>
<bean id="customerCustomAuthenticationProvider" class="ss.CustomerCustomAuthenticationProvider">
<property name="userDetailsService">
<bean class="ss.CustomerUserDetailsService"/>
</property>
</bean>
<sec:authentication-manager alias="authenticationManager">
<sec:authentication-provider ref="customerCustomAuthenticationProvider"/>
<sec:authentication-provider ref="employeeCustomAuthenticationProvider"/>
</sec:authentication-manager>
</beans>
Here's my updated configuration. It has to be some really small tweak I need to do to prevent the authentication fall back but I can't seem to figure it out now.
Thank you.
UPDATE - SOLUTION to #Ritesh's technique
Okay, I think I have solved the problem here. Instead of having EmployeeCustomAuthenticationProvider to rely on the default UsernamePasswordAuthenticationToken, I created EmployeeUsernamePasswordAuthenticationToken for it, just like the one I created CustomerUsernamePasswordAuthenticationToken for CustomerCustomAuthenticationProvider. These providers will then override the supports():-
CustomerCustomAuthenticationProvider class
#Override
public boolean supports(Class<? extends Object> authentication) {
return (CustomerUsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication));
}
EmployeeCustomAuthenticationProvider class
#Override
public boolean supports(Class<? extends Object> authentication) {
return (EmployeeUsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication));
}
MyAuthenticationFilter class
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
...
UsernamePasswordAuthenticationToken authRequest = null;
if ("customer".equals(request.getParameter("radioAuthenticationType"))) {
authRequest = new CustomerUsernamePasswordAuthenticationToken(username, password);
}
else {
authRequest = new EmployeeUsernamePasswordAuthenticationToken(username, password);
}
setDetails(request, authRequest);
return super.getAuthenticationManager().authenticate(authRequest);
}
... and WALAA! It works perfectly now after several days of frustration!
Hopefully, this post will be able to help somebody who is doing the same thing as I am here.
You don't need to create /j_spring_security_check_for_employee and /j_security_check_for_customer filterProcessingUrl.
The default one will work just fine with radio button field idea.
In the custom login LoginFilter, you need to create different tokens for employee and customer.
Here are the steps:
Use default UsernamePasswordAuthenticationToken for employee login.
Create CustomerAuthenticationToken for customer login. Extend AbstractAuthenticationToken so that its class type is distinct from UsernamePasswordAuthenticationToken.
Define a custom login filter:
<security:http>
<security:custom-filter position="FORM_LOGIN_FILTER" ref="customFormLoginFilter" />
</security:http>
In customFormLoginFilter, override attemptAuthentication as follows (pseudo code):
if (radiobutton_param value employee) {
UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, password);
setDetails(whatever);
return getAuthenticationManager().authenticate(authRequest);
} else if (radiobutton_param value customer) {
CustomerAuthenticationToken authRequest = new CustomerAuthenticationToken(username, password);
setDetails(whatever);
return getAuthenticationManager().authenticate(authRequest);
}
Override supports method in EmployeeCustomAuthenticationProvider to support UsernamePasswordAuthenticationToken.
Override supports method in CustomerCustomAuthenticationProvider to support CustomerAuthenticationToken.
#Override
public boolean supports(Class<?> authentication) {
return (CustomerAuthenticationToken.class.isAssignableFrom(authentication));
}
Use both providers in authentication-manager:
<security:authentication-manager alias="authenticationManager">
<security:authentication-provider ref='employeeCustomAuthenticationProvider ' />
<security:authentication-provider ref='customerCustomAuthenticationProvider ' />
</security:authentication-manager>
You can define several AuthenticationProcessingFilter filters. Each of them can have different URL like /j_security_check_for_employee and /j_security_check_for_customer. Here is example of the security application context that demonstrates this idea:
<bean id="myfilterChainProxy" class="org.springframework.security.util.FilterChainProxy">
<security:filter-chain-map pathType="ant">
<security:filter-chain pattern="/**" filters="authenticationProcessingFilterForCustomer, authenticationProcessingFilterForEmployee, ..." />
</security:filter-chain-map>
</bean>
<bean id="authenticationProcessingFilterForCustomer" class="org.springframework.security.web.authentication.AuthenticationProcessingFilter">
<property name="authenticationManager" ref="authenticationManagerForCustomer"/>
<property name="filterProcessesUrl" value="/j_security_check_for_customer"/>
</bean>
<bean id="authenticationProcessingFilterForEmployee" class="org.springframework.security.web.authentication.AuthenticationProcessingFilter">
<property name="authenticationManager" ref="authenticationManagerForEmployee"/>
<property name="filterProcessesUrl" value="/j_security_check_for_employee"/>
</bean>
<bean id="authenticationManagerForCustomer" class="org.springframework.security.authentication.ProviderManager">
<property name="providers">
<list>
<bean class="org.acegisecurity.providers.dao.DaoAuthenticationProvider">
<property name="userDetailsService">
<ref bean="customerUserDetailsServiceThatUsesDB"/>
</property>
</bean>
</list>
</property>
</bean>
<bean id="authenticationManagerForEmployee" class="org.springframework.security.authentication.ProviderManager">
<property name="providers">
<list>
<bean class="org.springframework.security.authentication.dao.DaoAuthenticationProvider">
<property name="userDetailsService">
<ref bean="employeeUserDetailsServiceThatUsesLDAP"/>
</property>
</bean>
</list>
</property>
</bean>
As you can see, in this scenario you have also different UserDetailServices - for DB auth and LDAP.
I think it's good idea to have different auth URLs for customers and employee (especially if they use different authentication strategies). You can even have different login pages for them.
For Java Configuration reference
As i keen to write here java configuration way of implementing the same technique to help people who is not familiar with xml configuration but i don't want to hijack this thread beauty with such a long answer of java configuration code.
People who wants to achieve the same with java configuration(Annotation based) can refer my self answered question link is given below and also you can find my github repository link for the code in the answer.
For Annotation based configuration code refer my answer here
Multiple AuthenticationProvider with different UsernamePasswordAuthToken to authenticate different login forms without fallback authentication
You can store this information in DB. For example you can have column called ldap_auth in Users table. You can look at my other answer (as an example):
Spring login form example
If you carefully look at UserService class, you will notice, that I actually test this LDAP flag and take user password either from LDAP or database.
it's me again :) Can you try to use filters like this:
<sec:http auto-config="true">
...
<sec:custom-filter ref="authenticationProcessingFilterForCustomer" after="FIRST"/>
<sec:custom-filter ref="authenticationProcessingFilterForEmployee" after="FIRST"/>
</sec:http>
instead of defining bean springSecurityFilterChain.

Categories

Resources