Spring Securityの使用分類:
Baiduに住んでいた人は皆、Spring Securityの使用方法を知っていると思います。単純なものから深いものまで、4つの使用法があります。
1.データベースはありません。すべてのデータは構成ファイルに記述されます。これは公式ドキュメントのデモでもあります。
2.データベースを使用して、Spring Securityに従ってデータベースのデフォルトコード設計を実装します。つまり、データベースが修正されており、この方法は柔軟性があり、データベースは非常にシンプルで実用性が低いことを意味します。
3.スプリングセキュリティはAcegiとは異なります。デフォルトフィルターを変更することはできませんが、フィルターの挿入をサポートするため、これに基づいて、柔軟に使用するために独自のフィルターを挿入できます。
4。ソースコードを変更するための激しい手段。上記のデフォルトフィルターの変更は、フィルターを交換する構成ファイルを変更するためだけです。これにより、ソースコードが内部に直接変更されますが、これはOO設計原則に適合せず、実用的で利用できません。
この記事では、主にSpring Security Custom Authentication Loginに関する関連コンテンツを紹介します。参照と学習のために共有されます。以下ではあまり言いません。詳細な紹介を一緒に見てみましょう。
1。概要
1.1。導入
Spring Securityは、Spring AOPとサーブレットフィルターに基づくセキュリティフレームワークであり、許可認証などを管理します。
1.2.SPRINGセキュリティカスタム認証プロセス
1)認証プロセス
認証されていないAuthenticationTokensを生成します
↑(情報を取得)(AuthenticationTokenによるとプロバイダーを割り当てる)AuthenticationFilter-> AuthenticationManager-> AuthenticationProvider↓(Authentication)ユーザーデテール(一般的なクエリデータベースの取得)↓(合格)認証に成功した認証が生成されます↓(ストレージ)セキュリティ対応
2)AuthenticationFilterをセキュリティフィルターチェーン(リソースサーバーで構成)に追加します。
http.addfilterbefore(authenticationfilter、abstractprauthenticatedprocessingfilter.class)
または:
http.addfilterafter(authenticationfilter、usernamepasswordauthenticationfilter.class)
2。例としてSMSログインを取ります
2.1。開発環境
2.2。コアコード分析
2.2.1。カスタムログイン認証プロセス
2.2.1.1。カスタム認証ログイントークン
/** *モバイルログイントークン * * @author:catalpaflat */public class mobileloginouthenticationtoken extends abstractauthenticationtoken {private static final long serialversionuid = springsecuritycoreversion.serial_version_uid; private static final logger logger = loggerfactory.getLogger(mobileloginauthenticationtoken.class.getName());プライベートファイナルオブジェクトプリンシパル。 Public MobileLoginauthenticationToken(String Mobile){super(null); this.principal = mobile; this.setauthenticated(false); logger.info( "mobileloginouthenticationtoken setauthenticated-> false roading ..."); } public MobileLoginauthenticationToken(オブジェクトプリンシパル、collection <?extends grantedauthority>当局){super(当局); this.principal =プリンシパル; // super.setauthenticated(true)をオーバーライドするため、スーパーを使用する必要があります。 logger.info( "mobileloginouthenticationtoken setauthenticated-> true loading ..."); } @Override public void setAuthenticated(boolean authenticated){if(authenticated){throw new IllegalargumentException( "このトークンを信頼できるように設定できない - 代わりに補助金リストを取るコンストラクターを使用する"); } super.setauthenticated(false); } @Override public Object getCreDentials(){return null; } @Override public Object getPrincipal(){return this.principal; } @override public void erasecredentions(){super.erasecredentients(); }}注記:
setauthenticated():認証されているかどうかを決定します
2.2.1.1。カスタム認証ログインフィルター
/** *モバイルSMSログインフィルター * * @author:catalpaflat */public class mobileloginauthenticationfilter extends abstractauthectionprocessingfilter {private boolean postonly = true; private static final logger logger = loggerfactory.getLogger(mobileloginauthenticationfilter.class.getName()); @getter @setter private string mobileparametername; public MobileLoginauthenticationFilter(String MobileLoginurl、String MobileParametername、String httpMethod){super(new antpathRequestMatcher(MobileLoginurl、httpmethod)); this.mobileparametername = mobileparametername; logger.info( "mobileloginauthenticationfilterの読み込み..."); } @Override Public Authentication TrageAuthentication(httpservletrequest request、httpservletResponse Response)Slows AuthenticationException、ioException、servletexception {if(postonly &&!request.getmethod()。 request.getMethod()); } // Mobile String Mobile = gotainMobile(request); //トークンMobileLeLoginauthenticationToken authRequest = new MobileLoginouthenticationToken(Mobile); //サブクラスが「詳細」プロパティSetDetailsを設定できるようにします(リクエスト、AuthRequest); this.getauthenticationManager()。authing(authrequest); } / *** IDの設定の詳細認証の詳細* / private void setDetails(httpservletrequest request、mobileloginouthenticationtoken authrequest){authrequest.setdetails(authenticationdetailssource.builddetails(request)); } / ***携帯電話番号を取得* / private文字列gotainMobile(httpservletrequest request){return request.getParameter(mobileparametername); } public void setpostonly(boolean postonly){this.postonly = postonly; }}注: TrageAuthentication()メソッド:
2.2.1.1。カスタム認証ログインプロバイダー
/** *モバイルSMSログイン認証プロバイダー * * @author:catalpaflat */public class mobileloginouthenticationprovider exmments AuthenticationProvider {private static final logger logger = loggerfactory.getLogger(mobileloginauthicationprovider.class.getname()); @getter @setter private userdetailsservice customuserdetailsservice; public MobileLoginouthenticationProvider(){logger.info( "mobileloginouthenticationProviderロード..."); } /***認証* /@Override public Authentication Authentication(Authentication Authentication)Slows AuthenticationException {//フィルターによってカプセル化されたトークン情報を取得してくださいMobileLoginauthenticationToken AuthenticationToken =(MobileLoginauthenticationToken)Authentication; //ユーザー情報(データベース認証)を取得しますuserdetails userdetails = customuserdetailsservice.loduserbyusername(((string)AuthenticationToken.getPrincipal()); //渡されないif(userdetails == null){新しいinternalAuthEnticationServiceException( "ユーザー情報を取得できない"); } // by mobileloginouthenticationtoken authenticationsresult = new MobileLoginauthenticationToken(userDetails、userdetails.getAuthorities()); authenticationResult.setDetails(AuthenticationToken.getDetails());認証を返す; } / ** *トークンタイプによると、どのプロバイダーが使用するかを決定します * / @Overrideパブリックブールサポート(class <?>認証){return mobileloginouthenticationtoken.class.isassignablefrom(authentication); }}注: authenticate()メソッド
2.2.1.1。カスタム認証ログイン認証構成
@configuration(springbeannameconstant.default_custom_mobile_login_authentication_security_config_bn)public class mobileloginouthenticationsecurityconfigはsecurityconfigureradapter <defaustsecurityfilterchain、httpsecurity> loggerfactory.getLogger(mobileloginouthenticationsecurityconfig.class.getName()); @value( "$ {login.mobile.url}")private string defaultmobileloginurl; @value( "$ {login.mobile.parameter}")private string defaultmobileloginparameter; @value( "$ {login.mobile.httpmethod}")private string defaultmobileloginhttpmethod; @autowired private customillconfig customillconfig; @autowired private userdetailsservice customuserdetailsservice; @Autowiredプライベート認証cccessuceshandler customauthenticationsuccesshandler; @autowired private authenticationfailurehandler customauthenticationfailurehandler; public MobileLoginauthenticationsecurityconfig(){logger.info( "mobileloginouthenticationsecurityconfig loading ..."); } @Override public void configure(httpsecurity http)スロー例外{mobilepojo mobile = customymlconfig.getLogins()。getMobile(); string url = mobile.geturl(); string parameter = mobile.getParameter()。getMobile();文字列httpmethod = mobile.gethttpmethod(); MobileLoginauthenticationFilter MobileLoginauthenticationFilter = new MobileLoginauthenticationFilter(stringutils.isblank(url)?defaultmobileLoginurl:url、stringutils.isblank(パラメーター)?defaultmobileeloginurl:defaultilsblank(htppmethodod)? httpmethod); mobilEloginauthenticationfilter.setAuthenticationManager(http.getSharedObject(AuthenticationManager.class)); mobileLoginauthenticationfilter.setAuthenticationsuccesshandler(customAuthenticationsuccesshandler); mobilEloginauthenticationfilter.setAuthenticationFailureHandler(customAuthenticationFailureHandler); mobileLoginauthenticationProvider mobilEloginouthenticationProvider = new MobileLoginouthenticationProvider(); mobileLoginauthenticationProvider.setCustomUserDetailsService(CustomUserDetailsService); http.authenticationProvider(mobileLoginauthenticationProvider).addfilterafter(mobileloginouthenticationfilter、usernamepasswordauthenticationfilter.class); }}注: configure()メソッド
Instantiate AuthenticationFilterとAuthenticationProvider
Spring SecurityにAuthenticationFilterとAuthenticationProviderを追加します。
2.2.2。 Redisに基づいてカスタム検証コードを確認します
2.2.2.1。 Redisに基づくカスタム検証コードフィルター
/** *検証コードフィルター * * @author:catalpaflat */ @component(springbeannameconstant.default_validate_code_filter_bn)public class balidatecodefilterがexpend intivilizingbean {private static final logger = loggeractory.geterfactoryfactory.get.get. @autowired private customillconfig customillconfig; @autowired private redistemplate <object、object> redistemplate; / ***要求されたURLが構成されたURLと一致するかどうかを確認するツールクラスpublic validatecodefilter(){logger.info( "loading validatecodefilter ..."); } @Override Protected void dofilterinternal(httpservletrequest request、httpservletresponse応答、フィルターチェーンフィルターチェーン)Servletexception、ioexception {string url = customillconfig.getLogins()。getMobile()。 if(pathmatcher.match(url、request.getRequesturi())){string deviceId = request.getheader( "deviceId"); if(stringutils.isblank(deviceId)){throw new customexception(httpstatus.not_acceptable.value()、「リクエストの頭にdeviceIdではない」); } string codeparamname = customymlconfig.getLogins()。getMobile()。getParameter()。getCode();文字列code = request.getParameter(codeparamname); if(stringutils.isblank(code)){throw new customexception(httpstatus.not_acceptable.value()、「リクエストのパラメーターのコードではない」); } string key = systemconstant.default_mobile_key_pix + deviceId; SMSCODEPO SMSCODEPO =(SMSCODEPO)redistemplate.opsforvalue()。get(key); if(smscodepo.isexpried()){throw new customexception(httpstatus.bad_request.value()、 "検証コードが期限切れになっています"); } string smscode = smscodepo.getCode(); if(stringutils.isblank(smscode)){throw new Customexception(httpstatus.bad_request.value()、 "検証コードは存在しません"); } if(stringutils.equals(code、smscode)){redistemplate.delete(key); // let it it Go filterchain.dofilter(request、response); } else {throw new Customexception(httpstatus.bad_request.value()、 "検証コードは間違っています"); }} else {// let it it Go filterchain.dofilter(request、response); }}}注: dofilterinternal()
カスタム検証コードフィルター検証
2.2.2.2。スプリングセキュリティフィルターチェーンにカスタム検証コードフィルターを追加する
http.addfilterbefore(validatecodefilter、abstractprouthenticedprocessingfilter.class)
注:認証前処理フィルターに追加する前
3.効果をテストします
最後に、ソースコードアドレスが添付されています:https://gitee.com/catalpaflat/springsecurity.git(ローカルダウンロード)
要約します
上記は、この記事のコンテンツ全体です。この記事の内容には、すべての人の研究や仕事に特定の参照値があることを願っています。ご質問がある場合は、メッセージを残してコミュニケーションをとることができます。 wulin.comへのご支援ありがとうございます。