Friday, September 17, 2010

Spring Security 3.0.0 implementaion using database

Spring Security 3.0.3


   
   <?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:d="http://www.springframework.org/schema/security"
    xmlns:util="http://www.springframework.org/schema/util"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xmlns:context="http://www.springframework.org/schema/context"
     xmlns:aop="http://www.springframework.org/schema/aop"
     xmlns:ehcache="http://www.springmodules.org/schema/ehcache"
    xsi:schemaLocation=" http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
                        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.0.xsd
                        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd
                        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
                        http://www.springmodules.org/schema/ehcache http://www.springmodules.org/schema/cache/springmodules-ehcache.xsd"
                         default-lazy-init="true" default-autowire="byName">

<context:component-scan base-package="com.phoenix.rbac" />
<context:annotation-config />
<aop:aspectj-autoproxy />


        <alias name="filterChainProxy" alias="springSecurityFilterChain"/>
        <bean id="filterChainProxy" class="org.springframework.security.web.FilterChainProxy"> 
            <d:filter-chain-map path-type="ant" >
            <d:filter-chain pattern="/**" filters="
                httpSessionContextIntegrationFilter,
                securityContextPersistenceFilter,
                logoutFilter,
                formLoginFilter,
                authenticationProcessingFilter,
                basicAuthenticationFilter,
                customAuthenticationProcessingFilter,
                anonymousAuthenticationFilter,
                securityContextHolderAwareRequestFilter,
                exceptionTranslationFilter,
                filterSecurityInterceptor"/>
            </d:filter-chain-map>
        </bean>

        <bean id="httpSessionContextIntegrationFilter" class="org.springframework.security.web.context.HttpSessionContextIntegrationFilter"/>
   
        <bean id="securityContextPersistenceFilter"
            class="org.springframework.security.web.context.SecurityContextPersistenceFilter">
            <property name='securityContextRepository'>
            <bean class='org.springframework.security.web.context.HttpSessionSecurityContextRepository'>
                <property name='allowSessionCreation' value='true' />
            </bean>
            </property>
        </bean>

        <bean id="basicAuthenticationFilter"
            class="org.springframework.security.web.authentication.www.BasicAuthenticationFilter">
             <property name="authenticationManager" ref="authenticationManager" /> 
             <property name="authenticationEntryPoint" ref="authenticationEntryPoint" />           
        </bean>

        <bean id="authenticationEntryPoint" class="org.springframework.security.web.authentication.www.BasicAuthenticationEntryPoint">
            <property name="realmName" value="Spring Web Realm" />
        </bean>

        <bean id="authenticationProcessingFilter" class="org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter">
            <property name="authenticationManager" ref="authenticationManager"/>
            <property name="filterProcessesUrl" value="/j_spring_security_check"/>
        </bean>

        <bean id="logoutFilter" class="org.springframework.security.web.authentication.logout.LogoutFilter">
            <constructor-arg value="/logout.htm" />
            <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="org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler">
                    <property name="defaultTargetUrl" value="/" />
                </bean>
            </property>
            <property name="sessionAuthenticationStrategy">
                <bean class="org.springframework.security.web.authentication.session.SessionFixationProtectionStrategy" />
            </property>
        </bean>

        <bean id="authenticationManager" class="org.springframework.security.authentication.ProviderManager">
            <property name="providers">
            <list>
                <ref bean="authenticationProvider" />
            </list>
            </property>
        </bean>

        <bean id="authenticationProvider" class="org.springframework.security.authentication.dao.DaoAuthenticationProvider">           
            <property name="userDetailsService" ref="userService" />
        </bean>

        <bean id="userService" class="org.springframework.security.core.userdetails.jdbc.JdbcDaoImpl">
            <property name="dataSource">
                <ref bean="dataSource"/>
            </property>
            <property name="usersByUsernameQuery">
                <value>
                    SELECT u.login_id, password, u.record_status FROM user_master u WHERE u.login_id=?
                </value>
            </property>

            <property name="authoritiesByUsernameQuery">
                <value>
                    SELECT u.login_id, r.role_name FROM user_role ur, user_master u, role_m r WHERE ur.user_id = u.id and ur.role_id = r.id and u.login_id=?
                </value>
            </property>
        </bean>

        <bean id="customAuthenticationProcessingFilter" class="com.security.CustomAuthenticationProcessingFilter">
            <property name="authenticationManager" ref="authenticationManager"/>
            <property name="authenticationFailureHandler">
                <bean class="org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler">
                    <!-- Redirects to this url if authentication fails -->
                    <constructor-arg index="0" value="/login.htm"/>
                    <!--
                        Next 2 params are required to force storing the SPRING_SECURITY_LAST_EXCEPTION into session
                        And we can use them in login.jsp to show an error if authentication fails
                        See the sources of SimpleUrlAuthenticationFailureHandler for details
                    -->
                    <property name="useForward" value="false"/>
                    <property name="allowSessionCreation" value="true"/>
                </bean>
            </property>
            <property name="authenticationSuccessHandler">
                <!-- This implementation restores the original user request -->
                <bean class="org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler"/>
            </property>
        </bean>


        <bean id="securityContextHolderAwareRequestFilter" class="org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter"/>
               
        <!-- If no user authed before this filter, it will authenticate the anonymous user -->
        <!-- In the filter chain it must be after all authentication filters -->
        <bean id="anonymousAuthenticationFilter" class="org.springframework.security.web.authentication.AnonymousAuthenticationFilter">
            <property name="key" value="changeThis"/>
            <property name="userAttribute" value="anonymousUser,ROLE_ANONYMOUS"/>
        </bean>

        <bean id="exceptionTranslationFilter" class="org.springframework.security.web.access.ExceptionTranslationFilter">
            <property name="authenticationEntryPoint">
                <bean class="org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint">
                    <property name="loginFormUrl" value="/login.htm"/>
                </bean>
            </property>
            <property name="accessDeniedHandler">
                <bean class="org.springframework.security.web.access.AccessDeniedHandlerImpl">
                    <property name="errorPage" value="/accessDenied.htm"/>
                </bean>
            </property>
        </bean>

        <bean id="filterSecurityInterceptor" class="org.springframework.security.web.access.intercept.FilterSecurityInterceptor">
            <property name="authenticationManager" ref="authenticationManager" />
            <property name="accessDecisionManager" ref="accessDecisionManager" />
            <property name="securityMetadataSource" ref="mySecureResourceFilter" >
            </property>           
        </bean>

         <bean id="mySecureResourceFilter" init-method="loadResourceDefine" class="com.security.MyFilterSecurityMetadataSource">   
         </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.access.vote.AuthenticatedVoter"/>
                </list>
            </property>
        </bean>

           <!--  <ehcache:annotation-driven /> -->
   
        <bean id="ehCacheManager" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean"/>

    <!-- ****** END SPRING Security Configuration *******-->

</beans>

public class CustomAuthenticationProcessingFilter extends UsernamePasswordAuthenticationFilter {
   
     @Override
        public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
            // Inherited method will obtain the username/password and
            // pass the UsernamePasswordAuthenticationToken into authenticationManager.
            // Then it will be processed by list of authentication providers.
            return super.attemptAuthentication(request, response);
        }

        @Override
        protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, Authentication authResult) throws IOException, ServletException {
            if (SecurityContextHolder.getContext().getAuthentication() != null) {
                throw new IllegalStateException("Some user has already authenticated.");
            }
            // Inherited method will call SecurityContextHolder.getContext().setAuthentication() for authResult
            super.successfulAuthentication(request, response, authResult);
        }


}

public class MyFilterSecurityMetadataSource extends UsernamePasswordAuthenticationFilter implements FilterInvocationSecurityMetadataSource {
   
    private RoleMService RoleMService ; 
    private ResourceMService ResourceMService;
    private ResourceRoleTService ResourceRoleTService;
   
    private String permissionsQuery;
    private UrlMatcher urlMatcher = new AntUrlPathMatcher();
    private static Map&gt; resourceMap = null;
    private static Map&gt; resourceMap1 = null;
    Collection list,list1 = null;
   

    String View_Details=null;
    String Delete_Details=null;
    String Update_Details=null;


   
    public  void loadResourceDefine() throws Exception { 
            resourceMap = new HashMap&gt;();
            try{               
                if(getRoleMService()!=null)
                {
                    System.out.println("The getRoleMService is not null");
                    for (RbacRoleMVO item:RoleMService.findAll()){                                               
                        Collection atts = new ArrayList(); 
                        ConfigAttribute ca = new SecurityConfig(item.getRoleName());
                        System.out.println("The Role Name is :"+item.getRoleName());
                        atts.add(ca);                       
                        List tActionList = ResourceRoleTService.findByRoleID(item.getId());
                        for(RbacResourceRoleTVO tAction:tActionList){
                            try{
                                RbacResourceMVO t=ResourceMService.findById(tAction.getResourceId());
                                resourceMap.put(t.getResourceName(), atts); 
                            }catch(Exception ex){
                                System.out.println("The value of resourceId is :"+tAction.getResourceId());
                            }                                                       
                        } 
                    }                   
                }
                else
                {
                    System.out.println("The getRoleMService is null");
                }
            }catch(Exception e){
                System.out.println("The error is :"+ e.getMessage());
                String str=RoleMService.toString();
                System.out.println("The value of S is :"+ str);               
            }
    }
   
    public Collection getAttributes(Object object) {
        String url=null;
        String[] urlarry=null;
        resourceMap1 = new HashMap&gt;();
        Collection atts = new ArrayList();
        FilterInvocation fi = (FilterInvocation) object;
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        System.out.println("The value of principal is :"+principal);
        Collection Auth = SecurityContextHolder.getContext().getAuthentication().getAuthorities();
        String url1 = ((FilterInvocation)object).getRequestUrl();
        int s=url1.indexOf("?");
        if(s&gt;0){
            urlarry=url1.split("\\?");
            if(urlarry.length&gt;0){
                url=urlarry[0];
            }
        }else{
            url=url1;
        }
        Collection returnCollection=null;
        for(GrantedAuthority GrantAuth:Auth){
            System.out.println("The value of GrantedAuthority value is :"+GrantAuth);
            ConfigAttribute ca = new SecurityConfig(GrantAuth.toString());
            atts.add(ca);
            List rbacRoleMArry=RoleMService.findByWhere("o.roleName='"+GrantAuth+"'");
            if(rbacRoleMArry!=null &amp;&amp; rbacRoleMArry.size()&gt;0){
                System.out.println("The value of Role ID value is :"+rbacRoleMArry.get(0).getId());
                List resourceMVOArry =ResourceMService.findByWhere("o.resourceName='"+url+"'");
                if(resourceMVOArry!=null &amp;&amp; resourceMVOArry.size()&gt;0){
                    List RbacResourceRoleTVOArry=ResourceRoleTService.findByWhere("o.roleId='"+rbacRoleMArry.get(0).getId()+"' and o.resourceId='"+resourceMVOArry.get(0).getId()+"'");
                    if(RbacResourceRoleTVOArry!=null &amp;&amp; RbacResourceRoleTVOArry.size()&gt;0){
                        resourceMap1.put(url, atts);
                        returnCollection = resourceMap1.get( url);
                    }
                }
            }           
        }
        if(returnCollection == null){
             Iterator it = resourceMap.keySet().iterator();
             while(it.hasNext()){
                 String resUrl = it.next();
                 if(urlMatcher.pathMatchesUrl(url, resUrl)){
                     returnCollection= resourceMap.get(resUrl);
                     return returnCollection;
                 }
             }  
        }
        return returnCollection;
    }
   
   
       

    public Collection getAllConfigAttributes() {
      return null;
    }

    public boolean supports(Class clazz) {
      return FilterInvocation.class.isAssignableFrom(clazz);
    }

    public ResourceMService getResourceMService() {
        System.out.println("We are in getResourceMService");
        return ResourceMService;
    }

    public void setResourceMService(ResourceMService ResourceMService) {
        System.out.println("We are in setResourceMService" + ResourceMService.toString());
        this.ResourceMService = ResourceMService;
    }

    public RoleMService getRoleMService() {
        System.out.println("We are in getRoleMService");
        return RoleMService;
    }

    public void setRoleMService(RoleMService RoleMService) {
        System.out.println("We are in setRoleMService" + RoleMService.toString());
        this.RoleMService = RoleMService;
    }

    public ResourceRoleTService getResourceRoleTService() {
        System.out.println("We are in getResourceRoleTService");
        return ResourceRoleTService;
    }

    public void setResourceRoleTService(ResourceRoleTService ResourceRoleTService) {
        System.out.println("We are in setResourceRoleTService" + RoleMService.toString());
        this.ResourceRoleTService = ResourceRoleTService;
    }

}

Thanks
Naveen