天天看點

五分鐘帶你玩轉SpringSecurity(十)全網最佳方案,解決無跳轉位址報錯問題

前文說當 http://192.168.19.277:6001/authentication/loginPage 路徑登入後沒有成功後的轉跳位址 是以會報錯 以下代碼可以解決

解決方案

在登入成功後 前文我們配置CustomAuthenticationSuccessHandler  傳回json 這個類調用了onAuthenticationSuccess 那就重寫onAuthenticationSuccess方法

@Component("customAuthenticationSuccessHandler")
public class CustomAuthenticationSuccessHandler extends CustomSavedRequestAwareAuthenticationSuccessHandler {
 
    @Autowired
    Utils utils;
 
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
        Authentication authentication) throws IOException, ServletException {
        SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SysUser sysUser = (SysUser)authentication.getPrincipal();
        logger.info("|" + "使用者" + sysUser.getUsername() + "于" + sd.format(new Date()) + "通過web端登入系統,ip為"
            + utils.getIpAddr() + "。" + "|" + sd.format(new Date()) + "|" + sysUser.getUsername());
        super.onAuthenticationSuccess(request, response, authentication);
    }
}      

重寫onAuthenticationSuccess  大緻意思就是 在登入成功後擷取轉跳位址 如果沒有 我們指定給他一個固定位址 這裡我們指定了百度

public class CustomSavedRequestAwareAuthenticationSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {
 
    protected final Log logger = LogFactory.getLog(this.getClass());
    private RequestCache requestCache = new HttpSessionRequestCache();
 
    public CustomSavedRequestAwareAuthenticationSuccessHandler() {}
 
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
        Authentication authentication) throws ServletException, IOException {
        // 擷取code碼路徑 現在有兩種判斷
        // 1.如果查詢緩存有 定向到緩存 也就是資料庫配置
        // 2.如果前台已經登入 但是退回導緻session丢失 跳轉可道雲頁面
        String targetUrl;
        // 擷取緩存
        SavedRequest savedRequest = this.requestCache.getRequest(request, response);
        if (savedRequest == null) {
            // 跳轉可道雲
            targetUrl = "https://www.baidu.com";
        } else {
            // 跳轉緩存
            targetUrl = savedRequest.getRedirectUrl();
        }
        String targetUrlParameter = this.getTargetUrlParameter();
        if (!this.isAlwaysUseDefaultTargetUrl()
            && (targetUrlParameter == null || !StringUtils.hasText(request.getParameter(targetUrlParameter)))) {
            this.clearAuthenticationAttributes(request);
            this.logger.debug("Redirecting to DefaultSavedRequest Url: " + targetUrl);
            this.getRedirectStrategy().sendRedirect(request, response, targetUrl);
        } else {
            this.requestCache.removeRequest(request, response);
            super.onAuthenticationSuccess(request, response, authentication);
        }
    }
 
    public void setRequestCache(RequestCache requestCache) {
        this.requestCache = requestCache;
    }
}