Listening Has Always Been Our Strongest Tool!

Just Give Us a Try, we respond to all messages within 1 business day. Really!


How can we reach out to you?






NDA From The Start
We keep your idea safe. We're always willing to sign a Non-Disclosure Agreement with you and fully protect your intellectual property.

captcha

Other Ways To Meet Us :info@zealousys.com
Our Blog
Jan 02
2014

Spring Custom authentication

By zealousys

Comprehensive Authorization Services:
Powerful EL-Based Syntax: Spring Security 3.0 focuses on the use of expression-language as an alternative to the older voter-based mechanism. The latter is still fully supported which allows security access rules to be easily defined in terms of the current invocation context without the use of custom code. By using this approach one can define access constraints using multiple factors like user identity, time of day, authorities held, method being invoked, method arguments and specific properties on method arguments or any other syntax supported by Spring-EL.

HTTP Requests Authorization:
No longer is it necessary to rely on web.xml security constraints. Spring Security allows securing of static URLs defined using a choice of regular expressions or Apache Ant paths, along with pluggable authentication, access-control and run-as replacement managers.

applicationContext.xml

  1. <?xml version=”1.0″ encoding=”UTF-8″?>
  2. <beans xmlns=”http://www.springframework.org/schema/beans”
  3.    xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance”
  4.    xmlns:p=”http://www.springframework.org/schema/p”
  5.    xmlns:aop=”http://www.springframework.org/schema/aop”
  6.    xmlns:context=”http://www.springframework.org/schema/context”
  7.    xmlns:security=”http://www.springframework.org/schema/security”
  8.    xmlns:util=”http://www.springframework.org/schema/util”
  9.    xsi:schemaLocation=”http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
  10.    http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
  11.       http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.0.xsd
  12.       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
  13.       http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd”>
  14.  
  15. <!– for using property file –>
  16. <bean id=”propertyConfigurer” class=”org.springframework.beans.factory.config.PropertyPlaceholderConfigurer” p:location=”/projectfields.properties” />
  17.  
  18. <!– for Database connections –>
  19. <bean class=”org.apache.commons.dbcp.BasicDataSource” id=”dataSource” destroy-method=”close”>
  20.    <property name=”driverClassName”>
  21.       <value>foo.fooserver.jdbc.FOODriver</value>
  22.    </property>
  23.    <property name=”url”>
  24.       <value>jdbc:url</value>
  25.    </property>
  26.    <property name=”username”>
  27.       <value>username</value>
  28.    </property>
  29.    <property name=”password”>
  30.       <value>password</value>
  31.    </property>
  32.    <property name=”maxActive” value=”100″/>
  33.    <property name=”maxWait” value=”10000″/>
  34.    <property name=”maxIdle” value=”10″/>
  35. </bean>
  36.  
  37. <!– for implementing session factory–>
  38. <bean class=”org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean” id=”sessionFactory” primary=”true” >
  39.    <property name=”dataSource”>
  40.       <ref bean=”dataSource”/>
  41.    </property>
  42.    <!–packagesToScan scans all the classes for hibernate(models)–>
  43.    <property name=”packagesToScan” value=”test.vipul.**.model”/>
  44.    <property name=”hibernateProperties”>
  45.       <props>
  46.          <prop key=”hibernate.dialect”>org.hibernate.dialect.SQLServerDialect</prop>
  47.          <prop key=”current_session_context_class”>thread</prop>
  48.          <prop key=”hibernate.cache.use_second_level_cache”>true</prop>
  49.          <prop key=”hibernate.connection.autocommit”>true</prop>
  50.          <prop key=”hibernate.max_fetch_depth”>5</prop>
  51.          <prop key=”hibernate.default_batch_fetch_size”>16</prop>
  52.          <prop key=”hibernate.jdbc.batch_size”>25</prop>
  53.          <prop key=”hibernate.jdbc.fetch_size”>8</prop>
  54.          <prop key=”hibernate.show_sql”>false</prop>
  55.          <prop key=”hibernate.connection.release_mode”>after_statement</prop>
  56.       </props>
  57.    </property>
  58. </bean>
  59. <!– for implementing transaction–>
  60. <bean id=”transactionManager” class=”org.springframework.orm.hibernate3.HibernateTransactionManager” p:sessionFactory-ref=”sessionFactory” />
  61.  
  62. <bean class=”org.springframework.orm.hibernate3.HibernateTemplate” id=”hibernateTemplate”>
  63.    <property name=”sessionFactory”>
  64.       <ref bean=”sessionFactory”/>
  65.    </property>
  66. </bean>
  67.  
  68. <!– This is where we configure Spring-Security –>
  69. <security:http auto-config=”false” entry-point-ref=”authenticationEntryPoint”>
  70.    <security:intercept-url pattern=”/school/” access=”IS_AUTHENTICATED_ANONYMOUSLY” />
  71.    <security:intercept-url pattern=”/common/**” access=”ROLE_TEACHER,ROLE_CLERK,ROLE_STUDENT”/>
  72.    <security:intercept-url pattern=”/clerk/**” access=”ROLE_CLERK” />
  73.    <security:intercept-url pattern=”/teacher/**” access=”ROLE_TEACHER” />
  74.    <security:intercept-url pattern=”/student/**” access=”ROLE_STUDENT” />
  75.    <security:logout logout-success-url=”/logout” />
  76.    <security:custom-filter position=”CONCURRENT_SESSION_FILTER” ref=”concurrencyFilter” />
  77.    <security:custom-filter ref=”authenticationFilter” position=”FORM_LOGIN_FILTER”/>
  78.    <security:custom-filter after=”CONCURRENT_SESSION_FILTER” ref=”secureFilter” />
  79.    <security:session-management session-authentication-strategy-ref=”sas”/>
  80. </security:http>
  81.  
  82. <!– Custom filter for username and password. The real customization is done in the customAthenticationManager –>
  83. <bean id=”authenticationFilter” class=”org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter”
  84.    p:authenticationManager-ref=”customAuthenticationManager”
  85.    p:authenticationFailureHandler-ref=”customAuthenticationFailureHandler”
  86.    p:authenticationSuccessHandler-ref=”customAuthenticationSuccessHandler”
  87.    p:sessionAuthenticationStrategy-ref=”sas”/>
  88.  
  89. <!– Custom authentication manager. In order to authenticate username and password. –>
  90. <bean id=”customAuthenticationManager” class=”com.vipul.CustomAuthenticationFilter”>
  91.    <constructor-arg type=”org.hibernate.SessionFactory” ref=”sessionFactory”/>
  92.    <!–Define maximum number of failed login attempt i.e. after how many consecutive failed attempts user’s account should be disabled–>
  93.    <constructor-arg type=”int” value=”${user_failedattempt}”></constructor-arg>
  94. </bean>
  95.  
  96. <!– Set authentication failure url here –>
  97. <bean id=”customAuthenticationFailureHandler” class=”org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler”
  98.    p:defaultFailureUrl=”/loginfailed”/>
  99.  
  100. <!– Set authentication success url here –>
  101. <bean id=”customAuthenticationSuccessHandler” class=”org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler”
  102.    p:defaultTargetUrl=”/submitLogin” />
  103.  
  104. <!– Filter required by concurrent session handling package The ConcurrentSessionFilter requires two properties, sessionRegistry, which generally points to an instance of SessionRegistryImpl, and expiredUrl, which points to the page to display when a session has expired. –>
  105. <bean id=”concurrencyFilter” class=”org.springframework.security.web.session.ConcurrentSessionFilter” p:expiredUrl=”/sessionexpired” >
  106.    <property name=”sessionRegistry” ref=”sessionRegistry” />
  107. </bean>
  108.  
  109. <!– Defines a concrete concurrent control strategy Checks whether the user should be allowed to proceed, by comparing the number of sessions they already have active with the configured maximumSessions value. The SessionRegistry is used as the source of data on authenticated users and session data. –>
  110. <bean id=”sas” class=”org.springframework.security.web.authentication.session.ConcurrentSessionControlStrategy”
  111.    p:maximumSessions=”${max_Sessions}” p:exceptionIfMaximumExceeded=”true”>
  112.    <constructor-arg name=”sessionRegistry” ref=”sessionRegistry”/>
  113. </bean>
  114.  
  115. <!– Maintains a registry of SessionInformation instances –>
  116. <bean id=”sessionRegistry” class=”org.springframework.security.core.session.SessionRegistryImpl”/>
  117.  
  118. <!– The AuthenticationEntryPoint is responsible for redirecting the user to a particular page, like a login page, whenever the server sends back a response requiring authentication –>
  119. <bean id=”authenticationEntryPoint” class=”org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint” p:loginFormUrl=”/login”/>
  120.  
  121. <!– The tag below has no use but Spring Security needs it to autowire the parent property of org.springframework.security.authentication.ProviderManager. Otherwise we get an error A probable bug.–>
  122. <security:authentication-manager/>
  123. </beans>
  124.  

CustomAuthenticationFilter.java

  1. import java.util.ArrayList;
  2. import java.util.Collection;
  3. import java.util.HashMap;
  4. import java.util.Iterator;
  5. import java.util.List;
  6. import java.util.Map;
  7. import javax.servlet.http.HttpSession;
  8. import org.hibernate.Query;
  9. import org.hibernate.Session;
  10. import org.hibernate.SessionFactory;
  11. import org.springframework.security.core.Authentication;
  12. import org.springframework.security.core.AuthenticationException;
  13. import org.springframework.security.core.GrantedAuthority;
  14. import org.springframework.security.core.authority.GrantedAuthorityImpl;
  15. import org.springframework.web.context.request.RequestContextHolder;
  16. import org.springframework.web.context.request.ServletRequestAttributes;
  17. import org.springframework.security.authentication.AuthenticationManager;
  18. import org.springframework.security.authentication.BadCredentialsException;
  19. import org.springframework.security.authentication.DisabledException;
  20. import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
  21. public class CustomAuthenticationFilter implements AuthenticationManager {
  22.  
  23.    private SessionFactory sessionFactory;
  24.    private int failedloginattempt;
  25.    public CustomAuthenticationFilter(SessionFactory sessionFactory, int failedattempt) {
  26.       this.sessionFactory = sessionFactory;
  27.       this.failedloginattempt = failedloginattempt;
  28.    }
  29.  
  30.    @Override
  31.    public Authentication authenticate(Authentication a) throws AuthenticationException {
  32.       Session session = sessionFactory.openSession();
  33.       String loginId = null;
  34.       String password = null;
  35.       String userType = null;
  36.       int failedAttempts = 0;
  37.  
  38.       StringBuilder hqlQuery = new StringBuilder();
  39.       hqlQuery.append(“select new map(lm.loginName as loginName,lm.loginPassword as passwrd,utm.userType as userType,lm.failedAttempt as failedAttempt) “);
  40.       hqlQuery.append(” from login lm, usermain utm “);
  41.       hqlQuery.append(” where lm.userTypeId=utm.userTypeId and lm.loginName=:loginName”);
  42.  
  43.       // Retrieve user details from database
  44.       Query query = session.createQuery(hqlQuery.toString());
  45.       query.setString(“loginName”, a.getName());
  46.  
  47.       List resultSetList = query.list();
  48.       Iterator it = resultSetList.iterator();
  49.  
  50.       // Here’s the main logic of this custom authentication manager
  51.       if (resultSetList != null && !resultSetList.isEmpty()) {
  52.          while (it.hasNext()) {
  53.             Map resultMap = (HashMap) it.next();
  54.             loginId = resultMap.get(“loginName”).toString();
  55.             password = resultMap.get(“passwrd”).toString();
  56.             userType = resultMap.get(“userType”).toString();
  57.             failedAttempts = Integer.parseInt(resultMap.get(“failedAttempt”).toString());
  58.          }
  59.  
  60.          if (loginId.equals(a.getName())) {
  61.             if (failedAttempts == failedloginattempt) {
  62.                throw new DisabledException(“User is disabled”);
  63.             } else {
  64.                if (password.equals(a.getCredentials().toString())) {
  65.                   return new UsernamePasswordAuthenticationToken(a.getPrincipal(), a.getCredentials(), getAuthorities(userType));
  66.                } else {
  67.                   throw new BadCredentialsException(“Bad credentials”);
  68.                }
  69.             }
  70.          } else {
  71.             throw new BadCredentialsException(“Bad credentials”);
  72.          }
  73.       } else {
  74.          throw new BadCredentialsException(“Bad credentials”);
  75.       }
  76.    }
  77.  
  78.    /**
  79.    * Retrieves the correct ROLE type depending on the access level, where access level is an String.
  80.    *
  81.    * @param access an string value representing the access of the user
  82.    * @return collection of granted authorities
  83.    */
  84.    public Collection getAuthorities(String access) {
  85.       List authList = new ArrayList();
  86.  
  87.       if (access.equals(“TEACHER”)) {
  88.          authList.add(new GrantedAuthorityImpl(“ROLE_TEACHER”));
  89.       }
  90.       if (access.equals(“CLERK”)) {
  91.          authList.add(new GrantedAuthorityImpl(“ROLE_CLERK”));
  92.       }
  93.       if (access.equals(“STUDENT”)) {
  94.          authList.add(new GrantedAuthorityImpl(“ROLE_STUDENT”));
  95.       }
  96.       return authList;
  97.    }
  98. }
View My Stats