Remember Me using Spring 3.1 not working over HTTP sessions - java

I'm trying to implement the Remember Me functionality that is part of Spring 3.1 to allow customers to automatically log in when they have previously selected that option in the login form. Here is my actual implementation:
In spring-security-config.xml:
<security:http auto-config="false" entry-point-ref="myEntryPoint" request-matcher="regex" disable-url-rewriting="true">
...
<security:remember-me key="mykey" authentication-success-handler-ref="rememberMeAuthenticationSuccessHandler"/>
</security:http>
<security:authentication-manager alias="authenticationManager">
<security:authentication-provider ref="acceleratorAuthenticationProvider" />
<security:authentication-provider ref="rememberMeAuthenticationProvider"/>
</security:authentication-manager>
<bean id="rememberMeAuthenticationSuccessHandler" class="uk.co.portaltech.qlaccelerator.storefront.security.RememberMeAuthenticationSuccessHandler" scope="tenant">
<property name="myCookieStrategy" ref="myCookieStrategy" />
<property name="customerFacade" ref="customerFacade" />
</bean>
<bean id="rememberMeAuthenticationProvider" class="org.springframework.security.authentication.RememberMeAuthenticationProvider">
<property name="key" value="myKey" />
</bean>
My login.jsp contains the spring rememeber me checkbox:
<form:checkbox id="_spring_security_remember_me" class="rememberMe" path="_spring_security_remember_me" />
When I access the site the first time (over HTTP session) it doesn't log me in automatically but as soon as I click on the login button (over HTTPS session) it automatically logs me in.
Is this the way it is supposed to work or am I missing something in the configuration to let Spring log me in when I access the site?

remember me lets the app remember the user across sessions. meaning, if the server bounces or if the user closed his browser and reopened it. in these cases, the user will not be asked again for his credentials.
in your case that you describe, the user (you) enter his credentials, and only then logs in? what is "automatically" means?
htlpful links:
remember me result is ignored by spring security, and i am still redirected to the login page
Configuring remember-me in spring security

Check if the remember-me cookie is flagged as "secure" (look in your browser's cookie list). If so, it won't be sent over HTTP connections, which would explain what you see.
The default is to create a secure cookie if the request is over HTTPS. You can change this using the useSecureCookie property of the RememberMeServices implementation you are using.

Related

Integration testing with ActiveDirectoryLdapAuthenticationProvider

Last time I've added to our project one more authentication provider in order to authenticate user through windows active directory server:
<security:authentication-manager id="authenticationManager" erase-credentials="true">
<security:authentication-provider ref="ldapActiveDirectoryAuthProvider" />
<security:authentication-provider ref="authenticationProvider1"/>
<security:authentication-provider ref="authenticationProvider2"/>
</security:authentication-manager>
<bean id="customLdapUserDetailsMapper" class="security.authentication.customLdapUserDetailsMapper">
</bean>
<bean id="ldapActiveDirectoryAuthProvider" class="org.springframework.security.ldap.authentication.ad.ActiveDirectoryLdapAuthenticationProvider">
<constructor-arg value="my.domain"/>
<constructor-arg value="ldap://my.custom.host:389" />
<property name="useAuthenticationRequestCredentials" value="true" />
<property name="convertSubErrorCodesToExceptions" value="true" />
<property name="userDetailsContextMapper" ref="customLdapUserDetailsMapper" />
</bean>
Alsmost work fine except existing integration tests that work with authentication flow. Namely each test tried to connect to server when ActiveDirectoryLdapAuthenticationProvider.bindAsUser then failed because my.custom.host is unavaible for this type of test.
I've started googling in order to find some mock for this type of test, but unfortunatly I found only this post Integration tests with spring-security and ldap where Luke Taylor recommended use existing integration tests as a guide. I've took a look into it but it doesn't contain any tests for this type of provider.
I'm new in such stuff and would be good to know the following things:
Will be it correct to reuse in any manner this approach with new ApacheDSContainer("dc=springframework,dc=org", "classpath:test-server.ldif"); that was mentioned in LDAP integration test(I am not sure wheter it suites to me because I didn't create ldap ebbedded ldap server in my application context and didn't specify any .ldif files in mentioned configuration as well).
In which way the following provider can be mocked in proper way?
Actually you just have to provide another configuration which will be loaded for Testing purposes. There you can define a different Authentication Provider, which for example just can authenticate everyone.... Or just simply deactivate Authentication at all.
Since you don't want to test the functionallity provided by spring.

Spring security authorization without authentication

I have a Java JSF 2, Spring 3, Hibernate 4 Java EE Application which uses a third party library to authenticate the users. I imported the required CA certs into my JVM, added the third library to the project and configured in web.xml. The library reads the users details from smart card. This whole setup is working and users are taken to the home page by the third party library.
Here are my requirements to secure the application.
Check one more time if the user exist in the application specific database
Get the roles of that user from the application database
Protect my JSF pages
Protect my application services
I looked at this link and it seems "AuthenticationProcessingFilter" is deprecated and not applicable for Spring 3!
http://codersatwork.wordpress.com/2010/02/13/use-spring-security-for-authorization-only-not-for-authentication/
I also looked this one but I did not understand what other steps/configuration is needed.
spring-security: authorization without authentication
I would really appreciate if someone can outline what are all the items I need to implement Spring Security with Authorization only. This is what I came up with.
1) Update pom with spring 3 security, add a filter (which filter I should pick)
2) Custom User Detail
3) Custom DaoAuthenticationProvider
4) register this custom authentication provider in application-context.xml
5) register access decision managers for authorization
The base Spring Security classes suited for this use-case are org.springframework.security.web.authentication.preauth.AbstractPreAuthenticatedProcessingFilter and org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationProvider.
In case your current authentication library results in the user being authenticated in the standard Java EE way (i.e. calls to getUserPrincipal() on HttpServletRequest instance return the authenticated user's Principal) the things you need to do should be similar to:
Implement interface org.springframework.security.core.userdetails.UserDetailsService which checks that the user exists in your application database and throws UsernameNotFoundException if it doesn't
Add the following settings for the Spring Security:
<!-- Declare the user details for database check -->
<bean id="userDetails" class="com.yourpackage.DatabaseUserDetails"/>
<!-- Default empty auth manager -->
<security:authentication-manager alias="authenticationManager"/>
<!-- Use default settings from the jee namespace -->
<security:http>
<security:jee mappable-roles="IS_AUTHENTICATED_FULLY" user-service-ref="userDetails"/>
</security:http>
Configure your Spring Security to perform authorization based on your requirements
The security:jee initializes both a filter and authentication provider and plugs your user-service to the provider.
In case your current authentication library doesn't use Java EE mechanisms, you will need to implement your own subclass of the AbstractPreAuthenticatedProcessingFilter which knows how to recognize that the user has authenticated.
You would then replace the default pre-auth filter with your own, so the configuration would look like:
<!-- Declare the user details for database check -->
<bean id="userDetails" class="com.yourpackage.DatabaseUserDetails"/>
<!-- Define provider -->
<bean id="preauthAuthProvider" class="org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationProvider">
<property name="preAuthenticatedUserDetailsService">
<bean id="userDetailsServiceWrapper"
class="org.springframework.security.core.userdetails.UserDetailsByNameServiceWrapper">
<property name="userDetailsService" ref="userDetails"/>
</bean>
</property>
</bean>
<!-- Define alias for the authentication manager -->
<authentication-manager alias="authenticationManager">
<security:authentication-provider ref="preauthAuthProvider" />
</authentication-manager>
<!-- Declare the custom filter -->
<bean id="authenticationFilter" class="com.yourpackage.AuthenticationFilter">
<property name="authenticationManager" ref="authenticationManager"/>
</bean>
<security:http>
<security:custom-filter ref="authenticationFilter" position="PRE_AUTH_FILTER"/>
</security:http>
You can find some more details in Spring Security documentation.

Implementing CAS with Spring Security 3

I currently have spring security configured and working correctly. I want to get CAS working so I can have a single sign on across multiple apps I've written. I am confused how I can make cas use my custom userdetailService.
Currently I have this is my spring-security.xml
<authentication-manager alias="authManager">
<authentication-provider user-service-ref="userDetailsService">
<password-encoder ref="passwordEncoder">
<salt-source ref="saltSource"/>
</password-encoder>
</authentication-provider>
</authetication-manager>
From all the cas examples I have found they say to do implement the manage this way:
<beans:bean id="casAuthenticationProvider" class="org.springframework.security.cas.authentication.CasAuthenticationProvider">
<beans:property name="authenticationUserDetailsService">
<beans:bean class="org.springframework.security.core.userdetails.UserDetailsByNameServiceWrapper">
<beans:constructor-arg ref="userDetailsService"/>
</beans:bean>
</beans:property>
<beans:property name="serviceProperties" ref="serviceProperties"/>
<beans:property name="ticketValidator">
<beans:bean class="org.jasig.cas.client.validation.Cas20ServiceTicketValidator">
<beans:constructor-arg index="0" value="https://localhost:8443/cas"/>
</beans:bean>
</beans:property>
<beans:property name="key" value="1234554321"/>
</beans:bean>
<authentication-manager alias="authManager">
<authentication-provider ref="casAuthenticationProvider"/>
</authentication-manager>
The documentation is confusing. How do I go from a working spring-security app to one that implements cas and still use my custom user details? Also what do I need to change on the jsp pages? Any help would be much appreciated.
Thanks
I think you want CAS to authenticate the password using your own password+salt encoder.
Unfortunately, it is not a straight forward configuration and the configuration is not in your Spring apps.
You need to recompile CAS to include your custom password+salt encoder.
Thus, when Spring calls CAS for authentication, the same custom password+salt encoder will be used.
Fortunately, CAS team has created WAR Overlay approach so that it is easy for the user to recompile CAS server in order to include custom password+salt encoders
The documentation is here
https://wiki.jasig.org/display/CASUM/Best+Practice+-+Setting+Up+CAS+Locally+using+the+Maven2+WAR+Overlay+Method
You need to be very patient to follow the steps and make sure that your system has Maven2
You need not to download any library as Maven will take care of that.
The basic idea of WAR Overlay approach is to create a maven controlled folder where you can create subfolders to add your custom java libraries.
Maven will used to recompiled the custom java code together with the CAS files to produce a WAR file where you can publish it to a SSL server.
Just make sure that both CAS and your Spring Apps are using SSL.
Good luck!
Here are the steps I would recommend when setting up a CAS infrastructure
First of all, you should be aware of what CAS is, and how it works. Check out this article and the jasig-webpage.
Then download the examples from Spring Source, make the cas-sample run, and play with it to get a better feeling of it. (I'm not sure whether there is a readme file or you get infos on how to use it on the spring source webpage, but there is definitely info out there)
Make your app authenticate against this simple CAS-Server (find config examples on the CAS webpage)
Setup and configure your own CAS-Server that uses your current authentication system to authorize a user.
you may use the SAML protocol to transfer roles etc from the CAS to the client app after authentication
to apply the roles at the client app you may need to implement that on your own.
Adapt other apps to use the CAS-Server

What is the recommended way to store user credentials in spring MVC?

I am creating a Spring MVC application which is a SOAP client. To communicate with SOAP web-service I am suppose to pass the login credentials. My application doesn't need to store any details dynamically and hence I am not using any db for this application. So kindly suggest a recommended practice to store the sensitive credential for my application. This credential will we managed by the system admin and must be easy for him to change according to the requirement.
Thanks in advance.
Store the username and password in a properties file external to your webapp spring context. That way the sysadmin can easily lock down read access on the properties file to the relevant parties (e.g. your application and himself). That should stop prying eyes seeing the password.
In your spring context have something like:
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location">
<list>
<value>/path/to/config.properties</value>
</list>
</property>
<property name="ignoreUnresolvablePlaceholders" value="true"/>
</bean>
<bean id="myBean" class="...">
<property name="username" value="{usernameFromExternalPropFile}" />
<property name="password" value="{passwordFromExternalPropFile}" />
</bean>
The sysadmin will then also be able to change the username/password independently from a build.
See http://www.javaworld.com/community/node/8309/
The simplest option would be to store them in your application context XML configuration file as properties to the bean which is communicating with the SOAP webservice.

Disable Remember-Me in Spring Security & Tomcat

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

Categories