您的位置:首页 > 其它

shiro不执行认证的解决办法

2017-03-17 13:13 706 查看
初次使用shiro,定义好了realm却发现程序并不进去执行,很是郁闷。这一问题前后出现了两次,而且原因各不相同。下面把觖办法记录下来。

第一种是因为spring的配置文件 中FormAuthenticationFilter过滤器的loginUrl没有与shiroFilter下filterChainDefinitions对应起来,这也是很常见的错误。



第二种错误非常另类,没有进入realm是因为请求方法不对,通过对源码的跟踪,我定位到了FormAuthenticationFilter的onAccessDenied方法:

/**
* 当认证失败时调用
*/
@Override
protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
if (isLoginRequest(request, response)) {
if (isLoginSubmission(request, response)) {
if (log.isTraceEnabled()) {
log.trace("- submission detected.  Attempting to execute login.");
}
return executeLogin(request, response);
} else {
if (log.isTraceEnabled()) {
log.trace("Login page view.");
}
// allow them to see the login page ;)
return true;
}
} else {
if (log.isTraceEnabled()) {
log.trace("Attempting to access a path which requires authentication.  Forwarding to the "
+ "Authentication url [" + getLoginUrl() + "]");
}

// saveRequestAndRedirectToLogin(request, response);
// 响应信息改为json
response.setContentType(MediaType.APPLICATION_JSON_VALUE); // 设置ContentType
// ,返回json数据
response.setCharacterEncoding("UTF-8"); // 避免乱码
try { // {"code":"1","message":"成功","data":"null"}
response.getWriter().write("{\"code\":\"0\",\"message\":\"拒绝访问\"}");
} catch (IOException e) {
System.out.println("返回json出错:" + e.getMessage());
e.printStackTrace();
}

return false;
}
}

shiro会调用isLoginRequest来判断当前请求是不是 登录请求,返回的是true,但是最终的判决是由isLoginSubmission方法决定,不知道它是干嘛的,点开看看:

protected boolean isLoginSubmission(ServletRequest request, ServletResponse response) {
return (request instanceof HttpServletRequest) && WebUtils.toHttp(request).getMethod().equalsIgnoreCase(POST_METHOD);
}


原来是用来判断当前请求的方法是不是POST,而我用的是GET,难怪!!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐