62,614
社区成员
发帖
与我相关
我的任务
分享
@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…………
}
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();
}
}