spring security拦截了任意的post请求,到了自定义的拦截器AccessDecisionManager后,url请求直接变成404

小小的人儿居然已存在 2017-05-24 07:12:45
项目采用的是javaconfig配置,在get方式请求时,一切正常,但是用post方式请求时,所有的url请求直接就变成配置的404页面,请大神帮忙看看什么问题。springsecurity拦截器配置:
@Override
protected void configure(HttpSecurity http) throws Exception {

//设置自定义的访问控制
http.authorizeRequests().accessDecisionManager(accessDecisionManager);

http
.authorizeRequests()
.antMatchers("/**").permitAll()
.and().formLogin().loginPage("/views/common/login.jsp").loginProcessingUrl("/securty_login").successHandler(loginSuccessHandler)
.usernameParameter("emailOrMobile").passwordParameter("passWord")
.and().csrf()
.and().exceptionHandling().accessDeniedPage("/sys/error");
http.logout().logoutUrl("/securyty_logout").logoutSuccessUrl("/views/common/index.jsp");
http.headers().frameOptions().disable();
}

@Override
public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes)
throws AccessDeniedException, InsufficientAuthenticationException {

FilterInvocation filterInvocation = (FilterInvocation) object;
String url = filterInvocation.getRequestUrl();
//如果没有配置访问权限,则不通过
if( configAttributes == null) {
throw new AccessDeniedException("未配置访问权限");
}
//直接放行的资源
if(this.isCommonResource(url)){
return;
}
otherCode…………
}

get的话就正常:

post请求404错误:

到自定义的控制器的时候,url请求直接变成了404页面:

不知道在此之前哪里拦截了post请求,有知情的大佬还望指教!!


...全文
1799 2 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
LeoSong121 2021-04-01
  • 打赏
  • 举报
回复
Nice solution
  • 打赏
  • 举报
回复
问题找到了,springsecurity配置了csrf(),csrf会拦截我所有的post请求,这涉及到csrf攻击,参考http://www.cnblogs.com/hyddd/archive/2009/04/09/1432744.html,这个地方有两个解决方案。 第一个:简单粗暴,直接设置http.csrf().disable();禁用csrf防御。然后暴露出的问题就很明显了。 第二个:自定义csrf处理。
RequestMatcher requestMatcher = new CsrfSecurityRequestMatcher();
http.csrf().requireCsrfProtectionMatcher(requestMatcher);
其中CsrfSecurityRequestMatcher自己实现RequestMatcher
public class CsrfSecurityRequestMatcher implements RequestMatcher {
	
	 private Pattern allowedMethods = Pattern.compile("^(GET|HEAD|TRACE|OPTIONS)$");
	
	@Override
	public boolean matches(HttpServletRequest request) {
		List<String> execludeUrls = new ArrayList<>();
		execludeUrls.add("sys/getSecCode.do");//允许post请求的url路径,这只是简单测试,具体要怎么设计这个csrf处理,看个人爱好
		
		 if (execludeUrls != null && execludeUrls.size() > 0) {
	            String servletPath = request.getServletPath();
	            request.getParameter("");
	            for (String url : execludeUrls) {
	                if (servletPath.contains(url)) {
	                    return false;
	                }
	            }
	        }
		 return !allowedMethods.matcher(request.getMethod()).matches();
	}
}

62,634

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧