Spring Security session concurrency - spring

I have an app build with Spring 4.0 and Security 3.2 and I want to implement session concurrency but it does not seems to work. All other aspects of security are working just fine. Here are my xml configs:
first of all in my web.xml:
<listener>
<listener-class>
org.springframework.security.web.session.HttpSessionEventPublisher
</listener-class>
</listener>
then in my security.xml
<security:http auto-config="false"
use-expressions="true"
authentication-manager-ref="authManager"
access-decision-manager-ref="webAccessDecisionManager"
entry-point-ref="authenticationEntryPoint">
<security:intercept-url pattern="/agent/**" access="hasAnyRole('ROLE_AGENT')" />
<security:intercept-url pattern="/admin/**" access="hasRole('ROLE_ADMIN')" />
<security:intercept-url pattern="/public/**" access="permitAll" />
<security:intercept-url pattern="/**" access="permitAll" />
<security:session-management session-authentication-strategy-ref="sas"
invalid-session-url="/public/login.xhtml"/>
<security:logout logout-success-url="/public/login.xhtml"
invalidate-session="true"
delete-cookies="true"/>
<security:expression-handler ref="webExpressionHandler"/>
<security:custom-filter position="FORM_LOGIN_FILTER" ref="myAuthFilter" />
<security:custom-filter position="CONCURRENT_SESSION_FILTER" ref="concurrencyFilter" />
</security:http>
and
<bean id="authenticationEntryPoint" class="org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint">
<constructor-arg index="0" value="/public/login.xhtml" />
</bean>
<bean id="customAuthenticationFailureHandler" class="org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler"
p:defaultFailureUrl="/public/login.xhtml" />
<bean id="sessionRegistry" class="org.springframework.security.core.session.SessionRegistryImpl"/>
<bean id="concurrencyFilter" class="org.springframework.security.web.session.ConcurrentSessionFilter">
<constructor-arg index="0" ref="sessionRegistry"/>
<constructor-arg index="1" value="/session-expired.htm"/>
</bean>
<bean id="myAuthFilter" class="org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter">
<property name="sessionAuthenticationStrategy" ref="sas" />
<property name="authenticationManager" ref="authManager" />
<property name="authenticationFailureHandler" ref="customAuthenticationFailureHandler"/>
</bean>
<bean id="sas" class="org.springframework.security.web.authentication.session.ConcurrentSessionControlAuthenticationStrategy">
<constructor-arg name="sessionRegistry" ref="sessionRegistry" />
<property name="maximumSessions" value="1" />
<property name="exceptionIfMaximumExceeded" value="true" />
</bean>
<bean id="authManager" class="org.springframework.security.authentication.ProviderManager">
<property name="providers">
<list>
<ref bean="myCompLdapAuthProvider"/>
<ref bean="myCompDBAuthProvider"/>
</list>
</property>
</bean>
My UserDetails implements hashCode() an equals() and with all this the concurrent session limitation does not work. After a little debug session I have observed that my session is never found in sessionRegistry and I guess that this is the main reason, but I do not know why!?
Any idea of what I`m doing wrong here ?
P.S. I have such records in my debug logs:
(FilterChainProxy.java:337) - /resources/images/icons/connection_on.gif at position 2 of 11 in additional filter chain; firing Filter: 'ConcurrentSessionFilter'
(FilterChainProxy.java:337) - /resources/images/icons/connection_on.gif at position 3 of 11 in additional filter chain; firing Filter: 'WebAsyncManagerIntegrationFilter'
(FilterChainProxy.java:337) - /resources/images/icons/connection_on.gif at position 4 of 11 in additional filter chain; firing Filter: 'LogoutFilter'
(FilterChainProxy.java:337) - /resources/images/icons/connection_on.gif at position 5 of 11 in additional filter chain; firing Filter: 'UsernamePasswordAuthenticationFilter'
(FilterChainProxy.java:337) - /resources/images/icons/connection_on.gif at position 6 of 11 in additional filter chain; firing Filter: 'RequestCacheAwareFilter'
(FilterChainProxy.java:337) - /resources/images/icons/connection_on.gif at position 7 of 11 in additional filter chain; firing Filter: 'SecurityContextHolderAwareRequestFilter'
(FilterChainProxy.java:337) - /resources/images/icons/connection_on.gif at position 8 of 11 in additional filter chain; firing Filter: 'AnonymousAuthenticationFilter'
(AnonymousAuthenticationFilter.java:107) - SecurityContextHolder not populated with anonymous token, as it already contained: 'org.springframework.security.authentication.UsernamePasswordAuthenticationToken#96cf68e: Principal: MyUserDetails [username=adrian.videanu, dn=org.springframework.ldap.core.DirContextAdapter: dn=cn=Adrian Videanu,ou=IT,ou=Organization .....
so the filters are invoked...
Updates
I can see that the session creation event is published because i have this line in logs :
(HttpSessionEventPublisher.java:66) - Publishing event: org.springframework.security.web.session.HttpSessionCreatedEvent[source=org.apache.catalina.session.StandardSessionFacade#3827a0aa]
but i never hit registerNewSession method from SessionRegistryImpl as I guess it should. Also the HttpSessionEventPublisher is invoked when I initially open the login page because I guess that`s when the session is created, but then after I enter the credentials and push submit HttpSessionEventPublisher is not invoked anymore.
Updates 2
As a test I have injected SessionRegistryImpl to one of my beans in order to try to access some of its methods:
#Named
#Scope("view")
public class UserDashboardMB implements Serializable {
private static final long serialVersionUID = 1L;
#Inject
private SessionRegistry sessionRegistry;
public void init(){
System.out.println("-- START INIT -- ");
List<Object> principals = sessionRegistry.getAllPrincipals();
System.out.println("Principals = "+principals);
for (Object p:principals){
System.out.println("Principal = "+p);
}
System.out.println("-- STOP INIT -- ");
}
}
and the output is :
INFO: -- START INIT --
INFO: Principals = []
INFO: -- STOP INIT --
so, nothing is populated there.
Update 3
I have replaced "sas" bean with the one provided by Serge but it still doesn`t seems to work. I have neabled the debugger again and I thing that the problem is that on class UsernamePasswordAuthenticationFilter at method doFilter() none of my requests are processed as it should.Here is a part of doFilter():
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
if (!requiresAuthentication(request, response)) {
chain.doFilter(request, response);
return;
}
if (logger.isDebugEnabled()) {
logger.debug("Request is to process authentication");
}
Authentication authResult;
// rest of method here
}
From what I see in the debugger my requests doesn't seems to require auth and chain.doFilter(request, response); is invoked.
Update 4
I guess i found the issue. The filter is not running as it should because the filterUrl param is not the proper one. As i read in the docs:
This filter by default responds to the URL /j_spring_security_check.
but my login part is implemented with JSF managed beans and actions. Now, my login form is at /public/login.xhtml and the url that the login info are posted is the same. If I set this as filterUrl I have problems because is called at the intial form rendering also and I have a infinite loop there as no user/password are set up.
Any idea how to overcome that ?
This is how my LoginManagedBean looks like:
#Named
#Scope("request")
public class LoginMB implements Serializable {
private static final long serialVersionUID = 1L;
#Autowired
#Qualifier("authManager")
private AuthenticationManager authenticationManager;
// setters and getters
public String login(){
FacesContext context = FacesContext.getCurrentInstance();
try {
Authentication request = new UsernamePasswordAuthenticationToken(this.getUsername(), this.getPassword());
Authentication result = authenticationManager.authenticate(request);
SecurityContextHolder.getContext().setAuthentication(result);
// perform some extra logic here and return protected page
return "/agent/dashboard.xhtml?faces-redirect=true";
} catch (AuthenticationException e) {
e.printStackTrace();
logger.error("Auth Exception ->"+e.getMessage());
FacesMessage fm = new FacesMessage("Invalid user/password");
fm.setSeverity(FacesMessage.SEVERITY_ERROR);
context.addMessage(null, fm);
}
return null;
}
}

There is a slight difference between spring security 3.1 and spring security 3.2 concerning concurrency session management.
The old ConcurrentSessionControlStrategy is now deprecated. It checked if the number of concurrent sessions was exceeded and registered sessions in a SessionRegistry for future use.
It has been partially replaced in 3.2 by ConcurrentSessionControlAuthenticationStrategy. It effectively controls if the number of concurrent sessions is exceeded but no longer registers new sessions (even if javadoc pretends to : I looked in the source code to understand it!)
The registration of sessions is now delegated to RegisterSessionAuthenticationStrategy! So for session concurrency to work, you have to use both. And the example in 3.2 reference manual, effectively uses for bean sas a CompositeSessionAuthenticationStrategy containing a ConcurrentSessionControlAuthenticationStrategy, a SessionFixationProtectionStrategy and a RegisterSessionAuthenticationStrategy!
For the whole thing to work, you just have to replace your sas bean with:
<bean id="sas" class="org.springframework.security.web.authentication.session.CompositeSessionAuthenticationStrategy">
<constructor-arg>
<list>
<bean class="org.springframework.security.web.authentication.session.ConcurrentSessionControlAuthenticationStrategy">
<constructor-arg ref="sessionRegistry"/>
<property name="maximumSessions" value="1" />
<property name="exceptionIfMaximumExceeded" value="true" />
</bean>
<bean class="org.springframework.security.web.authentication.session.SessionFixationProtectionStrategy">
</bean>
<bean class="org.springframework.security.web.authentication.session.RegisterSessionAuthenticationStrategy">
<constructor-arg ref="sessionRegistry"/>
</bean>
</list>
</constructor-arg>
</bean>

I have finally managed to fix the issue. The problem was due to my mix setup between spring standard filters and custom jsf login form. I have left in my xml conf only the "sas" bean as Serge pointed out and the in my LoginMB I have manually and programmatically invoked the SessionAuthenticationStrategy onAuthentication() method. So now my LoginMB looks like:
#Named
#Scope("request")
public class LoginMB implements Serializable {
#Autowired
#Qualifier("authManager")
private AuthenticationManager authenticationManager;
#Inject
#Qualifier("sas")
private SessionAuthenticationStrategy sessionAuthenticationStrategy;
public String login(){
FacesContext context = FacesContext.getCurrentInstance();
try {
Authentication authRequest = new UsernamePasswordAuthenticationToken(this.getUsername(), this.getPassword());
Authentication result = authenticationManager.authenticate(authRequest);
SecurityContextHolder.getContext().setAuthentication(result);
HttpServletRequest httpReq = (HttpServletRequest)FacesContext.getCurrentInstance().getExternalContext().getRequest();
HttpServletResponse httpResp = (HttpServletResponse)FacesContext.getCurrentInstance().getExternalContext().getResponse();
sessionAuthenticationStrategy.onAuthentication(result, httpReq, httpResp);
// custom logic here
return "/agent/dashboard.xhtml?faces-redirect=true";
}catch(SessionAuthenticationException sae){
sae.printStackTrace();
logger.error("Auth Exception ->"+sae.getMessage());
String userMessage = "Session auth exception!";
if (sae.getMessage().compareTo("Maximum sessions of 1 for this principal exceeded") == 0){
userMessage = "Cannot login from more than 1 location.";
}
FacesMessage fm = new FacesMessage(userMessage);
fm.setSeverity(FacesMessage.SEVERITY_FATAL);
context.addMessage(null, fm);
}
catch (AuthenticationException e) {
e.printStackTrace();
logger.error("Auth Exception ->"+e.getMessage());
FacesMessage fm = new FacesMessage("Invalid user/password");
fm.setSeverity(FacesMessage.SEVERITY_FATAL);
context.addMessage(null, fm);
}
return null;
}
Now the sessions are registered and session limitation is working.

Related

How to Over ride BindAuthenticator handleBindException for Spring LDAP Authentication setup in Spring Boot

For Spring security setup in Spring Boot. The LDAP Authentication provider is configured by default to use BindAuthenticator class.
This Class contains method
/**
* Allows subclasses to inspect the exception thrown by an attempt to bind with a
* particular DN. The default implementation just reports the failure to the debug
* logger.
*/
protected void handleBindException(String userDn, String username, Throwable cause) {
if (logger.isDebugEnabled()) {
logger.debug("Failed to bind as " + userDn + ": " + cause);
}
}
This Method is to handle the authentication related Exceptions like invalid credentials.
I want to over-ride this method so i can handle this issue and return proper error message on the basis of error codes returned by LDAP. like invalid password or the account is locked.
Current LDAP implementation always returns "Bad Credentials" that does not give the right picture that why my credentials are invalid. i want to cover the cases
where the account is Locked
password is expired so i can redirect to change password
account locked due to number of invalid password retries
Please help
The issue i fixed by defining the LDAP context instead of using the Spring Boot LDAPAuthenticationProviderConfigurer.
Then created the FilterBasedLdapUserSearch and Over-written the BindAuthentication with my ConnectBindAuthenticator.
i created a separate LDAPConfiguration class for spring boot configuration and registered all these custom objects as Beans.
From the above Objects i created LDAPAuthenticationProvider by passing my Custom Objects to constructor
The Config is as below
#Bean
public DefaultSpringSecurityContextSource contextSource() {
DefaultSpringSecurityContextSource contextSource = new DefaultSpringSecurityContextSource(env.getProperty("ldap.url"));
contextSource.setBase(env.getProperty("ldap.base"));
contextSource.setUserDn(env.getProperty("ldap.managerDn"));
contextSource.setPassword(env.getProperty("ldap.managerPassword"));
return contextSource;
}
#Bean
public ConnectBindAuthenticator bindAuthenticator() {
ConnectBindAuthenticator connectBindAuthenticator = new ConnectBindAuthenticator(contextSource());
connectBindAuthenticator.setUserSearch(ldapUserSearch());
connectBindAuthenticator.setUserDnPatterns(new String[]{env.getProperty("ldap.managerDn")});
return connectBindAuthenticator;
}
#Bean
public LdapUserSearch ldapUserSearch() {
return new FilterBasedLdapUserSearch("", env.getProperty("ldap.userSearchFilter"), contextSource());
}
You have to change your spring security configuration to add your extension of BindAuthenticator:
CustomBindAuthenticator.java
public class CustomBindAuthenticator extends BindAuthenticator {
public CustomBindAuthenticator(BaseLdapPathContextSource contextSource) {
super(contextSource);
}
#Override
protected void handleBindException(String userDn, String username, Throwable cause) {
// TODO: Include here the logic of your custom BindAuthenticator
if (somethingHappens()) {
throw new MyCustomException("Custom error message");
}
super.handleBindException(userDn, username, cause);
}
}
spring-security.xml
<beans:bean id="contextSource"
class="org.springframework.security.ldap.DefaultSpringSecurityContextSource">
<beans:constructor-arg value="LDAP_URL" />
<beans:property name="userDn" value="USER_DN" />
<beans:property name="password" value="PASSWORD" />
</beans:bean>
<beans:bean id="userSearch"
class="org.springframework.security.ldap.search.FilterBasedLdapUserSearch">
<beans:constructor-arg index="0" value="USER_SEARCH_BASE" />
<beans:constructor-arg index="1" value="USER_SEARCH_FILTER" />
<beans:constructor-arg index="2" ref="contextSource" />
</beans:bean>
<beans:bean id="ldapAuthProvider"
class="org.springframework.security.ldap.authentication.LdapAuthenticationProvider">
<beans:constructor-arg>
<beans:bean class="com.your.project.CustomBindAuthenticator">
<beans:constructor-arg ref="contextSource" />
<beans:property name="userSearch" ref="userSearch" />
</beans:bean>
</beans:constructor-arg>
</beans:bean>
<security:authentication-manager alias="authenticationManager">
<security:authentication-provider ref="ldapAuthProvider" />
</security:authentication-manager>
Hope it's helpful.

Spring security - Get all logged in principals

First of all! Thank you for reading my question.
I have a problem with retreiving all my principal objects. I use Spring version 3.2.1.RELEASE and spring security 3.1.3.RELEASE.
I did my research on the net and I found how to retrieve the principals, but after inserting my own authentication code it doesnt work anymore. Methode to retrieve all principals objects:
#RequestMapping("/loggedinusers")
public String viewAllLoggedInUsers(Model model) {
List<Object> principals = sessionRegistry.getAllPrincipals();
model.addAttribute("size", principals.size());
List<Integer> listOfUserIds = new ArrayList<Integer>();
for (Object principal : principals) {
if (principal instanceof Principal) {
listOfUserIds.add(((Principal) principal).getId());
}
}
return "/logged_in_users";
}
The above code was working before I changed some security configuration. Here is all my configuration:
<!-- bean namespave -->
<security:global-method-security jsr250-annotations="enabled" pre-post-annotations="enabled" secured-annotations="enabled" />
<security:http use-expressions="true" entry-point-ref="loginEntryPoint">
<security:intercept-url pattern="/login" access="permitAll()" />
<!-- ******* Filters ******* -->
<security:custom-filter ref="ipFormLoginFilter" position="FORM_LOGIN_FILTER"/>
<security:logout
delete-cookies="JSESSIONID"
logout-url="/logout"
logout-success-url="/login"
/>
<security:session-management session-fixation-protection="newSession">
<security:concurrency-control session-registry-alias="sessionRegistry" max-sessions="5" error-if-maximum-exceeded="false" />
</security:session-management>
</security:http>
<bean id="loginEntryPoint" class="org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint">
<constructor-arg value="/login"/>
</bean>
<security:authentication-manager alias="authenticationManager">
<security:authentication-provider ref="customUserAuthenticationProvider" />
</security:authentication-manager>
<bean id="ipFormLoginFilter" class="nl.irp.vadp.security.CustomIpUsernamePasswordAuthenticationFilter">
<property name="filterProcessesUrl" value="/authlogin"/>
<property name="authenticationManager" ref="authenticationManager"/>
<property name="usernameParameter" value="username"/>
<property name="passwordParameter" value="password"/>
<property name="authenticationSuccessHandler">
<bean class="org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler">
<property name="defaultTargetUrl" value="/"/>
</bean>
</property>
<property name="authenticationFailureHandler">
<bean class="org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler">
<property name="defaultFailureUrl" value="/login?login_error=true"/>
</bean>
</property>
</bean>
<bean id="passwordEncoder" class="org.springframework.security.authentication.encoding.ShaPasswordEncoder">
<constructor-arg value="512" />
</bean>
</beans>
Code::
Filter class
public final class CustomIpUsernamePasswordAuthenticationFilter extends UsernamePasswordAuthenticationFilter {
#Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
if (request.getMethod().equals("POST")) {
String username = obtainUsername(request);
String password = obtainPassword(request);
UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, password);
setDetails(request, authRequest);
return this.getAuthenticationManager().authenticate(authRequest);
}
throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
}
}
Code:: Custom Authentication class
#Component
public class CustomUserAuthenticationProvider implements AuthenticationProvider {
#Autowired
UserService userService;
#Autowired
ShaPasswordEncoder shaPasswordEncoder;
public CustomUserAuthenticationProvider() {
}
#Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
final String BAD_CREDENTIALS = "test";
final String BAD_IP_ADDRESS = "test";
List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
UsernamePasswordAuthenticationToken token = (UsernamePasswordAuthenticationToken) authentication;
String email = token.getName();
User user = null;
if (email != null) {
user = userService.findUserByEmail(email);
}
if (user == null) {
throw new UsernameNotFoundException(BAD_CREDENTIALS + "no user found");
}
String password = user.getPassword();
String salt = user.getName();
if (!shaPasswordEncoder.isPasswordValid(password, (String) token.getCredentials(), salt)) {
throw new BadCredentialsException(BAD_CREDENTIALS + "bad password");
}
if (!user.hasIpaddress(request.getRemoteAddr())) {
throw new BadCredentialsException(BAD_IP_ADDRESS + "bad ip adress");
}
authorities.add(new SimpleGrantedAuthority("ROLE_" + user.getRole().getName().toUpperCase()));
Principal principal = new Principal(user.getEmail(), user.getPassword(), authorities, user.getId());
return new UsernamePasswordAuthenticationToken(principal, user.getPassword());
}
#Override
public boolean supports(Class<?> authentication) {
return CustomIpUsernamePasswordAuthenticationToken.class.equals(authentication);
}
}
The following listeners are added:
<!-- Listeners -->
<listener><!-- Starts up the webapp project -->
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<listener><!-- spring security listener -->
<listener-class>org.springframework.security.web.session.HttpSessionEventPublisher</listener-class>
</listener>
<!-- extra toegevoegd voor die ip ... -->
<listener>
<listener-class>
org.springframework.web.context.request.RequestContextListener
</listener-class>
</listener>
As the above code describes, I made my own AuthenticationProvider with an authenticate methode which authenticates the inserted data. This works perfectly (component scan is also done). Authorities in jsp ( for example) seems to work also. I seem not to understand why I cant get the registered principals.
edit:
I removed the "auto-config=true" en the tag before inserting additional information.
Hope someone can help me out.
EDIT 2:
I found out where the problem was. In my own custom filter, there is a property called:sessionAuthenticationStrategy. This field needs to be set.
I inserted the following in my filter and it works:
<property name="sessionAuthenticationStrategy" ref="sessionFixationProtectionStrategy" />
<bean id="sessionFixationProtectionStrategy" class="org.springframework.security.web.authentication.session.SessionFixationProtectionStrategy">
Gtrz,

Login/logout in REST with Spring 3

We are developing RESTful webservices with Spring 3 and we need to have the functionality of login/logout, something like /webservices/login/<username>/<password>/ and /webservices/logout. The session should be stored in the context until the session is timed out or logged out to allow consumption of other webservices. Any request to access webservices without session information should be rejected. Looking for state-of-the-art solution for this scenario.
I am actually resurrecting the question asked here Spring Security 3 programmatically login, which is still not properly answered. Please specify the changes needed in web.xml as well.
I would suggest defining your Spring Security filters completely manually. It's not that difficult, and you get full control over your login/logout behaviour.
First of all, you will need standard web.xml blurb to delegate filter chain handling to Spring (remove async-supported if you are not on Servlet API ver 3):
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<async-supported>true</async-supported>
<filter-class>
org.springframework.web.filter.DelegatingFilterProxy
</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
Now, in security context you will define filters separately for each path. Filters can authenticate user, log out user, check security credentials etc.
<bean id="springSecurityFilterChain" class="org.springframework.security.web.FilterChainProxy">
<sec:filter-chain-map path-type="ant">
<sec:filter-chain pattern="/login" filters="sif,wsFilter"/>
<sec:filter-chain pattern="/logout" filters="sif,logoutFilter" />
<sec:filter-chain pattern="/rest/**" filters="sif,fsi"/>
</sec:filter-chain-map>
</bean>
The XML above tells Spring to pass requests to specific context-relative URLs through filter chains. First thing in any of the filter chains is establishing security context - 'sif' bean takes care of that.
<bean id="sif" class="org.springframework.security.web.context.SecurityContextPersistenceFilter"/>
Next filter in chain can now either add data to the security context (read: log in/log out user), or make a decision as to whether allow access based on said security context.
For your login URL you will want a filter that reads authentication data from the request, validates it, and in turn stores it in security context (which is stored in session):
<bean id="wsFilter" class="my.own.security.AuthenticationFilter">
<property name="authenticationManager" ref="authenticationManager"/>
<property name="authenticationSuccessHandler" ref="myAuthSuccessHandler"/>
<property name="passwordParameter" value="pass"></property>
<property name="usernameParameter" value="user"></property>
<property name="postOnly" value="false"></property>
You can use Spring generic UsernamePasswordAuthenticationFilter but the reason I use my own implementation is to continue filter chain processing (default implementation assumes user will get redirected on successful auth and terminates filter chain), and being able to process authentication every time username and password is passed to it:
public class MyAuthenticationFilter extends UsernamePasswordAuthenticationFilter {
#Override
protected boolean requiresAuthentication(HttpServletRequest request, HttpServletResponse response) {
return ( StringUtils.hasText(obtainUsername(request)) && StringUtils.hasText(obtainPassword(request)) );
}
#Override
protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain,
Authentication authResult) throws IOException, ServletException{
super.successfulAuthentication(request, response, chain, authResult);
chain.doFilter(request, response);
}
You can add any number of your own filter implementations for /login path, such as authentication using HTTP basic auth header, digest header, or even extract username/pwd from the request body. Spring provides a bunch of filters for that.
I have my own auth success handler who overrides the default redirect strategy:
public class AuthenticationSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {
#PostConstruct
public void afterPropertiesSet() {
setRedirectStrategy(new NoRedirectStrategy());
}
protected class NoRedirectStrategy implements RedirectStrategy {
#Override
public void sendRedirect(HttpServletRequest request,
HttpServletResponse response, String url) throws IOException {
// no redirect
}
}
}
You don't have to have custom auth success handler (and probably custom auth filter as well) if you're ok with user being redirected after successful login (redirect URL can be customized, check docs)
Define authentication manager who will be responsible for retrieving user's details:
<sec:authentication-manager alias="authenticationManager">
<sec:authentication-provider ref="myAuthAuthProvider"/>
</sec:authentication-manager>
<bean id="myAuthAuthProvider" 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="myUserDetailsImpl"/>
</bean>
</property>
</bean>
You will have to provide your own user details bean implementation here.
Logout filter: responsible for clearing security context
<bean id="logoutFilter" class="org.springframework.security.web.authentication.logout.LogoutFilter">
<constructor-arg>
<list>
<bean class="org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler"/>
</list>
</constructor-arg>
</bean>
Generic authentication stuff:
<bean id="httpRequestAccessDecisionManager" class="org.springframework.security.access.vote.AffirmativeBased">
<property name="allowIfAllAbstainDecisions" value="false"/>
<property name="decisionVoters">
<list>
<ref bean="roleVoter"/>
</list>
</property>
</bean>
<bean id="roleVoter" class="org.springframework.security.access.vote.RoleVoter"/>
<bean id="securityContextHolderAwareRequestFilter" class="org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter"/>
Access control filter (should be self-explanatory):
<bean id="fsi" class="org.springframework.security.web.access.intercept.FilterSecurityInterceptor">
<property name="authenticationManager" ref="myAuthenticationManager"/>
<property name="accessDecisionManager" ref="httpRequestAccessDecisionManager"/>
<property name="securityMetadataSource">
<sec:filter-invocation-definition-source>
<sec:intercept-url pattern="/rest/**" access="ROLE_REST"/>
</sec:filter-invocation-definition-source>
</property>
</bean>
You should also be able to secure your REST services with #Secured annotations on methods.
Context above was plucked from existing REST service webapp - sorry for any possible typos.
It is also possible to do at least most of what is implemented here by using stock sec Spring tags, but I prefer custom approach as that gives me most control.
Hope this at least gets you started.

Spring security for Authorization only

I'm working in a new project where I need to manage user roles, just that, because this application is using its own authentication system through web services. So, the only thing I need to do is validate each user role, if the user id exists in my database he could enter otherwise will be rejected. It means, no password, no login page (that is performed by the web services), just user id validation and get their roles.
I did a proof of concept in order to implement this according to my understanding, this was after reading the documentation involved. The point is that this is not working as expected, let me share this example with you:
Security settings
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:security="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-3.0.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-3.1.xsd">
<security:http use-expressions="true" entry-point-ref="http403ForbiddenEntryPoint">
<security:anonymous enabled="false" />
<security:intercept-url pattern="index.jsp" access="permitAll" />
<security:intercept-url pattern="home.html" access="hasRole('ROLE_ADMIN')" />
<security:intercept-url pattern="excel.html" access="hasAnyRole('ROLE_USER','ROLE_ADMIN')" />
<security:intercept-url pattern="denied.jsp" access="permitAll" />
<security:custom-filter position="PRE_AUTH_FILTER" ref="meivFilter" />
</security:http>
<bean id="http403ForbiddenEntryPoint" class="org.springframework.security.web.authentication.Http403ForbiddenEntryPoint" />
<bean id="meivFilter" class="org.springframework.security.web.authentication.preauth.RequestHeaderAuthenticationFilter">
<property name="principalRequestHeader" value="Host" />
<property name="authenticationManager" ref="authenticationManager" />
</bean>
<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="userDetailsService" />
</bean>
</property>
</bean>
<security:authentication-manager alias="authenticationManager">
<security:authentication-provider ref="preauthAuthProvider" />
</security:authentication-manager>
<bean id="userDetailsService" class="com.gm.gpsc.meiv.security.UserServiceImpl" />
</beans>
Note:In order to test it, as you can see, I use in RequestHeaderAuthenticationFilter as principalRequestHeader attribute, the Host header value which is present as default header value. Just for testing. Because in the future I going to read a value from the header.
This is the userDetailService I did in order to get user roles.
public class UserServiceImpl implements UserDetailsService {
private boolean accountNonExpired = true;
private boolean accountNonLocked = true;
private boolean credentialsNonExpired = true;
private boolean enabled = true;
#Override
public UserDetails loadUserByUsername(String userId)
throws UsernameNotFoundException {
GrantedAuthority[] grantedAuthority = new GrantedAuthority[1];
grantedAuthority[0] = new GrantedAuthorityImpl("ROLE_USER");
Collection<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
authorities.add(grantedAuthority[0]);
return new User(userId, "x",enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, authorities);
}
}
When I run this example the settings are loaded successfully, then when I try to reach the first pattern, home.html, I can reach that page, which is wrong, because according to my rule I have ROLE_USER and as you can see above I need ROLE_ADMIN.
For the second pattern I could get access too but in that case it makes sense because ROLE_USER is include as rule.
For the first situation I change home.html for /home.html and I got 403 Access denied. But If I use the same pattern for the second option excel, it means /excel.html, I got the same error (403).
This is the error I get from the log file:
DEBUG | 2012-09-30 03:55:09,738 | FilterChainProxy | /index.jsp at position 1 of 7 in additional filter chain; firing Filter: 'SecurityContextPersistenceFilter'
DEBUG | 2012-09-30 03:55:09,739 | HttpSessionSecurityContextRepository | No HttpSession currently exists
DEBUG | 2012-09-30 03:55:09,739 | HttpSessionSecurityContextRepository | No SecurityContext was available from the HttpSession: null. A new one will be created.
DEBUG | 2012-09-30 03:55:09,744 | FilterChainProxy | /index.jsp at position 2 of 7 in additional filter chain; firing Filter: 'RequestHeaderAuthenticationFilter'
DEBUG | 2012-09-30 03:55:09,744 | RequestHeaderAuthenticationFilter | Checking secure context token: null
DEBUG | 2012-09-30 03:55:09,744 | HttpSessionSecurityContextRepository | SecurityContext is empty or contents are anonymous - context will not be stored in HttpSession.
DEBUG | 2012-09-30 03:55:09,744 | SecurityContextPersistenceFilter | SecurityContextHolder now cleared, as request processing completed
30/09/2012 03:55:09 org.apache.catalina.core.StandardWrapperValve invoke
GRAVE: Servlet.service() para servlet jsp lanzó excepción
org.springframework.security.web.authentication.preauth.PreAuthenticatedCredentialsNotFoundException: MYID header not found in request.
I don't understand what's going on here, maybe someone can explain me where I'm wrong.
I'd appreciate your help because I am so confused with this and tired of reading the documentation without getting anywhere.

How can I use Spring Security without sessions?

I am building a web application with Spring Security that will live on Amazon EC2 and use Amazon's Elastic Load Balancers. Unfortunately, ELB does not support sticky sessions, so I need to ensure my application works properly without sessions.
So far, I have setup RememberMeServices to assign a token via a cookie, and this works fine, but I want the cookie to expire with the browser session (e.g. when the browser closes).
I have to imagine I'm not the first one to want to use Spring Security without sessions... any suggestions?
In Spring Security 3 with Java Config, you can use HttpSecurity.sessionManagement():
#Override
protected void configure(final HttpSecurity http) throws Exception {
http
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}
We worked on the same issue (injecting a custom SecurityContextRepository to SecurityContextPersistenceFilter) for 4-5 hours today. Finally, we figured it out.
First of all, in the section 8.3 of Spring Security ref. doc, there is a SecurityContextPersistenceFilter bean definition
<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='false' />
</bean>
</property>
</bean>
And after this definition, there is this explanation:
"Alternatively you could provide a null implementation of the SecurityContextRepository interface, which will prevent the security context from being stored, even if a session has already been created during the request."
We needed to inject our custom SecurityContextRepository into the SecurityContextPersistenceFilter. So we simply changed the bean definition above with our custom impl and put it into the security context.
When we run the application, we traced the logs and saw that SecurityContextPersistenceFilter was not using our custom impl, it was using the HttpSessionSecurityContextRepository.
After a few other things we tried, we figured out that we had to give our custom SecurityContextRepository impl with the "security-context-repository-ref" attribute of "http" namespace. If you use "http" namespace and want to inject your own SecurityContextRepository impl, try "security-context-repository-ref" attribute.
When "http" namespace is used, a seperate SecurityContextPersistenceFilter definition is ignored. As I copied above, the reference doc. does not state that.
Please correct me if I misunderstood the things.
It seems to be even easier in Spring Securitiy 3.0. If you're using namespace configuration, you can simply do as follows:
<http create-session="never">
<!-- config -->
</http>
Or you could configure the SecurityContextRepository as null, and nothing would ever get saved that way as well.
Take a look at SecurityContextPersistenceFilter class. It defines how the SecurityContextHolder is populated. By default it uses HttpSessionSecurityContextRepository to store security context in http session.
I have implemented this mechanism quite easily, with custom SecurityContextRepository.
See the securityContext.xml below:
<?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:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:sec="http://www.springframework.org/schema/security"
xmlns:jee="http://www.springframework.org/schema/jee"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.0.xsd">
<context:annotation-config/>
<sec:global-method-security secured-annotations="enabled" pre-post-annotations="enabled"/>
<bean id="securityContextRepository" class="com.project.server.security.TokenSecurityContextRepository"/>
<bean id="securityContextFilter" class="com.project.server.security.TokenSecurityContextPersistenceFilter">
<property name="repository" ref="securityContextRepository"/>
</bean>
<bean id="logoutFilter" class="org.springframework.security.web.authentication.logout.LogoutFilter">
<constructor-arg value="/login.jsp"/>
<constructor-arg>
<list>
<bean class="org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler"/>
</list>
</constructor-arg>
</bean>
<bean id="formLoginFilter"
class="org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter">
<property name="authenticationManager" ref="authenticationManager"/>
<property name="authenticationSuccessHandler">
<bean class="com.project.server.security.TokenAuthenticationSuccessHandler">
<property name="defaultTargetUrl" value="/index.html"/>
<property name="passwordExpiredUrl" value="/changePassword.jsp"/>
<property name="alwaysUseDefaultTargetUrl" value="true"/>
</bean>
</property>
<property name="authenticationFailureHandler">
<bean class="com.project.server.modules.security.CustomUrlAuthenticationFailureHandler">
<property name="defaultFailureUrl" value="/login.jsp?failure=1"/>
</bean>
</property>
<property name="filterProcessesUrl" value="/j_spring_security_check"/>
<property name="allowSessionCreation" value="false"/>
</bean>
<bean id="servletApiFilter"
class="org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter"/>
<bean id="anonFilter" class="org.springframework.security.web.authentication.AnonymousAuthenticationFilter">
<property name="key" value="ClientApplication"/>
<property name="userAttribute" value="anonymousUser,ROLE_ANONYMOUS"/>
</bean>
<bean id="exceptionTranslator" class="org.springframework.security.web.access.ExceptionTranslationFilter">
<property name="authenticationEntryPoint">
<bean class="org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint">
<property name="loginFormUrl" value="/login.jsp"/>
</bean>
</property>
<property name="accessDeniedHandler">
<bean class="org.springframework.security.web.access.AccessDeniedHandlerImpl">
<property name="errorPage" value="/login.jsp?failure=2"/>
</bean>
</property>
<property name="requestCache">
<bean id="nullRequestCache" class="org.springframework.security.web.savedrequest.NullRequestCache"/>
</property>
</bean>
<alias name="filterChainProxy" alias="springSecurityFilterChain"/>
<bean id="filterChainProxy" class="org.springframework.security.web.FilterChainProxy">
<sec:filter-chain-map path-type="ant">
<sec:filter-chain pattern="/**"
filters="securityContextFilter, logoutFilter, formLoginFilter,
servletApiFilter, anonFilter, exceptionTranslator, filterSecurityInterceptor"/>
</sec:filter-chain-map>
</bean>
<bean id="filterSecurityInterceptor"
class="org.springframework.security.web.access.intercept.FilterSecurityInterceptor">
<property name="securityMetadataSource">
<sec:filter-security-metadata-source use-expressions="true">
<sec:intercept-url pattern="/staticresources/**" access="permitAll"/>
<sec:intercept-url pattern="/index.html*" access="hasRole('USER_ROLE')"/>
<sec:intercept-url pattern="/rpc/*" access="hasRole('USER_ROLE')"/>
<sec:intercept-url pattern="/**" access="permitAll"/>
</sec:filter-security-metadata-source>
</property>
<property name="authenticationManager" ref="authenticationManager"/>
<property name="accessDecisionManager" ref="accessDecisionManager"/>
</bean>
<bean id="accessDecisionManager" class="org.springframework.security.access.vote.AffirmativeBased">
<property name="decisionVoters">
<list>
<bean class="org.springframework.security.access.vote.RoleVoter"/>
<bean class="org.springframework.security.web.access.expression.WebExpressionVoter"/>
</list>
</property>
</bean>
<bean id="authenticationManager" class="org.springframework.security.authentication.ProviderManager">
<property name="providers">
<list>
<bean name="authenticationProvider"
class="com.project.server.modules.security.oracle.StoredProcedureBasedAuthenticationProviderImpl">
<property name="dataSource" ref="serverDataSource"/>
<property name="userDetailsService" ref="userDetailsService"/>
<property name="auditLogin" value="true"/>
<property name="postAuthenticationChecks" ref="customPostAuthenticationChecks"/>
</bean>
</list>
</property>
</bean>
<bean id="customPostAuthenticationChecks" class="com.project.server.modules.security.CustomPostAuthenticationChecks"/>
<bean name="userDetailsService" class="com.project.server.modules.security.oracle.UserDetailsServiceImpl">
<property name="dataSource" ref="serverDataSource"/>
</bean>
</beans>
Actually create-session="never" doesn't mean being completely stateless. There's an issue for that in Spring Security issue management.
EDIT: As of Spring Security 3.1, there is a STATELESS option that can be used instead of all this. See the other answers. Original answer kept below for posterity.
After struggling with the numerous solutions posted in this answer, to try to get something working when using the <http> namespace config, I finally found an approach that actually works for my use case. I don't actually require that Spring Security doesn't start a session (because I use session in other parts of the application), just that it doesn't "remember" authentication in the session at all (it should be re-checked every request).
To begin with, I wasn't able to figure out how to do the "null implementation" technique described above. It wasn't clear whether you are supposed to set the securityContextRepository to null or to a no-op implementation. The former does not work because a NullPointerException gets thrown within SecurityContextPersistenceFilter.doFilter(). As for the no-op implementation, I tried implementing in the simplest way I could imagine:
public class NullSpringSecurityContextRepository implements SecurityContextRepository {
#Override
public SecurityContext loadContext(final HttpRequestResponseHolder requestResponseHolder_) {
return SecurityContextHolder.createEmptyContext();
}
#Override
public void saveContext(final SecurityContext context_, final HttpServletRequest request_,
final HttpServletResponse response_) {
}
#Override
public boolean containsContext(final HttpServletRequest request_) {
return false;
}
}
This doesn't work in my application, because of some strange ClassCastException having to do with the response_ type.
Even assuming I did manage to find an implementation that works (by simply not storing the context in session), there is still the problem of how to inject that into the filters built by the <http> configuration. You cannot simply replace the filter at the SECURITY_CONTEXT_FILTER position, as per the docs. The only way I found to hook into the SecurityContextPersistenceFilter that is created under the covers was to write an ugly ApplicationContextAware bean:
public class SpringSecuritySessionDisabler implements ApplicationContextAware {
private final Logger logger = LoggerFactory.getLogger(SpringSecuritySessionDisabler.class);
private ApplicationContext applicationContext;
#Override
public void setApplicationContext(final ApplicationContext applicationContext_) throws BeansException {
applicationContext = applicationContext_;
}
public void disableSpringSecuritySessions() {
final Map<String, FilterChainProxy> filterChainProxies = applicationContext
.getBeansOfType(FilterChainProxy.class);
for (final Entry<String, FilterChainProxy> filterChainProxyBeanEntry : filterChainProxies.entrySet()) {
for (final Entry<String, List<Filter>> filterChainMapEntry : filterChainProxyBeanEntry.getValue()
.getFilterChainMap().entrySet()) {
final List<Filter> filterList = filterChainMapEntry.getValue();
if (filterList.size() > 0) {
for (final Filter filter : filterList) {
if (filter instanceof SecurityContextPersistenceFilter) {
logger.info(
"Found SecurityContextPersistenceFilter, mapped to URL '{}' in the FilterChainProxy bean named '{}', setting its securityContextRepository to the null implementation to disable caching of authentication",
filterChainMapEntry.getKey(), filterChainProxyBeanEntry.getKey());
((SecurityContextPersistenceFilter) filter).setSecurityContextRepository(
new NullSpringSecurityContextRepository());
}
}
}
}
}
}
}
Anyway, to the solution that actually does work, albeit very hackish. Simply use a Filter that deletes the session entry that the HttpSessionSecurityContextRepository looks for when it does its thing:
public class SpringSecuritySessionDeletingFilter extends GenericFilterBean implements Filter {
#Override
public void doFilter(final ServletRequest request_, final ServletResponse response_, final FilterChain chain_)
throws IOException, ServletException {
final HttpServletRequest servletRequest = (HttpServletRequest) request_;
final HttpSession session = servletRequest.getSession();
if (session.getAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY) != null) {
session.removeAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY);
}
chain_.doFilter(request_, response_);
}
}
Then in the configuration:
<bean id="springSecuritySessionDeletingFilter"
class="SpringSecuritySessionDeletingFilter" />
<sec:http auto-config="false" create-session="never"
entry-point-ref="authEntryPoint">
<sec:intercept-url pattern="/**"
access="IS_AUTHENTICATED_REMEMBERED" />
<sec:intercept-url pattern="/static/**" filters="none" />
<sec:custom-filter ref="myLoginFilterChain"
position="FORM_LOGIN_FILTER" />
<sec:custom-filter ref="springSecuritySessionDeletingFilter"
before="SECURITY_CONTEXT_FILTER" />
</sec:http>
Just a quick note: it's "create-session" rather than "create-sessions"
create-session
Controls the eagerness with which an HTTP session is created.
If not set, defaults to "ifRequired". Other options are "always" and "never".
The setting of this attribute affect the allowSessionCreation and forceEagerSessionCreation properties of HttpSessionContextIntegrationFilter. allowSessionCreation will always be true unless this attribute is set to "never". forceEagerSessionCreation is "false" unless it is set to "always".
So the default configuration allows session creation but does not force it. The exception is if concurrent session control is enabled, when forceEagerSessionCreation will be set to true, regardless of what the setting is here. Using "never" would then cause an exception during the initialization of HttpSessionContextIntegrationFilter.
For specific details of the session usage, there is some good documentation in the HttpSessionSecurityContextRepository javadoc.
Now ELB supports sticky sessions, I think from 2016.
But also it's possible to store your sessions in Redis.

Resources