认证成功后,Spring会determineTargetUrl以决定跳转到哪里去:
org.springframework.security.ui.AbstractProcessingFilter
protected String determineTargetUrl(HttpServletRequest request) { // Don't attempt to obtain the url from the saved request if alwaysUsedefaultTargetUrl is set String targetUrl = alwaysUseDefaultTargetUrl ? null : targetUrlResolver.determineTargetUrl(getSavedRequest(request), request, SecurityContextHolder.getContext().getAuthentication()); if (targetUrl == null) { targetUrl = getDefaultTargetUrl(); } return targetUrl; }
有两种方法可以跳到非设置的默认的url去,可看TargetUrlResolverImpl的代码:
public String determineTargetUrl(SavedRequest savedRequest, HttpServletRequest currentRequest, Authentication auth) {
String targetUrl = currentRequest.getParameter(targetUrlParameter); if (StringUtils.hasText(targetUrl)) { try { return URLDecoder.decode(targetUrl, "UTF-8"); } catch (UnsupportedEncodingException e) { throw new IllegalStateException("UTF-8 not supported. Shouldn't be possible"); } } if (savedRequest != null) { if (!justUseSavedRequestOnGet || savedRequest.getMethod().equals("GET")) { targetUrl = savedRequest.getFullRequestUrl(); } } return targetUrl; }
创建SavedRequest并放到Session里的方法如下:
SavedRequest savedRequest = new SavedRequest(request, new PortResolverImpl()); request.getSession(true).setAttribute(AbstractProcessingFilter.SPRING_SECURITY_SAVED_REQUEST_KEY,savedRequest);
这种方式记录下了你当前请求的URL,认证成功后会跳回到这个URL。
而另外一个就是利用:
/j_spring_cas_security_check?"+TargetUrlResolverImpl.DEFAULT_TARGET_PARAMETER+"="+targetUrl;
判断是否已经认证可以这样看:
SecurityContextHolder.getContext().getAuthentication().getPrincipal()!=null&&
!"anonymousUser".equals( SecurityContextHolder.getContext().getAuthentication().getPrincipal())
同时满足表示已经登录。