Tuesday, October 23, 2012

Spring Security

Five minute guide to Spring Security

Web.xml


 <context-param>
  <param-name>contextConfigLocation</param-name>
  <param-value>
   /WEB-INF/spring-app-servlet.xml
   /WEB-INF/applicationContext-security.xml
  </param-value>
 </context-param>
    <filter>
        <filter-name>springSecurityFilterChain</filter-name>
        <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
    </filter>
 
    <filter-mapping>
      <filter-name>springSecurityFilterChain</filter-name>
      <url-pattern>/*</url-pattern>
    </filter-mapping>


Security.xml

    <http auto-config="true" access-denied-page="/accessDenied.jsp">
        <intercept-url pattern="/login.jsp*" filters="none"/>  
        <intercept-url pattern="/admin/editUser.do" access="ROLE_ADMIN"  />
        <intercept-url pattern="/admin/searchUsers.do" access="ROLE_ADMIN"  />
        <intercept-url pattern="/**.do" access="ROLE_USER,ROLE_ADMIN"  />
     <form-login authentication-failure-url="/login.jsp?login_error=1" default-target-url="/home.do"/>
     <logout logout-success-url="/home.do"/>
    </http>
 
    <authentication-provider>
        <jdbc-user-service data-source-ref="dataSource" authorities-by-username-query="select username,authority from users where username=?"/>
    </authentication-provider>


Example:

 <security:global-method-security secured-annotations="enabled" />

 <security:http access-decision-manager-ref="accessDecisionManager">
  <security:access-denied-handler error-page="/signin.mvc?from=ACCESS_DENIED&amp;status=403"/>
  <security:form-login login-page="/signin.mvc?from=ACCESS_DENIED&amp;status=403" default-target-url="/home.mvc" />
  <security:custom-filter position="PRE_AUTH_FILTER" ref="customPreAuthFilter" />
  <security:logout logout-url="/signoutSpring.mvc" logout-success-url="/signin.mvc"/>

  <security:intercept-url pattern="/home.mvc*" access="APPLICATION-ADMIN,APPLICATION-CUSTOMERSERVICE" />
  <security:intercept-url pattern="/dashboard.mvc*" access="APPLICATION-ADMIN,APPLICATION-CUSTOMERSERVICE" />
  <security:intercept-url pattern="/orders.mvc*" access="APPLICATION-CUSTOMERSERVICE" />
 </security:http>

 <bean id="accessDecisionManager" class="org.springframework.security.access.vote.AffirmativeBased">
  <property name="decisionVoters">
   <list>
    <ref bean="roleVoter" />
    <ref bean="authenticatedVoter" />
   </list>
  </property>
 </bean>

 <bean id="roleVoter" class="org.springframework.security.access.vote.RoleVoter">
  <property name="rolePrefix" value="" />
 </bean>

 <bean id="authenticatedVoter" class="org.springframework.security.access.vote.AuthenticatedVoter" />

No comments:

Post a Comment