Shiro登录成功后,默认返回登录前访问的URL。但是有些时候,这样并不能满足程序的要求,例如要跳出IFrame,要实现这样的要求,可以覆盖FormAuthenticationFilter中的onLoginSuccess方法。
01 | package com.ygsoft.security.shiro; |
03 | import javax.servlet.ServletRequest; |
04 | import javax.servlet.ServletResponse; |
05 | import javax.servlet.http.HttpServletRequest; |
06 | import javax.servlet.http.HttpServletResponse; |
08 | import org.apache.shiro.authc.AuthenticationToken; |
09 | import org.apache.shiro.subject.Subject; |
10 | import org.apache.shiro.web.filter.authc.FormAuthenticationFilter; |
11 | import org.apache.shiro.web.util.WebUtils; |
15 | * @author <a href="mailto:ketayao@gmail.com">ketayao</a> |
17 | * @since 2012-8-7 上午9:20:26 |
20 | public class CaptchaFormAuthenticationFilter extends FormAuthenticationFilter { |
22 | private String captchaParam = SimpleCaptchaServlet.CAPTCHA_KEY; |
24 | public String getCaptchaParam() { |
28 | protected String getCaptcha(ServletRequest request) { |
29 | return WebUtils.getCleanParam(request, getCaptchaParam()); |
33 | protected AuthenticationToken createToken(ServletRequest request, |
34 | ServletResponse response) { |
35 | String username = getUsername(request); |
36 | String password = getPassword(request); |
37 | String captcha = getCaptcha(request); |
38 | boolean rememberMe = isRememberMe(request); |
39 | String host = getHost(request); |
40 | return new CaptchaUsernamePasswordToken(username, password, rememberMe, |
45 | * 覆盖默认实现,用sendRedirect直接跳出框架,以免造成js框架重复加载js出错。 |
52 | * @see org.apache.shiro.web.filter.authc.FormAuthenticationFilter#onLoginSuccess(org.apache.shiro.authc.AuthenticationToken, org.apache.shiro.subject.Subject, javax.servlet.ServletRequest, javax.servlet.ServletResponse) |
55 | protected boolean onLoginSuccess(AuthenticationToken token, Subject subject, |
56 | ServletRequest request, ServletResponse response) throws Exception { |
59 | HttpServletRequest httpServletRequest = (HttpServletRequest)request; |
60 | HttpServletResponse httpServletResponse = (HttpServletResponse)response; |
62 | if (! "XMLHttpRequest" .equalsIgnoreCase(httpServletRequest.getHeader( "X-Requested-With" )) |
63 | || request.getParameter( "ajax" ) == null ) { |
64 | httpServletResponse.sendRedirect(httpServletRequest.getContextPath() + this .getSuccessUrl()); |
66 | httpServletRequest.getRequestDispatcher( "/login/timeout/success" ).forward(httpServletRequest, httpServletResponse); |
然后修改配置文件。
02 | < bean id = "shiroFilter" class = "org.apache.shiro.spring.web.ShiroFilterFactoryBean" > |
03 | < property name = "securityManager" ref = "securityManager" /> |
04 | < property name = "loginUrl" value = "/login" /> |
05 | < property name = "successUrl" value = "/management/index" /> |
06 | < property name = "filters" > |
08 | < entry key = "authc" value-ref = "captchaFormAuthenticationFilter" /> |
11 | < property name = "filterChainDefinitions" > |