




下載本文檔
版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請(qǐng)進(jìn)行舉報(bào)或認(rèn)領(lǐng)
文檔簡(jiǎn)介
1、SpringSecurityOauth2.0實(shí)現(xiàn)短信驗(yàn)證碼登錄示例本文介紹了SpringSecurityOauth2現(xiàn)短信驗(yàn)證碼登錄示例,分享給大家,具體如下:* authorlengleng* date2018/1/9手機(jī)號(hào)登錄令牌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ī)號(hào)登錄校驗(yàn)邏輯/*authorlengleng*date2018/1/9* 手機(jī)號(hào)登錄校驗(yàn)邏輯*/publicclassMobileAuthenticationProviderimplementsAuthenticationProviderprivateUserServiceuserService;OverridepublicAuthenticationauthenticate(Authenticationauthentication)throwsAuthenticationExceptionMobileAuthenticationTokenmobileAuthenticationTok
5、en=(MobileAuthenticationToken)authentication;UserVouserVo=userService.findUserByMobile(String)mobileAuthenticationToken.getPrincipal();UserDetailsImpluserDetails=buildUserDeatils(userVo);if(userDetails=null)thrownewlnternalAuthenticationServiceException(手機(jī)號(hào)不存在:+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ī)號(hào)登錄驗(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ī)號(hào)登錄成功,返回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(請(qǐng)求頭中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ī)號(hào)登錄配置入口*/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配置上邊定一個(gè)的那個(gè)聚合配置/* authorlengleng* date2018年01月09日14:01:25* 認(rèn)證服務(wù)器開放接口配置*/ConfigurationEnableResourceServerpublicclassRes
溫馨提示
- 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請(qǐng)下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請(qǐng)聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會(huì)有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
- 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫(kù)網(wǎng)僅提供信息存儲(chǔ)空間,僅對(duì)用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對(duì)用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對(duì)任何下載內(nèi)容負(fù)責(zé)。
- 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請(qǐng)與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶因使用這些下載資源對(duì)自己和他人造成任何形式的傷害或損失。
最新文檔
- 2025年齊齊哈爾貨運(yùn)從業(yè)資格證考試一共多少題
- 安全文明游戲
- 人參訂購(gòu)合同標(biāo)準(zhǔn)文本
- 停車場(chǎng)共用合同標(biāo)準(zhǔn)文本
- 代理銷售合同范例范例
- 激發(fā)幼兒園小班的藝術(shù)潛能展示創(chuàng)意天地計(jì)劃
- 強(qiáng)化倉(cāng)庫(kù)裝卸作業(yè)的安全管理計(jì)劃
- 公裝安全合同標(biāo)準(zhǔn)文本
- 公司出資管理合同標(biāo)準(zhǔn)文本
- 2025零售業(yè)勞動(dòng)合同樣本(合同版本)
- 建筑節(jié)能新路徑:嚴(yán)寒地區(qū)老舊建筑改造
- 2024年寧波樞智交通科技有限公司招聘考試真題
- 數(shù)學(xué)丨湖北省八市2025屆高三下學(xué)期3月聯(lián)考數(shù)學(xué)試卷及答案
- 2024年貴州省普通高中學(xué)業(yè)水平選擇性考試地理試題
- 2024年山東輕工職業(yè)學(xué)院招聘筆試真題
- 2024年中國(guó)工商銀行遠(yuǎn)程銀行中心招聘考試真題
- 護(hù)理查房實(shí)踐報(bào)告
- 2025年文化節(jié)慶活動(dòng)贊助商合作協(xié)議書
- 2025年醫(yī)學(xué)類單招試題及答案
- 3.1《中國(guó)科學(xué)技術(shù)史序言(節(jié)選)》教學(xué)設(shè)計(jì)-【中職專用】高二語文同步講堂(高教版2024拓展模塊上冊(cè))
- 連樂鐵路指導(dǎo)性施工組織設(shè)計(jì)
評(píng)論
0/150
提交評(píng)論