版權(quán)說(shuō)明:本文檔由用戶(hù)提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請(qǐng)進(jìn)行舉報(bào)或認(rèn)領(lǐng)
文檔簡(jiǎn)介
第SpringBoot訪(fǎng)問(wèn)安全之認(rèn)證和鑒權(quán)詳解目錄攔截器認(rèn)證鑒權(quán)在web應(yīng)用中有大量場(chǎng)景需要對(duì)用戶(hù)進(jìn)行安全校,一般人的做法就是硬編碼的方式直接埋到到業(yè)務(wù)代碼中,但可曾想過(guò)這樣做法會(huì)導(dǎo)致代碼不夠簡(jiǎn)潔(大量重復(fù)代碼)、有個(gè)性化時(shí)難維護(hù)(每個(gè)業(yè)務(wù)邏輯訪(fǎng)問(wèn)控制策略都不相同甚至差異很大)、容易發(fā)生安全泄露(有些業(yè)務(wù)可能不需要當(dāng)前登錄信息,但被訪(fǎng)問(wèn)的數(shù)據(jù)可能是敏感數(shù)據(jù)由于遺忘而沒(méi)有受到保護(hù))。
為了更安全、更方便的進(jìn)行訪(fǎng)問(wèn)安全控制,我們可以想到的就是使用springmvc的攔截器(HandlerInterceptor),但其實(shí)更推薦使用更為成熟的springsecurity來(lái)完成認(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)的方法,可以通過(guò)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)行頁(yè)面渲染),有機(jī)會(huì)修改ModelAndView
voidpostHandle(HttpServletRequestrequest,HttpServletResponseresponse,Objecthandler,ModelAndViewmodelAndView)throwsException;
*Callbackaftercompletionofrequestprocessing,thatis,afterrendering
*theview.Willbecalledonanyoutcomeofhandlerexecution,thusallows
*forproperresourcecleanup.
*在DispatcherServlet完全處理完請(qǐng)求后被調(diào)用,可用于清理資源等。返回處理(已經(jīng)渲染了頁(yè)面)
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登錄信息中獲取用戶(hù)信息失?。≡敿?xì)錯(cuò)誤信息:%s",e);
thrownewServletException("從SSO登錄信息中獲取用戶(hù)信息失?。?,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("獲取登錄用戶(hù)信息失?。?);
returntrue;
@Override
publicvoidpostHandle(HttpServletRequestrequest,HttpServletResponseresponse,Objecthandler,ModelAndViewmodelAndView)throwsException{
@Override
publicvoidafterCompletion(HttpServletRequestrequest,HttpServletResponseresponse,Objecthandler,Exceptionex)throwsException{
}
認(rèn)證
確認(rèn)一個(gè)訪(fǎng)問(wèn)請(qǐng)求發(fā)起的時(shí)候背后的用戶(hù)是誰(shuí),他的用戶(hù)信息是怎樣的。在springsecurity里面認(rèn)證支持很多種方式,最簡(jiǎn)單的就是用戶(hù)名密碼,還有LDAP、OpenID、CAS等等。
而在我們的系統(tǒng)里面,用戶(hù)信息需要通過(guò)kxtx-sso模塊進(jìn)行獲取。通過(guò)sso認(rèn)證比較簡(jiǎn)單,就是要確認(rèn)用戶(hù)是否通過(guò)會(huì)員系統(tǒng)登錄,并把登錄信息包裝成授權(quán)對(duì)象放到SecurityContext中,通過(guò)一個(gè)filter來(lái)完成:
@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)境允許匿名用戶(hù)訪(fǎng)問(wè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. 本站所有資源如無(wú)特殊說(shuō)明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請(qǐng)下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請(qǐng)聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶(hù)所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁(yè)內(nèi)容里面會(huì)有圖紙預(yù)覽,若沒(méi)有圖紙預(yù)覽就沒(méi)有圖紙。
- 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫(kù)網(wǎng)僅提供信息存儲(chǔ)空間,僅對(duì)用戶(hù)上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對(duì)用戶(hù)上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對(duì)任何下載內(nèi)容負(fù)責(zé)。
- 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請(qǐng)與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶(hù)因使用這些下載資源對(duì)自己和他人造成任何形式的傷害或損失。
最新文檔
- 三坐標(biāo)測(cè)量機(jī)實(shí)操手冊(cè):Mizar Gold 設(shè)備人形機(jī)器人零件檢測(cè)避坑指南
- 遼寧省葫蘆島市2026屆高三上學(xué)期1月期末考試英語(yǔ)試卷(含答案無(wú)聽(tīng)力音頻無(wú)聽(tīng)力原文)
- 廣東省江門(mén)市2026屆九年級(jí)上學(xué)期1月期末考試英語(yǔ)試卷(含答案無(wú)聽(tīng)力原文及音頻)
- 化工企業(yè)屬地管理培訓(xùn)
- 飛行安全管理課件
- 11月進(jìn)出口數(shù)據(jù)點(diǎn)評(píng):出口強(qiáng)在中游
- 飛機(jī)調(diào)試技術(shù)專(zhuān)家
- 飛機(jī)知識(shí)講解課件
- 2026年廣安市教育體育系統(tǒng)公開(kāi)考核招聘體育專(zhuān)業(yè)技術(shù)人員備考考試題庫(kù)及答案解析
- 2026甘肅嘉峪關(guān)市信訪(fǎng)局招聘公益性崗位人員筆試備考試題及答案解析
- 情趣用品項(xiàng)目計(jì)劃書(shū)
- 2025年中考語(yǔ)文文言文真題匯編47份(分師生版)
- DBJ∕T 15-106-2015 頂管技術(shù)規(guī)程
- 湖北省咸寧市2025-2026學(xué)年物理高二上期末復(fù)習(xí)檢測(cè)試題含解析
- 2025年煤層氣開(kāi)發(fā)行業(yè)分析報(bào)告及未來(lái)發(fā)展趨勢(shì)預(yù)測(cè)
- 全民健身中心建設(shè)工程施工方案
- 傳統(tǒng)文化音樂(lè)課題申報(bào)書(shū)
- GB/T 21526-2025結(jié)構(gòu)膠粘劑粘接前金屬和塑料表面處理導(dǎo)則
- 天然氣管道應(yīng)急搶修技術(shù)方案
- (2025年標(biāo)準(zhǔn))情侶欠錢(qián)協(xié)議書(shū)
- 長(zhǎng)租公寓消防知識(shí)培訓(xùn)課件
評(píng)論
0/150
提交評(píng)論