spring security入門教程

22339 ワード

本文の住所:spring security入門教程本篇の文章はspring security入門としてだけ使って、詳しい内容は自分で関連資料を調べてください.
ディレクトリ:
  • spring security概要
  • アクセス方式
  • ユーザは認証方式
  • を記憶する.
  • 暗号化ポリシー
  • ブロックポリシーを要求する
  • 強制安全性チャネル
  • CSRF
  • を防止する.
  • remember-me機能
  • カスタムログインページ
  • 1、spring security概要
    Spring Securityは、Springベースの企業アプリケーションシステムに声明式のセキュリティアクセス制御ソリューションを提供することができるセキュリティフレームワークである.Springアプリケーションのコンテキストに配置できるBeanのセットを提供し、Spring IoC、DI(コントロール反転Inversion of Control、DI:Dependency Injection依存注入)とAOP機能を十分に利用して、アプリケーションシステムに声明式のセキュリティ・アクセス制御機能を提供し、企業システムの安全制御のために多くの重複コードを作成する作業を減少させました.現在のバージョンは4.2.3です.
    2、アクセス方式
    Spring Securityのアクセス方法は全部で二つあります.注釈方式とxml構成方式に基づいています.二つのアクセス方法を紹介します.まず、スプリングsecurity依存でpom.xmlを導入します.
    
    
        4.0.0
    
        demo.security
        security
        1.0-SNAPSHOT
        war
    
        
            
            4.1.6.RELEASE
            4.0.1.RELEASE
            
            1.7.7
            1.2.17
    
        
    
        
        
        
            org.springframework
            spring-core
            ${spring.version}
        
    
        
            org.springframework
            spring-web
            ${spring.version}
        
        
            org.springframework
            spring-oxm
            ${spring.version}
        
        
            org.springframework
            spring-tx
            ${spring.version}
        
    
        
            org.springframework
            spring-jdbc
            ${spring.version}
        
    
        
            org.springframework
            spring-webmvc
            ${spring.version}
        
        
            org.springframework
            spring-aop
            ${spring.version}
        
    
        
            org.springframework
            spring-context-support
            ${spring.version}
        
    
        
            org.springframework
            spring-test
            ${spring.version}
        
        
            org.springframework.security
            spring-security-core
            ${security.version}
        
    
        
            org.springframework.security
            spring-security-config
            ${security.version}
        
    
        
            org.springframework.security
            spring-security-taglibs
            ${security.version}
        
            
                javax.servlet
                servlet-api
                3.0-alpha-1
                provided
            
            
            
                mysql
                mysql-connector-java
                5.1.30
            
        
    
        
            ROOT
            
                
                    src/main/resources
                    true
                
                
                    config/${env}
                
                
                    src/main/java
                    
                        **/*.xml
                    
                
            
        
    
            
    
    ここで使用するのはservlet 3.0で、servlet 3.0+仕様より、servlet、filter、listenerはweb.xmlに声明する必要はなく、ハードコードで存在し、容器のゼロ配置を実現します.
    2.1、注釈方式に基づく
    第一歩は、Spring Securityを作成するJavaプロファイルクラスです.作成クラスSecurityConfigrationは、WebSecurityConfigrer Adapterを継承して、私たちのアプリケーションのすべてのセキュリティに関する事項(すべてのurl、ユーザ名のパスワードを検証し、フォームのリダイレクトなど)を制御します.
    SecurityConfigration.java
    package com.security.code;
    
    import org.springframework.security.authentication.AuthenticationManager;
    import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
    import org.springframework.security.config.annotation.web.builders.HttpSecurity;
    import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
    import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
    
    import javax.sql.DataSource;
    
    /**
     * 
  • security config
  • * * @author lixin * @create 17/3/22 */ @EnableWebSecurity public class SecurityConfiguration extends WebSecurityConfigurerAdapter{ public AuthenticationManager authenticationManagerBean() throws Exception { return super.authenticationManagerBean(); } /** * user-detail * @param auth * @throws Exception */ @Override public void configure(AuthenticationManagerBuilder auth)throws Exception{ } /** * * @param http * @throws Exception */ @Override public void configure(HttpSecurity http)throws Exception{ } /** * * @param web * @throws Exception */ @Override public void configure(WebSecurity web) throws Exception { } }
    WebSecurityConfigrer Adapterには3つのconfigur方法があります.
    configure(WebSecurity)     ,  Spring Security Filter 
    configure(HttpSecurity)     ,             
    configure(AuthenticationManagerBuilder)     ,  user-detail  
    
    @EnbleWebSecurityコメントはWebセキュリティ機能を有効にします.
    第二ステップは、spring SecurityFilter登録クラスを初期化するもので、ここで使用する方法は、継承クラスAbstractSecurityWebApplizerです.
    package com.security.code;
    
    import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer;
    
    /**
     * 
  • springSecurityFilter
  • * * @author lixin * @create 17/3/22 */ public class SecurityWebApplicationInitializer extends AbstractSecurityWebApplicationInitializer { }
    ここでは何も実現できない.これで、注釈方式によるアクセスが完了しました.xml構成によるアクセスを紹介します.
    2.2、xml構成によるアクセス
    最初のステップは、web.xmlにプロファイルを追加します.
    
        springSecurityFilterChain
        org.springframework.web.filter.DelegatingFilterProxy
      
      
        springSecurityFilterChain
        /*
      
    
    第二ステップは、spring-security.xmlを追加し、appliation.xmlに導入する.
    spring-security.xml
    
    
    
        
            ...
        
    
        
            ..
        
    
    
    
    具体的な配置は後ほど追加されます.xml構成に基づいてこれだけ多くの方に、ユーザの記憶認証方法を紹介します.
    3、ユーザが認証方式を記憶する
    spring securityはユーザ記憶認証に関して非常に柔軟であり、各種データ記憶に基づいてユーザを認証することができる.多くの一般的なユーザーの記憶シーンが内蔵されていますが、以下に様々なシーンを紹介します.
    3.1、メモリベースのユーザ記憶を使用する
    名前からもわかるように、ユーザー名、パスワード、権限などのデータをメモリに保存する方法で、一般的な個人開発テストではこのような方法が使えます.
    注符号化方式:
        /**
         *   user-detail  
         * @param auth
         * @throws Exception
         */
        @Override
        public void configure(AuthenticationManagerBuilder auth)throws Exception{
            //         、  
            auth.inMemoryAuthentication()
                    .withUser("admin").password("admin").roles("ADMIN","USER")
                    .and()
                    .withUser("user").password("user").roles("USER");
        }
    
    コードの中でメソッドauth.inMemoryAuthentication()を通じてAuthentication ManagerBuiderオブジェクトを取得して、二つのユーザadminとuserを同時にパスワードと所有する権限を設定しました.
    ここで注意したいのは、roles()の方法はauthorities()の書き方です.roles()方法によって与えられた値には、「ROLE_u」プレフィックスが付加され、権限としてユーザに付与される.実際には、以下のユーザ構成は上記のプログラムと同じです.
        /**
         *   user-detail  
         * @param auth
         * @throws Exception
         */
        @Override
        public void configure(AuthenticationManagerBuilder auth)throws Exception{
             //         、  
            auth.inMemoryAuthentication()
                    .withUser("admin").password("admin").authorities("ROLE_AMIN","ROLE_USER")
                    .and()
                    .withUser("user").password("user").authorities("ROLE_USER");
    
        }
    
    上記の方法以外にも、ユーザの詳細情報を設定することができる他の方法があります.
    accountExpired(boolean)           
    accountLocked(boolean)           
    and()       
    authorities(GrantedAuthority...)              
    authorities(List extends GrantedAuthority>)              
    authorities(String...)              
    credentialsExpired(boolean)           
    disabled(boolean)           
    password(String)        
    roles(String...)              
    
    xml設定方式:
        
            
                
                    
                    
                
            
        
    
    3.2、データベーステーブルに基づくユーザ記憶認証
    私たちは通常、ユーザーデータを関係データベースに保存し、jdbcを通じてアクセスします.spring securityはjdbcを支持するユーザーストアを使って、下のように構成できます.
    注釈コードに基づいて:
        /**
         *   user-detail  
         * @param auth
         * @throws Exception
         */
        @Override
        public void configure(AuthenticationManagerBuilder auth)throws Exception{
            //          、  
            auth.jdbcAuthentication().dataSource(dataSource)
                    .usersByUsernameQuery("select account,password,true from user where account=?")
                    .authoritiesByUsernameQuery("select account,role from user where account=?");
        }
    
    最初のクエリ文はユーザの基本情報を取得し、第二のクエリ文はユーザ権限データを取得しました.
    xml構成に基づいて:
    
            
                
                
        
    
    3.3、LDAPに基づくユーザ記憶認証
    この方法はテストしていません.興味があれば自分でテストしてもいいです.
    3.4、カスタムユーザ記憶認証の設定
    この方式はより柔軟で、生産環境での使用に適しています.この方式は保存環境に限定されない.カスタムも簡単です.UserDetail Serviceインターフェースを提供するだけで実現できます.
    package com.blog.admin.security;
    
    import com.blog.admin.dao.UserDao;
    import db.model.User;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.security.core.userdetails.UserDetails;
    import org.springframework.security.core.userdetails.UserDetailsService;
    import org.springframework.security.core.userdetails.UsernameNotFoundException;
    import org.springframework.stereotype.Service;
    
    /**
     * 
  • * * @author lixin * @create 17/3/20 */ @Service public class BlogSecurityUserDetailsService implements UserDetailsService{ @Autowired private UserDao userDao; /** * * @param username * @return * @throws UsernameNotFoundException */ public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { User user = userDao.queryByUserName(username); if(user == null)throw new UsernameNotFoundException("user not found"); return new org.springframework.security.core.userdetails.User(user.getAccount(),user.getPassword(),userDao.getUserGrantedAuthoritys(user.getId())); } }
  • 自定义的方式只要实现接口方法loadUserByUsername(String username)即可,返回代表用户的UserDetails对象。调用方式也很简单:

        /**
         *   user-detail  
         * @param auth
         * @throws Exception
         */
        @Override
        public void configure(AuthenticationManagerBuilder auth)throws Exception{
            //     
            auth.userDetailsService(securityUserDetailsService);
        }
    
    xml方式に基づいて:
        
            
            
        
    
    4、暗号化ポリシー
    通常、私たちはパスワードを保存する時は暗号化します.spring securityはデフォルトで3つのパスワード記憶方式を提供しています.また、カスタム暗号化方式も使えます.
  • NoOpPassword Engcoder方式は
  • を保存します.
  • BtPassword Engcoder強力なhash方式の暗号化
  • StanddardPassword Ender SHA-256方式暗号化
  • Password Encersインターフェースのカスタム暗号化方式の注釈符号化方式を実現する:
  •     /**
         *   user-detail  
         * @param auth
         * @throws Exception
         */
        @Override
        public void configure(AuthenticationManagerBuilder auth)throws Exception{
            //          、  
            auth.jdbcAuthentication().dataSource(dataSource)
                    .usersByUsernameQuery("select account,password,true from user where account=?")
                    .authoritiesByUsernameQuery("select account,role from user where account=?")
                    .passwordEncoder(NoOpPasswordEncoder.getInstance());
        }
    
    対応する暗号化例は、方法password Encererによって入力すれば良い.
    xml設定方式:
    
            
                
                
            
        
    
        
    
    5、ブロックポリシーを要求する
    spring securityの重要な機能を紹介します.ブロック戦略をお願いします.spring securityの要求ブロックマッチングには2つのスタイルがあり、antスタイルと正規表現スタイルがあります.符号化方式は、configure(HttpSecurity)を再搭載することにより実現される.
        /**
         *     
         * @param http
         * @throws Exception
         */
        @Override
        public void configure(HttpSecurity http)throws Exception{
            http.authorizeRequests()
                    .antMatchers("/","/css/**","/js/**").permitAll()   //        
                    .antMatchers("/admin/**").access("hasRole('ADMIN')")     //  user         
                    .antMatchers("/user/**").hasAuthority("ROLE_USER");
        }
    
    上ではantスタイルのマッチングを使用していますが、http.regexMatch()メソッドで正規表現スタイルを使用できます.
    対応するxml設定方式:
        
            
            
        
    
    上記の保護要求方法に加えて、保護要求を定義する方法があります.
    access(String)          SpEL        true,     
    anonymous()                
    authenticated()              
    denyAll()                   
    fullyAuthenticated()              (    Remember-me     ),     
    hasAnyAuthority(String...)                    ,     
    hasAnyRole(String...)                    ,     
    hasAuthority(String)               ,     
    hasIpAddress(String)           IP    ,     
    hasRole(String)               ,     
    not()               
    permitAll()          
    rememberMe()          Remember-me     ,     
    
    6、強制安全性通路
    私たちは通常httpを使ってデータを送るので、この方法は安全ではありません.敏感情報についてはhttpsで暗号化して送るのが普通です.spring securityはセキュリティチャネルに対しても一つの方法を提供しています.私たちは構成にrequiresChanelを追加して、urlにhttpsを強制的に使用させることができます.
        /**
         *     
         * @param http
         * @throws Exception
         */
        @Override
        public void configure(HttpSecurity http)throws Exception{
            http.authorizeRequests()
                    .antMatchers("/","/css/**","/js/**").permitAll()   //        
                    .antMatchers("/admin/**").access("hasRole('ADMIN')")     //  user         
                    .antMatchers("/user/**").hasAuthority("ROLE_USER")
                    .and()
                    .requiresChannel().antMatchers("/admin/info").requiresSecure();
        }
    
    いつでも、「/admin/info」に対する要求であれば、spring securityは安全性チャネルが必要だと考え、自動的にhttpsに再配向するように要求します.
    これに対して、https転送が必要でない要求がある場合は、requiresInsecure()を使ってレキシスSecure()の代わりに、http転送を常に使用するように要求します.
    対応xml設定:
        
            
            
            
        
    
    7、CSRF防止
    spring securityはバージョン3.2から始まり、デフォルトではCSRF保護が有効になります.spring securityは同期token方式でCSRF保護機能を実現する.状態変化の要求を遮断してCSRF tokenを確認します.要求にCSRF tokenが含まれていない場合、またはtokenがサーバ端のtokenと一致しない場合、要求は失敗し、CsrfExceptionが例外となります.
    JSPをページテンプレートとして使うなら、非常に簡単に作る必要があります.
    
    
    これでspring securityは自動的にcsrf tokenを生成します.csrf保護をオフにしたいなら、必要なものも簡単です.csrf().disableを呼び出すだけです.いいです
    エンコーディング:
        /**
         *     
         * @param http
         * @throws Exception
         */
        @Override
        public void configure(HttpSecurity http)throws Exception{
            http.authorizeRequests()
                    .antMatchers("/","/css/**","/js/**").permitAll()   //        
                    .antMatchers("/admin/**").access("hasRole('ADMIN')")     //  user         
                    .antMatchers("/user/**").hasAuthority("ROLE_USER")
                    .and().csrf().disable();
        }
    
    対応xml方式:
        
            
            
            
        
    
    8、remember-me機能
    Remember-meは重要な機能です.ユーザは毎回ユーザー名のパスワードを入力してログインしたくないです.spring securityが提供するremember-me機能はとても使いやすいです.この機能を有効にするには、remember Me()メソッドを呼び出すだけでいいです.
        /**
         *     
         * @param http
         * @throws Exception
         */
        @Override
        public void configure(HttpSecurity http)throws Exception{
            http.authorizeRequests()
                    .antMatchers("/","/css/**","/js/**").permitAll()   //        
                    .antMatchers("/admin/**").access("hasRole('ADMIN')")     //  user         
                    .antMatchers("/user/**").hasAuthority("ROLE_USER")
                    .and().rememberMe().key("abc").rememberMeParameter("remember_me").rememberMeCookieName("my-remember-me").tokenValiditySeconds(86400);
        }
    
    パラメータ名、cookieのnameと有効期限も設定できます.対応するxml設定:
        
            
            
            
        
    
    remember-meには様々なパラメータがあります.構成を選択できます.
    ここで注意すべき点があります.ログインページ内のremember-meのinputタグにvalueの値を設定しないでください.そうでないとremember-me機能は有効になりません.
    9、カスタムログインページ
    spring securityはデフォルトの登録ページを提供します.自分の登録ページを使いたいなら、このように設定できます.
    エンコーディング:
        /**
         *     
         * @param http
         * @throws Exception
         */
        @Override
        public void configure(HttpSecurity http)throws Exception{
            http.authorizeRequests()
                    .antMatchers("/","/css/**","/js/**").permitAll()   //        
                    .antMatchers("/admin/**").access("hasRole('ADMIN')")     //  user         
                    .antMatchers("/user/**").hasAuthority("ROLE_USER")
                    .and().formLogin()
                    .loginPage("/login").usernameParameter("username").passwordParameter("password")
                    .and().exceptionHandling().accessDeniedPage("/loginfail");
        }
    
    form Login()メソッドによりカスタム登録ページを使用して、ログインページアドレス、accessDeniePage登録失敗ジャンプアドレスを設定します.
    対応するxml設定:
        
            
            
            
        
    
    ここでspring securityのいくつかの常用機能を紹介しました.書いたのは比較的に粗くて、間違いがあるかもしれません.みんなのフィードバック交流を歓迎します.