Remember-me- spring security - spring-security

I am currently trying to implement remember me functionality in my website. Following is part of my configuration
<security:remember-me services-ref="rememberMeServices" />
<bean id="rememberMeServices" class="com.entertainment.ecom.web.auth.EcomRemembe rMeServices">
<property name="userDetailsService" ref="ecomUserDetailsService"/>
<property name="key" value="a23eef6dfd1514cb885f47070380ff18"/>
<property name="cookieName" value="ENTC"/>
<property name="tokenValiditySeconds" value="80000"/>
</bean>
My EcomRememberMeServices extends AbstractRememberMeServices & I have overridden onLoginFail & onLoginSuccess methods. My question is, from where my onLoginSuccess() method will be called?
I have tried to run above configuration & it was seen that onLoginFail gets called through RememberMeAuthenticationFilter(rememberMeServices.loginFail(request, response)) but when I checked source code for this filter, I could not find any call for onLoginSuccess() or loginSuccess() method. So do I need to call this explicitly?
In BasicAuthenticationFilter, there is a call for this method. So I tried to use it but still i does not work.(<http-basic/>). So can anyone please help me in this?

There is one more method logout(), which is called by logout filter. I guess you have to inject rememberMeServices into Login and Logout Filter as well (I am not sure if it can be done within http element in xml):
<bean id="logoutFilter" class="org.springframework.security.web.authentication.logout.LogoutFilter">
<constructor-arg index="0" type="org.springframework.security.web.authentication.logout.LogoutSuccessHandler" ref="logoutSuccessHandler" />
<constructor-arg index="1">
<list value-type="org.springframework.security.web.authentication.logout.LogoutHandler">
<ref local="rememberMeServices"/>
</list>
</constructor-arg>
</bean>
and
<bean id="formLoginFilter" class="org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter">
...
<property name="rememberMeServices">
<ref local="rememberMeServices" />
</property>
</bean>

Related

CAS attributes in wsfederation not being forwarded to CAS client

I am implementing an authentication system for a Tomcat web application that gets authenticated against ADFS using CAS. I am using unicon's CAS server with ADFS integration.
I have reached to the state where I can see that the required attributes reach the CAS server. But these attributes are not getting forwarded to the client. check the figure below:
In the above image, the attribute map is empty after authentication. Also, when the client application validates the ticket, the attribute map is empty. Ref picture below:
After getting authenticated, the attributes are visible in the logs, but they are not being loaded into attribute Map.
The deployerConfigContext.xml is as follows. The attributeRepository bean and allowed attributes property in serviceRegistryDao bean are the probably the main focus areas.
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:sec="http://www.springframework.org/schema/security"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.1.xsd">
<bean id="authenticationManager"
class="org.jasig.cas.authentication.AuthenticationManagerImpl">
<property name="authenticationMetaDataPopulators">
<list>
<bean class="net.unicon.cas.support.wsfederation.authentication.WsFederationAuthenticationMetaDataPopulator" />
</list>
</property>
<property name="credentialsToPrincipalResolvers">
<list>
<bean class="net.unicon.cas.support.wsfederation.authentication.principal.WsFederationCredentialsToPrincipalResolver">
<property name="configuration" ref="wsFedConfig" />
</bean>
<bean class="org.jasig.cas.authentication.principal.UsernamePasswordCredentialsToPrincipalResolver" >
<property name="attributeRepository" ref="attributeRepository" />
</bean>
<bean class="org.jasig.cas.authentication.principal.HttpBasedServiceCredentialsToPrincipalResolver" />
</list>
</property>
<property name="authenticationHandlers">
<list>
<bean class="net.unicon.cas.support.wsfederation.authentication.handler.support.WsFederationAuthenticationHandler" />
<bean class="org.jasig.cas.authentication.handler.support.HttpBasedServiceCredentialsAuthenticationHandler"
p:httpClient-ref="httpClient" />
</list>
</property>
</bean>
<sec:user-service id="userDetailsService">
<sec:user name="##THIS SHOULD BE REPLACED##" password="notused" authorities="ROLE_ADMIN" />
</sec:user-service>
<bean id="attributeRepository"
class="org.jasig.services.persondir.support.StubPersonAttributeDao">
<property name="backingMap">
<map>
<entry key="emailaddress" value="upn" />
<!--<entry key="FirstName" value="username" />-->
<entry key="name" value="LastName" />
<entry key="costcent" value="costcent" />
<entry key="title" value="FirstName" />
</map>
</property>
</bean>
<bean
id="serviceRegistryDao"
class="org.jasig.cas.services.InMemoryServiceRegistryDaoImpl">
<property name="registeredServices">
<list>
<bean class="org.jasig.cas.services.RegexRegisteredService">
<property name="id" value="0" />
<property name="name" value="HTTP and IMAP" />
<property name="description" value="Allows HTTP(S) and IMAP(S) protocols" />
<property name="serviceId" value="^(https?|imaps?)://.*" />
<property name="evaluationOrder" value="10000001" />
<property name="allowedAttributes">
<list>
<value>upn</value>
<value>Department</value>
<value>costcent</value>
<value>LastName</value>
<value>FirstName</value>
<value>name</value>
<value>emailaddress</value>
<value>title</value>
<value>SAM-Account-Name</value>
</list>
</property>
</bean>
</list>
</property>
</bean>
<bean id="auditTrailManager" class="com.github.inspektr.audit.support.Slf4jLoggingAuditTrailManager" />
<bean id="healthCheckMonitor" class="org.jasig.cas.monitor.HealthCheckMonitor">
<property name="monitors">
<list>
<bean class="org.jasig.cas.monitor.MemoryMonitor"
p:freeMemoryWarnThreshold="10" />
<bean class="org.jasig.cas.monitor.SessionMonitor"
p:ticketRegistry-ref="ticketRegistry"
p:serviceTicketCountWarnThreshold="5000"
p:sessionCountWarnThreshold="100000" />
</list>
</property>
</bean>
</beans>
The rest of the at CAS server is same as in the sample implementation of unicon's CAS-server implementation here
I've tried a lot of combinations in the mentioned beans. Being new to Spring I could not understand how to load the credentials in the attributeMap. Kindly guide me in forwarding the attributes sent by CAS server during authentication to the client application.
It looks like the WsFederationCredentialsToPrincipalResolver only extracts the principal id from the collection of attributes received, and ignores other attributes. So you only get the identity attribute defined in your configuration. You could for the time being, connect that resolver to your attribute repository and have it consume and retrieve attributes from there.
Note that CAS 4.2 supports and fixes this behavior and has built-in support for the ADFS integration. Your other option would be to extend WsFederationCredentialsToPrincipalResolver and have it process attributes and stuff them into the final principal created there by overriding the appropriate method.

Spring security authentication using ldap based on memberOf attribute

I'm using spring authentication against ldap. If the provided user id and password exists in ldap, then I was able to get the user login. I would like to restrict this based on the user's memberOf attribute in the LDAP. If the user has memberOf attribute with a specific CN value (CN=adminaccess or CN=superadminaccess), then authentication/authorization should pass.Else authentication/authorization should fail.
<security:http auto-config="true" use-expressions="true" access-denied-page="/admin/auth/denied">
<security:intercept-url pattern="/admin/auth/login" access="permitAll" />
<security:intercept-url pattern="/admin/dashboard/*" access="hasAnyRole('ROLE_ADMINACCESS','ROLE_SUPERADMINACCESS')"/>
</security:http>
<security:authentication-manager>
<security:ldap-authentication-provider user-dn-pattern="CN={0},CN=Users" group-search-base="CN=adminaccess,CN=Users" />
</security:authentication-manager>
<bean id="ldapContext"
class="org.springframework.security.ldap.DefaultSpringSecurityContextSource">
<constructor-arg value="ldap://xxx.ds.yyy.com:389/DC=xxx,DC=ds,DC=yyy,DC=com"/>
<property name="userDn" value="CN=aaa,CN=Users,DC=xxx,DC=ds,DC=yyy,DC=com"/>
<property name="password" value="thepassword"/>
</bean>
I always go to the Access Denied page with my above configuration. If I remove the access="hasAnyRole('ROLE_ADMINACCESS','ROLE_SUPERADMINACCESS')" from the security:intercept-url, I'm able to always access with valid user/password, even if the user is not part of adminaccess (which I was hoping would be restricted because my group -search-base had specified CN=adminaccess).
Wondering what the configuration should be:
To restrict access to just users who are memberOf CN=adminaccess and/or CN=superadminaccess
Specify correct group-search-base. If I specify only CN=Users, I'm getting a timeout as this is going against our corporate ldap. When I looked up users on LDAP browser, I couldnt find a "ou" that couldhelp. With my above configuration group-search-base="CN=adminaccess,CN=Users", I dont get a timeout, but I dont think it is correct either
Not sure if there is a better way, but I was able to successfully get this working using DefaultLdapAuthoritiesPopulator and updating to the below configuration:
<security:http auto-config="true" use-expressions="true" access-denied-page="/admin/auth/denied">
<security:intercept-url pattern="/admin/auth/login" access="permitAll" />
<security:intercept-url pattern="/admin/dashboard/*" access="hasAnyRole('ROLE_ADMINACCESS','ROLE_SUPERADMINACCESS')"/>
</security:http>
<security:authentication-manager>
<security:authentication-provider
ref="ldapAuthProvider"></security:authentication-provider>
</security:authentication-manager>
<bean id="ldapContext"
class="org.springframework.security.ldap.DefaultSpringSecurityContextSource">
<constructor-arg value="ldap://xxx.ds.yyy.com:389/DC=xxx,DC=ds,DC=yyy,DC=com"/>
<property name="userDn" value="CN=aaa,CN=Users,DC=xxx,DC=ds,DC=yyy,DC=com"/>
<property name="password" value="thepassword"/>
</bean>
<bean id="ldapAuthProvider"
class="org.springframework.security.ldap.authentication.LdapAuthenticationProvider">
<constructor-arg>
<bean
class="org.springframework.security.ldap.authentication.BindAuthenticator">
<constructor-arg ref="ldapContext" />
<property name="userDnPatterns">
<list>
<value>CN={0},CN=Users</value>
</list>
</property>
</bean>
</constructor-arg>
<constructor-arg>
<bean
class="org.springframework.security.ldap.userdetails.DefaultLdapAuthoritiesPopulator">
<constructor-arg ref="ldapContext" />
<constructor-arg value="CN=Users" />
<property name="groupRoleAttribute" value="CN" />
</bean>
</constructor-arg>
</bean>
With this configuration, if the login username/password provided is correct, all the groups that the user is "memberOf" (pattern CN=Users,DC=xxx,DC=ds,DC=yyy,DC=com), get loaded as his "roles" (prefixed with ROLE_) and I'm able to manage access to these roles using security:intercept-url

Spring WS "The security token could not be authenticated or authorized"

I'm creating a java client consumer for a web service using SpringWS-Security.
My Request SOAP (That I use in SOAP UI)
<soapenv:Envelope
xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:sch="http://myws.mycompany.com/myws/schema">
<soapenv:Header>
<wsse:Security soapenv:mustUnderstand="1"
xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">
<wsse:UsernameToken xmlns:wsu="http://schemas.xmlsoap.org/ws/2003/06/utility">
<wsse:Username>myUsernameString</wsse:Username>
<wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText">123</wsse:Password>
</wsse:UsernameToken>
</wsse:Security>
</soapenv:Header>
<soapenv:Body>
<sch:GetUserDetails idSender="5"/>
</soapenv:Body>
</soapenv:Envelope>
My servlet.xml in the WS.
<bean name="endpointMapping"
class="org.springframework.ws.server.endpoint.mapping.PayloadRootQNameEndpointMapping">
<property name="interceptors">
<list>
<ref local="wsSecurityInterceptor" />
</list>
</property>
<bean id="wsSecurityInterceptor"
class="org.springframework.ws.soap.security.wss4j.Wss4jSecurityInterceptor">
<property name="validationActions" value="UsernameToken" />
<property name="validationCallbackHandler" ref="springSecurityCallbackHandler" />
</bean>
<bean id="springSecurityCallbackHandler"
class="org.springframework.ws.soap.security.wss4j.callback.SpringPlainTextPasswordValidationCallbackHandler">
<property name="authenticationManager" ref="authenticationManager"/>
</bean>
<bean id="authenticationProvider" class="ws.security.CustomAuthenticationProviderImpl">
<property name="userCommonService" ref="userCommonService" />
<security:custom-authentication-provider/>
</bean>
<security:authentication-manager alias="authenticationManager" />.
In my Java Client - applicationContext.xml
<bean name="webserviceTemplate" class="org.springframework.ws.client.core.WebServiceTemplate">
<property name="defaultUri" value="http:/localhost:8080/myws-ws/" />
<property name="marshaller" ref="marshaller" />
<property name="unmarshaller" ref="unmarshaller" />
<property name="interceptors">
<list>
<ref local="wsSecurityInterceptor" />
</list>
</property>
</bean>
<oxm:jaxb2-marshaller id="marshaller"
contextPath="org.example.bean.schema" />
<oxm:jaxb2-marshaller id="unmarshaller"
contextPath="org.example.org.bean.schema" />
<bean id="client" class="example.client.impl.EfactClientImpl">
<property name="webServiceTemplate" ref="webserviceTemplate" />
</bean>
<bean id="wsSecurityInterceptor" class="org.springframework.ws.soap.security.wss4j.Wss4jSecurityInterceptor">
<property name="securementActions" value="UsernameToken"/>
</bean>
When I use SOAP UI to consume the service everything is going fine, I think I need a little help at the Java Client and its context because when I run it I got this error:
The security token could not be authenticated or authorized; nested exception is:
javax.security.auth.callback.UnsupportedCallbackException; nested exception is org.apache.ws.security.WSSecurityException: The security token could not be authenticated or authorized; nested exception is:
javax.security.auth.callback.UnsupportedCallbackException
When I debug my app I can notice that this element is crashing:
GetUserRequest request = new GetUserRequest();
request.setIdentifier(user.getIdentifier());
request.setPassword(user.getPassword());
GetUserResponse response = new GetUserResponse();
/* Crashing here. */
response = (GetUserResponse) getWebServiceTemplate().marshalSendAndReceive(request);
FYI: I always see this list of users in SpringWS with security, but what if I have a lot of users trying to access.
WS - [servlet-name]-servlet.xml
<bean id="callbackHandler" class="org.springframework.ws.soap.security.wss4j.callback.SimplePasswordValidationCallbackHandler">
<property name="users">
<props>
<prop key="Bert">Ernie</prop>
<prop key="Mickey">Mouse</prop>
</props>
</property>
</bean>
How can I resolve this UnsupportedCallbackException Exception?
You must specify SecurementUsername and SecurementPassword at call time. This is a programmatically example:
WebServiceTemplate webServiceTemplate = new WebServiceTemplate();
webServiceTemplate.setDefaultUri(uri);
Wss4jSecurityInterceptor interceptor = new Wss4jSecurityInterceptor();
interceptor.setSecurementActions(securementActions);
interceptor.setSecurementMustUnderstand(true);
interceptor.setSecurementUsername(usuario);
interceptor.setSecurementPassword(contrasena);
webServiceTemplate.setInterceptors(new ClientInterceptor[] {interceptor});
I was getting this error when I upgraded from cfx 2.2.X to 2.7.X. Due to feature upgrades, the server side code was not able to read the password as a result the password was received as null by the server. Make sure the server received the correct username and password, which would fix this issue.

Transforming spring-ws implementation to spring-integration-ws implementation

I have an implementation of web service (server side) using spring-ws. I would like to change my code to use spring-integration-ws (ws:inbound-gateway and channels). I have tried examples but still not sure if it is possible to transform my implementation. In short my I am using #Endpoint, #PayloadRoot, PayloadRootAnnotationMethodEndpointMapping and JMS (as transport). Please find below my implementation:
The endpoint class (MyEndpoint.java):
#Endpoint
public class MyEndpoint {
#PayloadRoot(localPart="getUserRequest", namespace="http://play.zahid.springint/Jibx")
public GetUserResponse getUserResponse(GetUserRequest request){
log.info("Start getUserResponse " + request);
GetUserResponse response = new GetUserResponse();
User user = new User();
user.setFirstName(request.getFirstName());
user.setLastName(request.getFirstName() + " Last");
response.setUser(user);
log.info("End getUserResponse " + response);
return response;
}
#PayloadRoot(localPart="sayHiUserRequest", namespace="http://play.zahid.springint/Jibx")
public SayHiResponse sayHiUserResponse(SayHiUserRequest request){
log.info("Start sayHiUserResponse " + request);
SayHiUserResponse response = new SayHiUserResponse();
response.setResponse("Hi " + request.getFirstName() + " " + request.getLastName());
log.info("End sayHiUserResponse " + response);
return response;
}
}
The spring xml file (applicationContext.xml):
<bean id="listenerContainer"
class="org.springframework.jms.listener.DefaultMessageListenerContainer">
<property name="connectionFactory" ref="mqCachedConnectionFactory" />
<property name="destination" ref="defaultDestination" />
<property name="messageListener">
<bean class="org.springframework.ws.transport.jms.WebServiceMessageListener">
<property name="messageFactory" ref="messageFactory"/>
<property name="messageReceiver" ref="messageReceiver" />
</bean>
</property>
<property name="concurrentConsumers" value="1" />
<property name="acceptMessagesWhileStopping" value="false" />
<property name="recoveryInterval" value="10000" />
<property name="cacheLevelName" value="CACHE_CONSUMER" />
</bean>
<bean id="messageFactory" class="org.springframework.ws.soap.saaj.SaajSoapMessageFactory" />
<bean id="messageReceiver" class="org.springframework.ws.soap.server.SoapMessageDispatcher">
<property name="endpointAdapters">
<list>
<bean id="endpointAdapter" class="org.springframework.ws.server.endpoint.adapter.GenericMarshallingMethodEndpointAdapter">
<constructor-arg ref="marshaller" />
</bean>
</list>
</property>
</bean>
<bean class="org.springframework.ws.server.endpoint.mapping.PayloadRootAnnotationMethodEndpointMapping" />
For simplicity purpose I have removed the unnecessary codes and xml configuration.
Is there anyway to keep my endpoint class (MyEndpoint.java) as it is and use spring-integration-ws support (ws:inbound-gateway and channel)?
Let me know if you need any more information.
Thanks
Is there anyway to keep my endpoint class (MyEndpoint.java) as it is and use spring-integration-ws support (ws:inbound-gateway and channel)?
Yes you can.
I'll try to explain a simple integration-ws implementation for your situation:
applicationContext.xml:
<bean id="endpointMappings"
class="org.springframework.beans.factory.config.ListFactoryBean"
lazy-init="true">
<property name="sourceList">
<list>
<ref bean="uriEndpointMapping"/>
</list>
</property>
</bean>
<bean id="uriEndpointMapping"
class="org.springframework.ws.server.endpoint.mapping.UriEndpointMapping"
p:defaultEndpoint-ref="ws-inbound-gateway">
<property name="mappings">
<props>
<prop key="${yourEndPointUrl}">ws-inbound-gateway</prop>
</props>
</property>
</bean>
<int-ws:inbound-gateway id="ws-inbound-gateway"
request-channel="ws-request-channel"
reply-channel="ws-response-channel"
error-channel="ws-error-channel"
marshaller="marshaller"
unmarshaller="marshaller"/>
<int:channel id="ws-request-channel"/>
<int:channel id="ws-response-channel"/>
<int:channel id="ws-error-channel"/>
<int:chain input-channel="ws-request-channel" output-channel="ws-response-channel">
<int:service-activator ref="yourBean" method="getUserResponse"/>
</int:chain>
There are some points here.
You need to define a bean, MyEndpoint type, I named it yourBean here.
yourEndPointUrl defines your end point URL for getUserResponse method.
I've defined service-activator inside a chain, you can add logging or another thing inside this chain to enrich your handling mechanism.
You also need to have a router for routing your requests in to different methods of your bean.

How/where can I manage Authentication at SecurityContext in pre-authentation Scenario

I wonder how/where can I manage Authentication at SecurityContext in pre-authentation Scenario.
I am using spring security 2.x to implement pre-authentation Scenario in my project. now, it patially work.
After user login by pre-authentation process, they can be authrozied with relevant roles, and are able to acecess resources which defined in security:filter.
e.g.
<security:filter-invocation-definition-source lowercase-comparisons="true" path-type="ant">
<security:intercept-url pattern="/resource/**" access="ROLE_ADMIN" />
In a some controller, I want to check principal in security content.
public abstract class AbstractUserAuthenticationController extends AbstractController
{
protected boolean isAuthenticated(String userName)
{
Object obj = SecurityContextHolder.getContext().getAuthentication().getPrincipal(); // where issue come up
But SecurityContextHolder.getContext().getAuthentication() always return null.
In addition, I also can not use secuiry tag in jsp to check if user has relative roles
<security:authorize ifNotGranted="ROLE_ADMIN">
no role found
</security:authorize>
Below shows the "filterChainProxy" I am using.
<bean id="filterChainProxy" class="org.springframework.security.util.FilterChainProxy">
<property name="filterInvocationDefinitionSource">
<value>
CONVERT_URL_TO_LOWERCASE_BEFORE_COMPARISON
PATTERN_TYPE_APACHE_ANT
/*subscri*=httpSessionContextIntegrationFilter,logoutFilter,j2eePreAuthenticatedProcessingFilter,securityContextHolderAwareRequestFilter,subscribeExceptionTranslationFilter,filterInvocationInterceptor
/**=httpSessionContextIntegrationFilter,logoutFilter,j2eePreAuthenticatedProcessingFilter,logoutFilter,rememberMeProcessingFilter,exceptionTranslationFilter,filterSecurityInterceptor
</value>
</property>
</bean>
<bean id="preAuthenticatedAuthenticationProvider" class="org.springframework.security.providers.preauth.PreAuthenticatedAuthenticationProvider">
<property name="preAuthenticatedUserDetailsService" ref="preAuthenticatedUserDetailsService" />
</bean>
<bean id="preAuthenticatedUserDetailsService" class="demo.project.security.auth.RsaAuthenticationUserDetailsService" >
<property name="userService" ref="userService" />
</bean>
<bean id="j2eePreAuthFilter" class="demo.project.security.filter.AutoLoginFilter">
<property name="authenticationManager" ref="authenticationManager" />
<property name="userService" ref="userService" />
</bean>
I think I need to set Authentication to SecurityContext in somewhere, But I do not know where/where.
What I am missing? Can anyone provide me some clues?
Thanks!
Ian
You should use SecurityContextHolder.setContext method to store your SecurityContext prior to getting it back.
The simplest way for doing this is just SecurityContextHolder.setContext(new SecurityContextImpl()).

Resources