SpringSecurityOauth2.0實(shí)現(xiàn)短信驗(yàn)證碼登錄示例_第1頁
SpringSecurityOauth2.0實(shí)現(xiàn)短信驗(yàn)證碼登錄示例_第2頁
SpringSecurityOauth2.0實(shí)現(xiàn)短信驗(yàn)證碼登錄示例_第3頁
SpringSecurityOauth2.0實(shí)現(xiàn)短信驗(yàn)證碼登錄示例_第4頁
SpringSecurityOauth2.0實(shí)現(xiàn)短信驗(yàn)證碼登錄示例_第5頁
全文預(yù)覽已結(jié)束

下載本文檔

版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進(jìn)行舉報或認(rèn)領(lǐng)

文檔簡介

1、SpringSecurityOauth2.0實(shí)現(xiàn)短信驗(yàn)證碼登錄示例本文介紹了SpringSecurityOauth2現(xiàn)短信驗(yàn)證碼登錄示例,分享給大家,具體如下:* authorlengleng* date2018/1/9手機(jī)號登錄令牌publicclassMMobileAuthenticationTokenextendsAbstractAuthenticationTokenprivatestaticfinallongserialVersionUID=SpringSecurityCoreVersion.SERIAL_VERSIOprivatefinalObjectprincipal;public

2、MobileAuthenticationToken(Stringmobile)super(null);this.principal=mobilesetAuthenticated(false)publicileAuthenticationen(Objectprincipal,ectionauthoritiesuper(authorities);this.principal=principalsuper.setAuthenticated(truepublicObjectgetPrincipareturnthis.principal;OverridepublicObjectgetCredentiar

3、eturnnull;publicvoidsetAuthenticated(booleanisAuthenticated)throwsIllegalArgumentExceptionif(isAuthenticated)thrownewIllegalArgumentException(Cannotsetthistokentotrusted-useconstructorwhichtakesaGrantedAuthoritylistsuper.setAuthenticated(false);OverridepublicvoideraseCredentiasuper.eraseCredentials(

4、)手機(jī)號登錄校驗(yàn)邏輯/*authorlengleng*date2018/1/9* 手機(jī)號登錄校驗(yàn)邏輯*/publicclassMobileAuthenticationProviderimplementsAuthenticationProviderprivateUserServiceuserService;OverridepublicAuthenticationauthenticate(Authenticationauthentication)throwsAuthenticationExceptionMobileAuthenticationTokenmobileAuthenticationTok

5、en=(MobileAuthenticationToken)authentication;UserVouserVo=userService.findUserByMobile(String)mobileAuthenticationToken.getPrincipal();UserDetailsImpluserDetails=buildUserDeatils(userVo);if(userDetails=null)thrownewlnternalAuthenticationServiceException(手機(jī)號不存在:+mobileAuthenticationToken.getPrincipal

6、();MobileAuthenticationTokenauthenticationToken=newMobileAuthenticationToken(userDetails,userDetails.getAuthorities();authenticationToken.setDetails(mobileAuthenticationToken.getDetails();returnauthenticationToken;privateUserDetailsImplbuildUserDeatils(UserVouserVo)returnnewUserDetailsImpl(userVo);O

7、verridepublicbooleansupports(Classauthentication)returnMobileAuthenticationToken.class.isAssignableFrom(authentication);publicUserServicegetUserService()returnuserService;publicvoidsetUserService(UserServiceuserService)this.userService=userService;登錄過程filter處理/* authorlengleng* date2018/1/9*手機(jī)號登錄驗(yàn)證f

8、ilter*/publicclassMobileAuthenticationFilterextendsAbstractAuthenticationProcessingFilterpublicstaticfinalStringSPRING_SECURITY_FORM_MOBILE_KEY=mobile;privateStringmobileParameter=SPRING_SECURITY_FORM_MOBILE_KEY;privatebooleanpostOnly=true;publicMobileAuthenticationFilter()super(newAntPathRequestMat

9、cher(SecurityConstants.MOBILE_TOKEN_URL,POST);publicAuthenticationattemptAuthentication(HttpServletRequestrequest,HttpServletResponseresponse)throwsAuthenticationExceptionif(postOnly&!request.getMethod().equals(HttpMethod.POST.name()thrownewAuthenticationServiceException(Authenticationmethodnotsuppo

10、rted:+request.getMethod();Stringmobile=obtainMobile(request);if(mobile=null)mobile=;mobile=mobile.trim();MobileAuthenticationTokenmobileAuthenticationToken=newMobileAuthenticationToken(mobile);setDetails(request,mobileAuthenticationToken);returnthis.getAuthenticationManager().authenticate(mobileAuth

11、enticationToken);protectedStringobtainMobile(HttpServletRequestrequest)returnrequest.getParameter(mobileParameter);protectedvoidsetDetails(HttpServletRequestrequest,MobileAuthenticationTokenauthRequest)authRequest.setDetails(authenticationDetailsSource.buildDetails(request);publicvoidsetPostOnly(boo

12、leanpostOnly)this.postOnly=postOnly;publicStringgetMobileParameter()returnmobileParameter;publicvoidsetMobileParameter(StringmobileParameter)this.mobileParameter=mobileParameter;publicbooleanisPostOnly()returnpostOnly;生產(chǎn)token位置/* authorlengleng* date2018/1/8*手機(jī)號登錄成功,返回oauthtoken*/Componentpublicclas

13、sMobileLoginSuccessHandlerimplementsorg.springframework.security.web.authentication.AuthenticationSuccessHandlerprivateLoggerlogger=LoggerFactory.getLogger(getClass();AutowiredprivateObjectMapperobjectMapper;AutowiredprivateClientDetailsServiceclientDetailsService;AutowiredprivateAuthorizationServer

14、TokenServicesauthorizationServerTokenServices;OverridepublicvoidonAuthenticationSuccess(HttpServletRequestrequest,HttpServletResponseresponse,Authenticationauthentication)Stringheader=request.getHeader(Authorization);if(header=null|!header.startsWith(Basic)thrownewUnapprovedClientAuthenticationExcep

15、tion(請求頭中client信息為空);tryStringtokens=extractAndDecodeHeader(header);asserttokens.length=2;StringclientId=tokens0;StringclientSecret=tokens1;JSONObjectparams=newJSONObject();params.put(clientId,clientId);params.put(clientSecret,clientSecret);params.put(authentication,authentication);ClientDetailsclie

16、ntDetails=clientDetailsService.loadClientByClientId(clientId);TokenRequesttokenRequest=newTokenRequest(MapUtil.newHashMap(),clientId,clientDetails.getScope(),mobile);OAuth2RequestoAuth2Request=tokenRequest.createOAuth2Request(clientDetails);OAuth2AuthenticationoAuth2Authentication=newOAuth2Authentic

17、ation(oAuth2Request,authentication);OAuth2AccessTokenoAuth2AccessToken=authorizationServerTokenServices.createAccessToken(oAuth2Authentication);I(獲取token成功:,oAuth2AccessToken.getValue();response.setCharacterEncoding(CommonConstant.UTF8);response.setContentType(CommonConstant.CONTENT_TYPE);

18、PrintWriterprintWriter=response.getWriter();printWriter.append(objectMapper.writeValueAsString(oAuth2AccessToken);catch(IOExceptione)thrownewBadCredentialsException(Failedtodecodebasicauthenticationtoken);/* Decodestheheaderintoausernameandpassword.* throwsBadCredentialsExceptioniftheBasicheaderisno

19、tpresentorisnotvalid* Base64*/privateStringextractAndDecodeHeader(Stringheader)throwsIOExceptionbytebase64Token=header.substring(6).getBytes(UTF-8);bytedecoded;trydecoded=Base64.decode(base64Token);catch(IllegalArgumentExceptione)thrownewBadCredentialsException(Failedtodecodebasicauthenticationtoken

20、);Stringtoken=newString(decoded,CommonConstant.UTF8);intdelim=token.indexOf(:);if(delim=-1)thrownewBadCredentialsException(Invalidbasicauthenticationtoken);returnnewStringtoken.substring(0,delim),token.substring(delim+1);配置以上自定義/* authorlengleng* date2018/1/9*手機(jī)號登錄配置入口*/ComponentpublicclassMobileSec

21、urityConfigurerextendsSecurityConfigurerAdapterAutowiredprivateMobileLoginSuccessHandlermobileLoginSuccessHandler;AutowiredprivateUserServiceuserService;Overridepublicvoidconfigure(HttpSecurityhttp)throwsExceptionMobileAuthenticationFiltermobileAuthenticationFilter=newMobileAuthenticationFilter();mo

22、bileAuthenticationFilter.setAuthenticationManager(http.getSharedObject(AuthenticationManager.class);mobileAuthenticationFilter.setAuthenticationSuccessHandler(mobileLoginSuccessHandler);MobileAuthenticationProvidermobileAuthenticationProvider=newMobileAuthenticationProvider();mobileAuthenticationPro

23、vider.setUserService(userService);http.authenticationProvider(mobileAuthenticationProvider).addFilterAfter(mobileAuthenticationFilter,UsernamePasswordAuthenticationFilter.class);在springsecurity配置上邊定一個的那個聚合配置/* authorlengleng* date2018年01月09日14:01:25* 認(rèn)證服務(wù)器開放接口配置*/ConfigurationEnableResourceServerpublicclassRes

溫馨提示

  • 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
  • 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
  • 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負(fù)責(zé)。
  • 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時也不承擔(dān)用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。

最新文檔

評論

0/150

提交評論