04.Spring Securityフレーム-----ユーザー登録ブロックの使用

40264 ワード

1.SprigSecurityフレーム紹介
Spring Securityは、Springベースの企業アプリケーションシステムに声明式のセキュリティアクセス制御ソリューションを提供することができるセキュリティフレームワークである.Springアプリケーションのコンテキストに配置できるBeanのセットを提供し、Spring IoC、DI(コントロール反転Inversion of Control、DI:Dependency Injection依存注入)とAOP機能を十分に利用して、アプリケーションシステムに声明式のセキュリティ・アクセス制御機能を提供し、企業システムの安全制御のために多くの重複コードを作成する作業を減少させました.
どんな仕事ができますか?
  • ユーザがログインし、ブロックが登録されていません.もうログインしました.どのページがブロックされていないかを指定します.

  • 2.具体的に使う
  • コンダクタンス(web層に追加)
  • <!--      -->
    		<dependency>
    			<groupId>org.springframework.security</groupId>
    			<artifactId>spring-security-web</artifactId>
    			<version>4.1.0.RELEASE</version>
    		</dependency>
    
    		<dependency>
    			<groupId>org.springframework.security</groupId>
    			<artifactId>spring-security-config</artifactId>
    			<version>4.1.0.RELEASE</version>
    		</dependency>
    
  • web.xmlファイルを変更する(web層に追加する)
  • 	<!--   springSecurity      -->
      	 <context-param>
    		<param-name>contextConfigLocation</param-name>
    		<param-value>classpath:spring-security.xml</param-value>
    	 </context-param>
    	 <listener>
    		<listener-class>
    			org.springframework.web.context.ContextLoaderListener
    		</listener-class>
    	 </listener>
    	 
    	<!--           ,  springSecurity   ,                    ,      ,      ,  springSecurity    -->
    	 <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>/*  
    	 
    
  • spring-security.xmlプロファイルを書く注意ページのラベルは、他のページとは違って、このファイルもこのフレームの主な構成ファイル
  • です.
    <?xml version="1.0" encoding="UTF-8"?>
    <beans:beans xmlns="http://www.springframework.org/schema/security"
    	xmlns:beans="http://www.springframework.org/schema/beans" 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.xsd
    						http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security.xsd">
       
    	<!--              -->
    	<http pattern="/*.html" security="none"></http>
    	<http pattern="/css/**" security="none"></http>
    	<http pattern="/img/**" security="none"></http>
    	<http pattern="/js/**" security="none"></http>
    	<http pattern="/plugins/**" security="none"></http>
    
    	<!--            use-expressions:    SPEL       true -->
    	<http use-expressions="false">
    		<!--        ROLE_USER                      -->
    		<intercept-url pattern="/**" access="ROLE_ADMIN"/>
    		<!--          -->
    		<!-- login-page:    ;   default-target-url:        ;     authentication-failure-url:           -->
    		<!-- always-use-default-target:              (       :default-target-url="/admin/index.html"),                 ,       ,     -->
    		<form-login  login-page="/login.html" default-target-url="/admin/index.html" authentication-failure-url="/login.html" always-use-default-target="true"/>
    		<!--    jsp  ,       ,       html  ,         (     403-->
    		<!-- CSRF(Cross-site request forgery)      ,    “One Click Attack”  Session Riding,
    			     CSRF  XSRF,           。 -->
    		<csrf disabled="true"/>
    		<!--      <iframe>  (     ),            -->
    		<headers>
    			<frame-options policy="SAMEORIGIN"/>
    		</headers>
    		<!--       ,            ,     " /logout ",           :href="../logout"../       admin   ,   webapp  ),          -->
    		<logout/>
    	</http>
    	
    	<!--       -->
    	<authentication-manager>
    		<!--           ,                 (       ) -->
    		<!--                 -->
    		<authentication-provider user-service-ref="userDetailService">	
    			<!--        BCrypt     , ref        -->
    			<password-encoder ref="bcryptEncoder"></password-encoder>
    		</authentication-provider>	
    	</authentication-manager>
    		
    	<!--set-->
    	<beans:bean id="userDetailService" class="com.pinyougou.service.UserDetailsServiceImpl">
    		<!--     sellerService  UserDetailsServiceImpl.java      ,  ref       dubbo  id      -->
    		<beans:property name="sellerService" ref="sellerService"></beans:property>
    	</beans:bean>
    
    	<!--   dubbo   ,   dubbo                 ,  SellerService       -->
    	<dubbo:application name="pinyougou-shop-web" />
    	<dubbo:registry address="zookeeper://192.168.196.134:2181"/>	
    	<dubbo:reference id="sellerService" interface="com.pinyougou.sellergoods.service.SellerService"></dubbo:reference>
    	
    	<!--         -->
    	<beans:bean id="bcryptEncoder" class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder"></beans:bean>
    		
    </beans:beans>
    
  • 認証類UserDetails ServiceImpl.java、この類はspring-security.xmlの配置ファイルに協力して
  • を見ます.
    
    public class UserDetailsServiceImpl implements UserDetailsService {
    
    	//       ,     ,        set()    
    	private SellerService sellerService;
    	
    	public void setSellerService(SellerService sellerService) {
    		this.sellerService = sellerService;
    	}
    
    	//               (      SpringSecurity      )
    	@Override
    	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    
    
    		//         (     ,          )
    		String name = SecurityContextHolder.getContext().getAuthentication().getName();
    
    
    		System.out.println("   UserDetailsServiceImpl");//             
    		
    		//      
    		List<GrantedAuthority> grantAuths=new ArrayList();//           
    		grantAuths.add(new SimpleGrantedAuthority("ROLE_SELLER"));//              
    		
    		//      
    		TbSeller seller = sellerService.findOne(username);//                 
    		if(seller!=null){
    			if(seller.getStatus().equals("1")){//  ,   1     (   :  0:      1:      2:        3:  )
    				return new User(username,seller.getPassword(),grantAuths);
    			}else{
    				return null;
    			}			
    		}else{
    			return null;
    		}
    	}
    
    }
    
    
    
  • htmlページのいくつかの構成
            a.提出ページの「action」住所
    <!-- action        SpringSecurity          -->
    <form class="sui-form" action="/login" method="post" id="loginform">
    
            c.登録ボタン
    <div class="logined">
    	<!--                    ,loginform  <form>    id  -->
    	<a class="sui-btn btn-block btn-xlarge btn-danger" onclick="document:loginform.submit()" target="_blank"> &nbsp;&nbsp; </a>
    </div>
    
            b.ユーザーのログアウトボタン
    <div class="pull-right">
    	<!--  "spring-security.xml"    <logout/>     -->
    	<a href="../logout" class="btn btn-default btn-flat">  </a>
    </div>
    
    2.暗号化
  • Brypt暗号化アルゴリズム
  • ユーザーテーブルのパスワードは、MD 5などの非可逆的アルゴリズムを用いて暗号化されて記憶されています.虹テーブルのクラックを防ぐために、特定の文字列(ドメイン名など)を使って暗号化し、ランダムなsalt(塩値)を使って暗号化されます.特定の文字列はプログラムコードに固定されています.saltはパスワードごとにランダムで、一般的にユーザーテーブルにフィールドを追加して単独で保存するのが面倒くさいです.Bryptアルゴリズムは、saltをランダムにして最終暗号化後のパスワードに混ぜて検証する時も、単独で前のsaltを提供する必要がなく、単独でsalt問題を処理する必要がない.
  • 具体的な使い方は
  • です.
    a.追加方法に暗号化方法を追加する(Seller Controller.javaクラス)
    	/**
    	 *   
    	 * @param seller
    	 * @return
    	 */
    	@RequestMapping("/add")
    	public Result add(@RequestBody TbSeller seller){
    		//    
    		BCryptPasswordEncoder passwordEncoder=new BCryptPasswordEncoder();
    		String password = passwordEncoder.encode(seller.getPassword());//  
    		seller.setPassword(password);
    		
    		try {
    			sellerService.add(seller);
    			return new Result(true, "    ");
    		} catch (Exception e) {
    			e.printStackTrace();
    			return new Result(false, "    ");
    		}
    	}
    
    b.登録方法に復号方法を追加する(spring-security.xmlプロファイル)
    	<!--       -->
    	<authentication-manager>
    		<!--                 -->
    		<authentication-provider user-service-ref="userDetailService">	
    			<!--        BCrypt     , ref        -->
    			<password-encoder ref="bcryptEncoder"></password-encoder>
    		</authentication-provider>	
    	</authentication-manager>
    	
    			<!--         -->
    	<beans:bean id="bcryptEncoder" class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder"></beans:bean>