この記事では、SMS検証コードログインの例を実装するためにSpring Security OAuth2.0を紹介し、次のようにそれらを共有します。
携帯電話番号ログイントークンを定義します
/** * @author length * @date 2018/1/9 *携帯電話番号ログイントークン */パブリッククラスMobileAuthenticationToken extends AbstractAuthenticationToken {private static final long serialversionuid = springsecuritycoreversion.serial_version_uid;プライベートファイナルオブジェクトプリンシパル。 public MobileAuthenticationToken(String Mobile){super(null); this.principal = mobile; setauthenticated(false); } public MobileAuthenticationToken(Object Principal、collection <?extends varnedauthority>当局){super(当局); this.principal =プリンシパル; super.setauthenticated(true); } public Object getPrincipal(){return this.principal; } @Override public Object getCreDentials(){return null; } public void setAuthenticated(boolean isauthenticated)shleg legalargumentexception {if(isauthenticated){show new Illegalargumentexception( "このトークンを信頼できるように設定できません - 代わりに許可されたコンストラクターを使用するコンストラクターを使用する"); } super.setauthenticated(false); } @override public void erasecredentions(){super.erasecredentients(); }}携帯電話番号ログイン検証ロジック
/** * @author length * @date 2018/1/9 *携帯電話番号ログイン検証Logic */public class mobileAuthenticationProvider explence AuthenticationProvider {private userservice userservice; @Override public Authentication Authentication(Authentication Authentication)Slows AuthenticationException {MobiLeAuthenticationToken MobiLeAuthenticationToken =(MobileAuthenticationToken)認証; uservo uservo = userservice.finduserbymobile((string)mobileauthenticationtoken.getprincipal()); userdetailsimpl userdetails = builduserdeatils(uservo); if(userdetails == null){new new internalAuthEnticationServiceException( "携帯電話番号は存在しません:" + mobileAuthenticationToken.getPrincipal()); } mobileAuthenticationToken AuthenticationToken = new MobiLeAuthenticationToken(userDetails、userdetails.getAuthorities()); AuthenticationToken.setDetails(MobiLeAuthenticationToken.getDetails()); AuthenticationTokenを返します。 } private userdetailsimpl builduserdeatils(uservo uservo){return new userdetailsimpl(uservo); } @Override public boolean supports(class <?> authentication){return mobileauthenticationtoken.class.isassignable from(authentication); } public userservice getUserservice(){return userservice; } public void setuserservice(userservice userservice){this.userservice = userservice; }}ログインプロセスフィルター処理
/** * @Author Length * @date 2018/1/9 *携帯電話番号ログイン検証フィルター */public class mobileAuthenticationFilter extends abstractAuthenticationProcessingFilter {public static final string spring_security_form_key = "mobile"; private string mobileparameter = spring_security_form_mobile_key; private boolean postonly = true; public MobileAuthenticationFilter(){super(new antpathRequestMatcher(securityconstants.mobile_token_url、 "post")); } public認証試行承認(httpservletrequest request、httpservletResponse応答)authentivesexception {if(posonly &&!request.getMethod()。 } string mobile = gotainmobile(request); if(mobile == null){mobile = ""; } mobile = mobile.trim(); MobileAuthenticationToken MobiLeAuthenticationToken = new MobiLeAuthenticationToken(Mobile); setDetails(リクエスト、mobileAuthenticationToken); this.getauthenticationManager()。認証(MobiLeAuthenticationToken); }保護された文字列gotedmobile(httpservletrequest request){return request.getParameter(mobileparameter); }保護されたvoid setDetails(httpservletrequest request、mobileAuthenticated authrequest){authrequest.setdetails(authindicationdetailssource.builddetails(request)); } public void setpostonly(boolean postonly){this.postonly = postonly; } public string getMobileParameter(){return mobileparameter; } public void setMobileparameter(String MobileParameter){this.mobileparameter = mobileparameter; } public boolean ispostonly(){return postonly; }}生産トークンの場所
/** * @author length * @date 2018/1/8 *携帯電話番号のログインが成功し、Oauthトークンを返します */ @componentpublic class mobileloginsuccesshandlerはorg.springframework.security.web.authentication.authentication.authenticationsucceshandler {private logger = getger() @autowired private objectmapper objectmapper; @autowired private clientdetailsService clientDetailsService; @autowired private authorizationservertokenservices authorizationservertokenservices; @Override public void onauthenticationsucess(httpservletrequest request、httpservletresponse応答、認証認証){string header = request.getheader( "autherization"); if(header == null ||!header.startswith( "Basic"))){new new approvedclientauthenticationexception( "リクエストヘッダーのクライアント情報は空です"); } try {string [] tokens = extractanddecodeheader(header); tokens.length == 2をアサートします。 string clientId = tokens [0];文字列clientsecret = tokens [1]; jsonobject params = new jsonobject(); params.put( "clientId"、clientId); params.put( "clientsecret"、clientsecret); params.put( "authentication"、authentication); clientDetails clientDetails = clientDetailsService.LoadClientByClientID(clientId); tokenRequest tokenRequest = new tokenRequest(maputil.newhashmap()、clientid、clientDetails.getScope()、 "Mobile"); oauth2request oauth2request = tokenrequest.createouth2request(clientDetails); oauth2authentication oauth2authentication = new oauth2authentication(oauth2request、authentication); OAUTH2ACCESSTOKEN OAUTH2ACCESSTOKEN = authorizationservertokenServices.createAccessToken(oauth2authentication); logger.info( "トークン成功を取得:{}"、oauth2accesstoken.getValue()); Response.setcharacterencoding(commonConstant.utf8); Response.setContentType(commonConstant.content_type); printwriter printwriter = response.getWriter(); printwriter.append(objectmapper.writevalueasstring(oauth2accesstoken)); } catch(ioException e){新しいbadcredentialsexception( "基本認証トークンをデコードできなかった"); }} /***ヘッダーをユーザー名とパスワードにデコードします。 * * @Throws BadCreDentialSeexception Basicヘッダーが存在しないか有効でない場合 * Base64 */ Private String [] ExtractandDecodeheader(String Header)Throws IoException {byte [] base64token = header.substring(6).getBytes( "utf-8");バイト[]デコードされた; try {decoded = base64.decode(base64Token); } catch(IllegalargumentException e){新しいbadcredentialsexception( "基本認証トークンをデコードできなかった"); } string token = new String(decoded、commonConstant.utf8); int delim = token.indexof( ":"); if(delim == -1){新しいbadcredentialsexception( "invalid basic認証トークン"); } new String [] {token.substring(0、delim)、token.substring(delim + 1)}; }}上記のカスタマイズを構成します
// ** * @Author Length * @date 2018/1/9 *携帯電話番号ログイン構成ポータル */ @componentPublic ClassecurityConfigurer extends SecurityConfigurerAdapter <defaultsecurityfilterchain、httpsecurity> {@autowired private mobileloginsuccessler mobileoginsuccescesccescesccescescescescescescescescescescescescescescescescescescescescescysucn @Autowiredプライベートユーザーサービスユーザーサービス。 @Override public void configure(httpsecurity http)throws exception {mobileauthenticationfilter mobileauthenticationfilter = new MobiLeAuthenticationFilter(); MobileAuthenticationFilter.setAuthenticationManager(http.getSharedObject(AuthenticationManager.class)); mobileothenticationfilter.setauthenticationsuccesshandler(mobileloginsuccesshandler); MobileAuthenticationProvider mobileAuthenticationProvider = new MobiLeAuthenticationProvider(); mobileathenticationProvider.setUserservice(userservice); http.authenticationProvider(mobileAuthenticationProvider).addfilterafter(mobileAuthenticationFilter、usernamepasswordauthenticationfilter.class); }}スプリングセキュリティ構成の上に指定されている集約構成
/** * @author length * @date 2018年1月9日14:01:25 *認証サーバーオープンインターフェイス構成 */ @configuration */ @configuration @enableresourceServerpublic resourceserverconfigurationは、resourceserverconfigureradapter {@autowired private filterurlspropertiesconifg filterurlspropertiesconifg; @autowired private mobilesecurityconfigurer mobilesecurityconfigurer; @Override public void configure(httpsecurity http)throws exception {registry .AntMatchers( "/mobile/token")。permissionall().AnyRequest()。 http.apply(mobilesecurityconfigurer); }}使用
コードコピーは次のとおりです。
curl -h "承認:基本cglnonbpzw ==" -d "grant_type = mobile&scope = server&mobile = 17034642119&code =" http:// localhost:9999/auth/mobile/token
ソースコード
gitee.com/log4j/を参照してください
スプリングクラウドとスプリングセキュリティOAUTH2.0に基づいて、エンタープライズレベルの認証と承認が開発され、一般的なサービス監視、リンクトレース、ログ分析、キャッシュ管理、タスクスケジューリング、その他の実装を提供します
ロジック全体は、Spring Securityのusernamepasswordログインモードに実装されており、ソースコードを参照できます。
検証コードの発行と検証のロジックは比較的簡単です。メソッドの後、グローバルフィッターを使用して、リクエストのコードが携帯電話番号と一致するかどうかを判断します。重要なロジックは、トークンのパラメーターです。
上記はこの記事のすべての内容です。みんなの学習に役立つことを願っています。誰もがwulin.comをもっとサポートすることを願っています。