




版權(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ì)自己和他人造成任何形式的傷害或損失。
最新文檔
- 中國地理試題及答案
- 云南省玉溪市元江縣第一中學(xué)2024-2025學(xué)年高二物理第二學(xué)期期末預(yù)測(cè)試題含解析
- 云南省巧家縣巧家第一中學(xué)2025屆物理高二下期末質(zhì)量跟蹤監(jiān)視試題含解析
- 重慶第二外國語學(xué)校高2025屆生物高二第二學(xué)期期末教學(xué)質(zhì)量檢測(cè)模擬試題含解析
- 車輛運(yùn)輸服務(wù)合同合同解除范本
- 茶葉企業(yè)社會(huì)責(zé)任履行合同
- 柴油運(yùn)輸保險(xiǎn)合同范本
- 2025年快手磁力引擎暑期內(nèi)容營銷招商手冊(cè)
- 餐飲特許經(jīng)營合同(17篇)
- 2024年揭東農(nóng)商銀行微貸中心招聘筆試真題
- 人教B版高中數(shù)學(xué)必修第二冊(cè) 4.7數(shù)學(xué)建?;顒?dòng):生長規(guī)律的描述【課件】
- 娛樂場(chǎng)所安全管理?xiàng)l例
- 超星爾雅學(xué)習(xí)通《社會(huì)科學(xué)方法論(南開大學(xué))》2024章節(jié)測(cè)試答案
- 蘇教版小學(xué)1-6年級(jí)英語單詞
- 托育服務(wù)項(xiàng)目運(yùn)營管理方案
- 江蘇省鹽城市、南京市2024年數(shù)學(xué)高一下期末統(tǒng)考模擬試題含解析
- 生物醫(yī)學(xué)電子學(xué)智慧樹知到期末考試答案章節(jié)答案2024年天津大學(xué)
- 2024回彈法檢測(cè)巖石抗壓強(qiáng)度技術(shù)規(guī)程
- 《水電工程水生生態(tài)調(diào)查與評(píng)價(jià)技術(shù)規(guī)范》(NB-T 10079-2018)
- 2023年哈爾濱市道外區(qū)人民法院聘用制書記員招聘考試試題及答案
- 通信架空光纜工程驗(yàn)收檢查表
評(píng)論
0/150
提交評(píng)論