SpingSecurity 3 Formログイン


初めてSpringSecurityに触れて、本当に牛Bのものだと感嘆するしかありません.マークちょっと
SpringSecurityを使用するには、まずJarパッケージを追加し、Mavenに次の依存を追加します.

  
  
  
  
  1. <!-- spring3 Security --> 
  2.         <dependency> 
  3.             <groupId>org.springframework.security</groupId> 
  4.             <artifactId>spring-security-core</artifactId> 
  5.             <version>3.1.2.RELEASE</version> 
  6.         </dependency> 
  7.         <dependency> 
  8.             <groupId>org.springframework.security</groupId> 
  9.             <artifactId>spring-security-web</artifactId> 
  10.             <version>3.1.2.RELEASE</version> 
  11.         </dependency> 
  12.         <dependency> 
  13.             <groupId>org.springframework.security</groupId> 
  14.             <artifactId>spring-security-config</artifactId> 
  15.             <version>3.1.2.RELEASE</version> 
  16.         </dependency> 
  17.         <dependency> 
  18.             <groupId>org.springframework.security</groupId> 
  19.             <artifactId>spring-security-taglibs</artifactId> 
  20.             <version>3.1.2.RELEASE</version> 
  21.         </dependency>

 
それからweb.xmlにSpringSecurityのフィルタを追加します
 

  
  
  
  
  1. <!-- Spring Security   --> 
  2.     <filter> 
  3.         <filter-name>springSecurityFilterChain</filter-name> 
  4.         <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class> 
  5.     </filter> 
  6.     <filter-mapping> 
  7.         <filter-name>springSecurityFilterChain</filter-name> 
  8.         <url-pattern>/*</url-pattern> 
  9.     </filter-mapping> 

 
SpringSecurityのプロファイルを追加

  
  
  
  
  1. <!-- spring  --> 
  2. <context-param> 
  3.     <param-name>contextConfigLocation</param-name> 
  4.     <param-value>classpath:spring.xml,classpath:spring-hibernate.xml,classpath:spring-security.xml</param-value> 
  5. </context-param> 

 
classpathの下にspring-security.xmlファイルを新規作成します.セキュリティ設定はspring-securityに配置されます. 
 

  
  
  
  
  1. <?xml version="1.0" encoding="UTF-8"?> 
  2. <beans:beans xmlns="http://www.springframework.org/schema/security" 
  3.     xmlns:beans="http://www.springframework.org/schema/beans" 
  4.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
  5.     xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 
  6.                         http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.1.xsd"> 
  7.     <debug/> 
  8.     <!--  css js  --> 
  9.     <http pattern="*.css" security="none"></http> 
  10.     <http pattern="*.js" security="none"></http> 
  11.      
  12.      
  13.     <http use-expressions="true" auto-config="true"> 
  14.         <!-- patten Url , ant , use-expressions  access  --> 
  15.         <intercept-url pattern="/index.jsp" access="hasRole('ROLE_ADMIN')"/> 
  16.         <intercept-url pattern="/**/*.action" access="hasRole('ROLE_ADMIN')"/> 
  17.         <!--  , Cookie  --> 
  18.         <logout delete-cookies="JSESSIONID"/> 
  19.         <!--  , /login.jsp --> 
  20.         <form-login login-page="/login.jsp" authentication-failure-url="/login.jsp?error=true"/> 
  21.         <!--   --> 
  22.         <session-management> 
  23.         <!--  Session  --> 
  24.         <concurrency-control max-sessions="10" expired-url="/CommonAction!login.action"/> 
  25.          </session-management>   
  26.          <!--  , 1  --> 
  27.          <remember-me token-validity-seconds="84000"/> 
  28.     </http> 
  29.      
  30.     <!--   --> 
  31.     <beans:bean id="encoder" class="org.springframework.security.crypto.password.StandardPasswordEncoder"/> 
  32.      
  33.     <beans:bean name="myUserDetilService" class="com.graduate.security.UserFoundService"> 
  34.         <beans:property name="teacherDao" ref="TeacherDao"></beans:property> 
  35.     </beans:bean> 
  36.  
  37.  
  38.     <authentication-manager> 
  39.     <authentication-provider user-service-ref="myUserDetilService"/> 
  40.   </authentication-manager> 
  41.  
  42. </beans:beans> 

 カスタム・データベース・テーブルを使用するには、UserDetailServiceをカスタマイズする必要があります.現在は比較的小さいため、データベースにはユーザー名、パスワード、ユーザーに対応するロール名しか指定されていません.
 

  
  
  
  
  1. package com.graduate.security; 
  2.  
  3. import java.util.ArrayList; 
  4. import java.util.List; 
  5. import java.util.Set; 
  6.  
  7. import org.slf4j.Logger; 
  8. import org.slf4j.LoggerFactory; 
  9. import org.springframework.security.core.GrantedAuthority; 
  10. import org.springframework.security.core.authority.GrantedAuthorityImpl; 
  11. import org.springframework.security.core.userdetails.User; 
  12. import org.springframework.security.core.userdetails.UserDetails; 
  13. import org.springframework.security.core.userdetails.UserDetailsService; 
  14. import org.springframework.security.core.userdetails.UsernameNotFoundException; 
  15.  
  16. import com.graduate.dao.TeacherDao; 
  17. import com.graduate.models.Teacher; 
  18. import com.graduate.models.Usertype; 
  19.  
  20. public class UserFoundService implements UserDetailsService{ 
  21.  
  22.     private TeacherDao teacherDao; 
  23.      
  24.     private Logger logger=LoggerFactory.getLogger(UserFoundService.class); 
  25.      
  26.     @Override 
  27.     public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { 
  28.         Teacher teacher = teacherDao.getTeacherByName(username); 
  29.         UserDetails user=null
  30.         if(teacher!=null){ 
  31.             String password=teacher.getPassword(); 
  32.             String name=teacher.getName(); 
  33.             List<GrantedAuthority> authority=getTeacherAuthority(teacher); 
  34.             user=new User(name,password,authority); 
  35.             logger.info(" , "+name); 
  36.             return user; 
  37.         }else
  38.             logger.info(" "); 
  39.             throw new UsernameNotFoundException(" "); 
  40.         } 
  41.     } 
  42.  
  43.  
  44.  
  45.  
  46.     private List<GrantedAuthority> getTeacherAuthority(Teacher teacher) { 
  47.         List<GrantedAuthority> grantedAuthority=new ArrayList<GrantedAuthority>(); 
  48.          
  49.         Set<Usertype> roleType = teacher.getRoleType(); 
  50.          
  51.         for(Usertype type:teacher.getRoleType()){ 
  52.             System.out.println(type.getName()); 
  53.             GrantedAuthority auth=new GrantedAuthorityImpl(type.getName()); 
  54.             grantedAuthority.add(auth); 
  55.         } 
  56.         return grantedAuthority; 
  57.     } 
  58.      
  59.  
  60.     public TeacherDao getTeacherDao() { 
  61.         return teacherDao; 
  62.     } 
  63.  
  64.     public void setTeacherDao(TeacherDao teacherDao) { 
  65.         this.teacherDao = teacherDao; 
  66.     } 
  67.      
  68.  

1つのフォームにログインすると、ユーザー名に基づいてユーザー認証情報を取得するカスタムUserDetailのメソッドが呼び出されます.
 
 
フロントログインボックス、対応formは以下の通りです

  
  
  
  
  1. <form id="loginForm" method="post" action="j_spring_security_check"> 
  2.              
  3.          
  4.             <c:if test="${param.error eq 'true'}"><p><label style="color: red; margin-bottom: 10px;"></label></p></c:if> 
  5.             <p> 
  6.                 <label for="user_name"> <br> 
  7.                 </label> 
  8.                 <input type="text"  size="20" value="${sessionScope['SPRING_SECURITY_LAST_USERNAME']}" class="validate[required,minSize[2],maxSize[10] ] inpu" id="user_name" name="j_username" /> 
  9.             </p> 
  10.             <p> 
  11.                 <label for="user_pass"> <br> 
  12.                 <input type="password"  size="20" value="" class="validate[required,minSize[5],maxSize[12]] inpu" id="user_pass" name="j_password" /></label> 
  13.             </p> 
  14.             <div class="clearfix"> 
  15.             <p class="forgetmenot"> 
  16.                 <label for="rememberme"><input type="checkbox" tabindex="90" id="_spring_security_remember_me" name="_spring_security_remember_me"> </label> 
  17.             </p> 
  18.             <p class="nore"> 
  19.                 <a href="#"></a> 
  20.             </p> 
  21.             </div> 
  22.             <p> 
  23.                 <a class="login_btn" href="javascript:;" onclick='$("#loginForm").submit()'> &nbsp;&nbsp; </a> 
  24.             </p> 
  25.         </form>