Spring Boot 訪問安全之認(rèn)證和鑒權(quán)詳解_第1頁
Spring Boot 訪問安全之認(rèn)證和鑒權(quán)詳解_第2頁
Spring Boot 訪問安全之認(rèn)證和鑒權(quán)詳解_第3頁
Spring Boot 訪問安全之認(rèn)證和鑒權(quán)詳解_第4頁
Spring Boot 訪問安全之認(rèn)證和鑒權(quán)詳解_第5頁
已閱讀5頁,還剩3頁未讀, 繼續(xù)免費(fèi)閱讀

下載本文檔

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

文檔簡介

第SpringBoot訪問安全之認(rèn)證和鑒權(quán)詳解目錄攔截器認(rèn)證鑒權(quán)在web應(yīng)用中有大量場(chǎng)景需要對(duì)用戶進(jìn)行安全校,一般人的做法就是硬編碼的方式直接埋到到業(yè)務(wù)代碼中,但可曾想過這樣做法會(huì)導(dǎo)致代碼不夠簡潔(大量重復(fù)代碼)、有個(gè)性化時(shí)難維護(hù)(每個(gè)業(yè)務(wù)邏輯訪問控制策略都不相同甚至差異很大)、容易發(fā)生安全泄露(有些業(yè)務(wù)可能不需要當(dāng)前登錄信息,但被訪問的數(shù)據(jù)可能是敏感數(shù)據(jù)由于遺忘而沒有受到保護(hù))。

為了更安全、更方便的進(jìn)行訪問安全控制,我們可以想到的就是使用springmvc的攔截器(HandlerInterceptor),但其實(shí)更推薦使用更為成熟的springsecurity來完成認(rèn)證和鑒權(quán)。

攔截器

攔截器HandlerInterceptor確實(shí)可以幫我們完成登錄攔截、或是權(quán)限校驗(yàn)、或是防重復(fù)提交等需求。其實(shí)基于它也可以實(shí)現(xiàn)基于url或方法級(jí)的安全控制。

如果你對(duì)springmvc的請(qǐng)求處理流程相對(duì)的了解,它的原理容易理解。

publicinterfaceHandlerInterceptor{

*Intercepttheexecutionofahandler.CalledafterHandlerMappingdetermined

*anappropriatehandlerobject,butbeforeHandlerAdapterinvokesthehandler.

*在業(yè)務(wù)處理器處理請(qǐng)求之前被調(diào)用。預(yù)處理,可以進(jìn)行編碼、安全控制、權(quán)限校驗(yàn)等處理

*handler:controller內(nèi)的方法,可以通過HandlerMethodmethod=((HandlerMethod)handler);獲取到@RequestMapping

booleanpreHandle(HttpServletRequestrequest,HttpServletResponseresponse,Objecthandler)throwsException;

*Intercepttheexecutionofahandler.CalledafterHandlerAdapteractually

*invokedthehandler,butbeforetheDispatcherServletrenderstheview.

*在業(yè)務(wù)處理器處理請(qǐng)求執(zhí)行完成后,生成視圖之前執(zhí)行。后處理(調(diào)用了Service并返回ModelAndView,但未進(jìn)行頁面渲染),有機(jī)會(huì)修改ModelAndView

voidpostHandle(HttpServletRequestrequest,HttpServletResponseresponse,Objecthandler,ModelAndViewmodelAndView)throwsException;

*Callbackaftercompletionofrequestprocessing,thatis,afterrendering

*theview.Willbecalledonanyoutcomeofhandlerexecution,thusallows

*forproperresourcecleanup.

*在DispatcherServlet完全處理完請(qǐng)求后被調(diào)用,可用于清理資源等。返回處理(已經(jīng)渲染了頁面)

voidafterCompletion(HttpServletRequestrequest,HttpServletResponseresponse,Objecthandler,Exceptionex)throwsException;

//你可以基于有些url進(jìn)行攔截

@Configuration

publicclassUserSecurityInterceptorextendsWebMvcConfigurerAdapter{

@Override

publicvoidaddInterceptors(InterceptorRegistryregistry){

String[]securityUrls=newString[]{"/**"};

String[]excludeUrls=newString[]{"/**/esb/**","/**/dictionary/**"};

registry.addInterceptor(userLoginInterceptor()).excludePathPatterns(excludeUrls).addPathPatterns(securityUrls);

super.addInterceptors(registry);

/**fixed:url中包含//報(bào)錯(cuò)

*org.springframework.security.web.firewall.RequestRejectedException:TherequestwasrejectedbecausetheURLwasnotnormalized.

*@return

@Bean

publicHttpFirewallallowUrlEncodedSlashHttpFirewall(){

DefaultHttpFirewallfirewall=newDefaultHttpFirewall();

firewall.setAllowUrlEncodedSlash(true);

returnfirewall;

@Bean

publicAuthInterceptoruserLoginInterceptor(){

returnnewAuthInterceptor();

publicclassAuthInterceptorimplementsHandlerInterceptor{

publicLoggerlogger=LoggerFactory.getLogger(AuthInterceptor.class);

@Autowired

privateApplicationContextapplicationContext;

publicAuthInterceptor(){

@Override

publicbooleanpreHandle(HttpServletRequestrequest,HttpServletResponseresponse,Objecthandler)throwsException{

LoginUserInfouser=null;

try{

user=(LoginUserInfo)SSOUserUtils.getCurrentLoginUser();

}catch(Exceptione){

logger.error("從SSO登錄信息中獲取用戶信息失??!詳細(xì)錯(cuò)誤信息:%s",e);

thrownewServletException("從SSO登錄信息中獲取用戶信息失?。?,e);

String[]profiles=applicationContext.getEnvironment().getActiveProfiles();

if(!Arrays.isNullOrEmpty(profiles)){

if("dev".equals(profiles[0])){

returntrue;

if(user==null||UserUtils.ANONYMOUS_ROLE_ID.equals(user.getRoleId())){

thrownewServletException("獲取登錄用戶信息失??!");

returntrue;

@Override

publicvoidpostHandle(HttpServletRequestrequest,HttpServletResponseresponse,Objecthandler,ModelAndViewmodelAndView)throwsException{

@Override

publicvoidafterCompletion(HttpServletRequestrequest,HttpServletResponseresponse,Objecthandler,Exceptionex)throwsException{

}

認(rèn)證

確認(rèn)一個(gè)訪問請(qǐng)求發(fā)起的時(shí)候背后的用戶是誰,他的用戶信息是怎樣的。在springsecurity里面認(rèn)證支持很多種方式,最簡單的就是用戶名密碼,還有LDAP、OpenID、CAS等等。

而在我們的系統(tǒng)里面,用戶信息需要通過kxtx-sso模塊進(jìn)行獲取。通過sso認(rèn)證比較簡單,就是要確認(rèn)用戶是否通過會(huì)員系統(tǒng)登錄,并把登錄信息包裝成授權(quán)對(duì)象放到SecurityContext中,通過一個(gè)filter來完成:

@Data

@EqualsAndHashCode(callSuper=false)

publicclassSsoAuthenticationextendsAbstractAuthenticationToken{

privatestaticfinallongserialVersionUID=-1799455508626725119L;

privateLoginUserInfouser;

publicSsoAuthentication(LoginUserInfouser){

super(null);

this.user=user;

@Override

publicObjectgetCredentials(){

return"kxsso";

@Override

publicObjectgetPrincipal(){

returnuser;

@Override

publicStringgetName(){

returnuser.getName();

publicclassSsoAuthenticationProcessingFilterextendsOncePerRequestFilter{

@Override

protectedvoiddoFilterInternal(HttpServletRequestrequest,HttpServletResponseresponse,FilterChainfilterChain)

throwsServletException,IOException{

LoginUserInfouser=(LoginUserInfo)SSOUserUtils.getCurrentLoginUser();

SsoAuthenticationauth=newSsoAuthentication(user);

SecurityContextHolder.getContext().setAuthentication(auth);

filterChain.doFilter(request,response);

@Component

publicclassSsoAuthenticationProviderimplementsAuthenticationProvider{

@Value("${env}")

Stringenv;

@Override

publicAuthenticationauthenticate(Authenticationauthentication)throwsAuthenticationException{

LoginUserInfologinUserInfo=(LoginUserInfo)authentication.getPrincipal();

*DEV環(huán)境允許匿名用戶訪問,方便調(diào)試,其他環(huán)境必須登錄。

if(!UserUtils.ANONYMOUS_ROLE_ID.equals(loginUserInfo.getRoleId())||"dev".equals(env)){

authentication.setAuthenticated(true);

}else{

thrownewBadCredentialsException("請(qǐng)登錄");

returnauthentication;

@Override

publicbooleansupports(Classauthentication){

returnSsoAuthentication.class.equals(authentication);

@Configuration

@EnableWebSecurity

@EnableGlobalMethodSecurity(securedEnabled=true,prePostEnabled=true)

publicclassWebSecurityConfigextendsWebSecurityConfigurerAdapter{

protectedvoidconfigure(HttpSecurityhttp)throwsException{

//關(guān)閉session

http.sessionManagement().sessionCreationPolicy(Sessi

溫馨提示

  • 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. 人人文庫網(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ì)自己和他人造成任何形式的傷害或損失。

最新文檔

評(píng)論

0/150

提交評(píng)論