javascript
Spring Security——实现登录后跳转到登录前页面
基本概念
暫無(wú)。
官方文檔
https://docs.spring.io/spring-security/site/docs/5.3.1.BUILD-SNAPSHOT/reference/html5/#nsa-form-login
https://docs.spring.io/autorepo/docs/spring-security/3.2.4.RELEASE/apidocs/org/springframework/security/web/authentication/SavedRequestAwareAuthenticationSuccessHandler.html
API
SavedRequestAwareAuthenticationSuccessHandler:身份驗(yàn)證成功策略,可以利用身份驗(yàn)證成功策略,該策略DefaultSavedRequest可能已由會(huì)話存儲(chǔ)在會(huì)話中ExceptionTranslationFilter。當(dāng)此類(lèi)請(qǐng)求被攔截并需要進(jìn)行身份驗(yàn)證時(shí),將存儲(chǔ)請(qǐng)求數(shù)據(jù)以記錄身份驗(yàn)證過(guò)程開(kāi)始之前的原始目的地,并允許在重定向到相同URL時(shí)重構(gòu)請(qǐng)求。如果合適,此類(lèi)負(fù)責(zé)執(zhí)行重定向到原始URL的操作。
成功進(jìn)行身份驗(yàn)證后,它將根據(jù)以下情況決定重定向目標(biāo):
- 如果該alwaysUseDefaultTargetUrl屬性設(shè)置為true,defaultTargetUrl?則將用于目標(biāo)。任何DefaultSavedRequest存儲(chǔ)在會(huì)話將被刪除。
- 如果targetUrlParameter已在請(qǐng)求中設(shè)置,則該值將用作目的地。任何DefaultSavedRequest都將再次被刪除。
- 如果在SavedRequest中找到了RequestCache(由設(shè)置為在ExceptionTranslationFilter身份驗(yàn)證過(guò)程開(kāi)始之前記錄原始目標(biāo)),則將重定向到該原始目標(biāo)的Url。SavedRequest收到重定向的請(qǐng)求后,該對(duì)象將保持緩存并被拾取(請(qǐng)參閱參考資料SavedRequestAwareWrapper)。
- 如果SavedRequest找不到,它將委派給基類(lèi)。
需求分析
1.通過(guò)登錄頁(yè)登錄后,跳轉(zhuǎn)到后臺(tái)首頁(yè) 。
例如,直接打開(kāi)login.htm登錄,登錄成功后應(yīng)跳轉(zhuǎn)到admin/adminIndex.htm
2.直接訪問(wèn)后臺(tái)其他需要權(quán)限的頁(yè)面,因?yàn)闄?quán)限控制的原因會(huì)被跳轉(zhuǎn)到登錄頁(yè),登錄成功后,應(yīng)在此跳轉(zhuǎn)到想直接訪問(wèn)的頁(yè)面。
例如,admin/b.htm需要權(quán)限才可以訪問(wèn),未登錄的無(wú)權(quán)限用戶直接訪問(wèn)改頁(yè)面,會(huì)被跳轉(zhuǎn)到登錄頁(yè)login.htm,登陸成功后,應(yīng)自動(dòng)跳轉(zhuǎn)到admin/b.htm頁(yè)。
解決方案
當(dāng)在ExceptionTranslationFilter中攔截時(shí),會(huì)調(diào)用HttpSessionRequestCache保存原始的請(qǐng)求信息。
在UsernamePasswordAuthenticationFilter過(guò)濾器登錄成功后,會(huì)調(diào)用SavedRequestAwareAuthenticationSuccessHandler。
自定義一個(gè)MyAuthenticationSuccessHandler類(lèi),繼承自SavedRequestAwareAuthenticationSuccessHandler,并在其中的onAuthenticationSuccess將頁(yè)面重定向至需要的URL。
/*** @Author ShenTuZhiGang* @Version 1.0.0* @Date 2020-03-21 13:10*/@Component public class CustomSavedRequestAwareAuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {@Overridepublic void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws ServletException, IOException {RequestCache requestCache = new HttpSessionRequestCache();SavedRequest savedRequest = requestCache.getRequest(httpServletRequest,httpServletResponse);if(savedRequest != null){//url = savedRequest.getRedirectUrl();}else{getRedirectStrategy().sendRedirect(httpServletRequest,httpServletResponse,"/index");}super.onAuthenticationSuccess(httpServletRequest, httpServletResponse, authentication);} }Spring Security配置文件中需要設(shè)置authentication-success-handler-ref?
<bean id="myAuthenticationSuccessHandler" class="com.jiyufei.security.security.MyAuthenticationSuccessHandler"></bean> <sec:http auto-config="true" use-expressions="false"><sec:intercept-url pattern="/admin/login.htm" access="IS_AUTHENTICATED_ANONYMOUSLY"/><sec:intercept-url pattern="/error/*" access="IS_AUTHENTICATED_ANONYMOUSLY"/><sec:intercept-url pattern="/admin/*.htm" access="ROLE_ADMIN,ROLE_USER"/><sec:intercept-url pattern="/*.htm" access="IS_AUTHENTICATED_ANONYMOUSLY"/><sec:form-login login-page="/admin/login.htm" username-parameter="mail" password-parameter="password"authentication-success-handler-ref="myAuthenticationSuccessHandler" authentication-failure-url="/admin/login.htm?err=1" login-processing-url="/admin/check.htm"/></sec:http>Spring Boot WebSecurity 配置類(lèi)中需要配置.successHandler(customSavedRequestAwareAuthenticationSuccessHandler)
/*** @Author ShenTuZhiGang* @Version 1.0.0* @Date 2020-03-07 16:48*/ @Configuration @EnableGlobalMethodSecurity(prePostEnabled = true) public class MyZSTUWebSecurityConfig extends WebSecurityConfigurerAdapter {@AutowiredIUserService iUserService;@AutowiredCustomFilterInvocationSecurityMetadataSource customFilterInvocationSecurityMetadataSource;@AutowiredCustomAccessDecisionManager customAccessDecisionManager;@AutowiredAuthenticationAccessDeniedHandler authenticationAccessDeniedHandler;@AutowiredCustomSavedRequestAwareAuthenticationSuccessHandler customSavedRequestAwareAuthenticationSuccessHandler;@AutowiredCustomAuthenticationFailureHandler customAuthenticationFailureHandler;@AutowiredCustomAuthenticationSuccessHandler customAuthenticationSuccessHandler;@BeanPasswordEncoder passwordEncoder(){return NoOpPasswordEncoder.getInstance();}@Overridepublic void configure(WebSecurity web){web.ignoring().antMatchers("/index.html","/student/**","/wx/**","/qq/**");}@Overrideprotected void configure(AuthenticationManagerBuilder auth)throws Exception{auth.userDetailsService(iUserService);}@Overrideprotected void configure(HttpSecurity http)throws Exception{http.authorizeRequests().withObjectPostProcessor(new ObjectPostProcessor<FilterSecurityInterceptor>() {@Overridepublic <O extends FilterSecurityInterceptor> O postProcess(O object) {object.setSecurityMetadataSource(customFilterInvocationSecurityMetadataSource);object.setAccessDecisionManager(customAccessDecisionManager);return object;}}).and().formLogin()//.loginPage("/login").loginProcessingUrl("/login").usernameParameter("username").passwordParameter("password").failureHandler(customAuthenticationFailureHandler)//本需求關(guān)鍵句.successHandler(customSavedRequestAwareAuthenticationSuccessHandler).permitAll().and().logout().permitAll().and().csrf().disable().exceptionHandling().accessDeniedHandler(authenticationAccessDeniedHandler);} }?
參考文章
https://www.jianshu.com/p/e1f41b27e902
https://my.oschina.net/jiyufei/blog/1635118
?
總結(jié)
以上是生活随笔為你收集整理的Spring Security——实现登录后跳转到登录前页面的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: docsify——一个神奇的文档站点生成
- 下一篇: Vue + Bootstrap|Elem