1. 程式人生 > >Apache Shiro Ajax授權登入

Apache Shiro Ajax授權登入

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方式提交的登入請求成功後將會返回回撥引數到請求方法中