关于spring security的URL路径验证问题
在前一篇文章中,还是有些地方没讲清楚,但那篇文章已经有点长了,所以还是另外单独讲一下吧。见SecureResourceFilterInvocationDefinitionSource代码:
/** * RegexUrlPathMatcher默认不进行小写转换,而AntUrlPathMatcher默认要进行小写转换 */ public void afterPropertiesSet() throws Exception { // default url matcher will be RegexUrlPathMatcher this.urlMatcher = new RegexUrlPathMatcher(); if (useAntPath) { // change the implementation if required this.urlMatcher = new AntUrlPathMatcher(); } // Only change from the defaults if the attribute has been set if ("true".equals(lowercaseComparisons)) { if (!this.useAntPath) { ((RegexUrlPathMatcher) this.urlMatcher).setRequiresLowerCaseUrl(true); } } else if ("false".equals(lowercaseComparisons)) { if (this.useAntPath) { //是否对URL全部转换成小写格式 ((AntUrlPathMatcher) this.urlMatcher).setRequiresLowerCaseUrl(false); } } }//这个方法主要会在FilterSecurityInterceptor->AbstractSecurityInterceptor->beforeInvocation中用到 public ConfigAttributeDefinition getAttributes(Object filter) throws IllegalArgumentException { FilterInvocation filterInvocation = (FilterInvocation) filter; String requestURI = filterInvocation.getRequestUrl(); Map<String, String> urlAuthorities = this.getUrlAuthorities(filterInvocation); String grantedAuthorities = null; for(Iterator<Map.Entry<String, String>> iter = urlAuthorities.entrySet().iterator(); iter.hasNext();) { Map.Entry<String, String> entry = iter.next(); //url表示从资源表取出的值,在这里代表的是相应的URL String url = entry.getKey(); //这段代码表示数据库内的需要验证的资源URL与当前请求的URL相匹配时进行验证 if(urlMatcher.pathMatchesUrl(url, requestURI)) { //grantedAuthorities表示每个资源对应的角色,如果有多个角色,则以','隔开 grantedAuthorities = entry.getValue(); break; } } if(grantedAuthorities != null) { ConfigAttributeEditor configAttrEditor = new ConfigAttributeEditor(); configAttrEditor.setAsText(grantedAuthorities); return (ConfigAttributeDefinition) configAttrEditor.getValue(); } //返回null表示不会验证 return null; }
<intercept-url pattern="/secure/extreme/**" access="ROLE_SUPERVISOR"/> <intercept-url pattern="/secure/**" access="IS_AUTHENTICATED_REMEMBERED" /> <intercept-url pattern="/**" access="IS_AUTHENTICATED_ANONYMOUSLY" />

public Map<String, String> loadUrlAuthorities() { Map<String, String> urlAuthorities = new LinkedHashMap<String, String>(); @SuppressWarnings("unchecked") List<Resource> urlResources = getHibernateTemplate().find("FROM Resource resource WHERE resource.type = ?", "URL"); for(Resource resource : urlResources) { urlAuthorities.put(resource.getValue(), resource.getRoleAuthorities()); } return urlAuthorities; }* <li>? matches one character</li> * <li>* matches zero or more characters</li> * <li>** matches zero or more 'directories' in a path</li>