Apache Shiro授权登录一般方式为页面提交授权验证,根据严重结果跳转对应URL,但有时登录方式为AJAX请求,所以需要继承FormAuthenticationFilter并重写登录成功onLoginSuccess与登录失败onLoginFailure方法进行相应处理,简单实现方式如下:
1、继承FormAuthenticationFilter类,重新onLoginSuccess与onLoginFailure方法:
public class FormAuthenticationCaptchaFilter extends FormAuthenticationFilter {
@Override
protected boolean onLoginSuccess(AuthenticationToken token,
Subject subject, ServletRequest request, ServletResponse response)
throws Exception {
HttpServletRequest httpServletRequest = (HttpServletRequest) request;
HttpServletResponse httpServletResponse = (HttpServletResponse) response;
if (!"XMLHttpRequest".equalsIgnoreCase(httpServletRequest.getHeader("X-Requested-With"))) {// 不是ajax请求
issueSuccessRedirect(request, response);
} else {
httpServletResponse.setCharacterEncoding("UTF-8");
PrintWriter out = httpServletResponse.getWriter();
out.println("{success:true,msg:'登录成功'}");
out.flush();
out.close();
}
return false;
}
@Override
protected boolean onLoginFailure(AuthenticationToken token,
AuthenticationException e, ServletRequest request,
ServletResponse response) {
if (!"XMLHttpRequest".equalsIgnoreCase(((HttpServletRequest) request).getHeader("X-Requested-With"))) {// 不是ajax请求
setFailureAttribute(request, e);
return true;
}
try {
response.setCharacterEncoding("UTF-8");
PrintWriter out = response.getWriter();
if("IncorrectCredentialsException".equals(e.getClass().getSimpleName())) {
out.println("{success:false,msg:'"+e.getMessage()+"'}");
}else{
out.println("{success:false,msg:'登录失败!'}");
}
out.flush();
out.close();
} catch (IOException e1) {
e1.printStackTrace();
}
return false;
}
这样以AJAX方式提交的登录请求成功后将会返回回调参数到请求方法中