public static RequestMatcher getRequestMatcher( ManagementContextResolver contextResolver) { if (contextResolver == null) { return null; } ManagementServerProperties management = contextResolver .getApplicationContext().getBean(ManagementServerProperties.class); ServerProperties server = contextResolver.getApplicationContext() .getBean(ServerProperties.class); String path = management.getContextPath(); if (StringUtils.hasText(path)) { AntPathRequestMatcher matcher = new AntPathRequestMatcher( server.getPath(path) + "/**"); return matcher; } // Match everything, including the sensitive and non-sensitive paths return new LazyEndpointPathRequestMatcher(contextResolver, EndpointPaths.ALL); }
public void execute(FilterSecurityInterceptor filterSecurityInterceptor, Map<String, String> resourceMap) { Assert.notNull(filterSecurityInterceptor); Assert.notNull(resourceMap); logger.info("refresh url resource"); LinkedHashMap<RequestMatcher, Collection<ConfigAttribute>> requestMap = null; requestMap = new LinkedHashMap<RequestMatcher, Collection<ConfigAttribute>>(); for (Map.Entry<String, String> entry : resourceMap.entrySet()) { String key = entry.getKey(); String value = entry.getValue(); requestMap.put(new AntPathRequestMatcher(key), SecurityConfig.createListFromCommaDelimitedString(value)); } FilterInvocationSecurityMetadataSource source = new DefaultFilterInvocationSecurityMetadataSource( requestMap); filterSecurityInterceptor.setSecurityMetadataSource(source); }
@Bean public AuthenticationInterceptor authInterceptor() { List<RequestMatcher> matchers = ImmutableList.of( new AntPathRequestMatcher("/flows/**"), new AntPathRequestMatcher("/user/register"), new AntPathRequestMatcher("/user/delete"), new AntPathRequestMatcher("/user"), new AntPathRequestMatcher("/user/role/update"), new AntPathRequestMatcher("/jobs/**"), new AntPathRequestMatcher("/credentials/*"), new AntPathRequestMatcher("/actions/**"), new AntPathRequestMatcher("/message/**"), new AntPathRequestMatcher("/agents/create"), new AntPathRequestMatcher("/agents"), new AntPathRequestMatcher("/roles/**"), new AntPathRequestMatcher("/thread/config") ); return new AuthenticationInterceptor(matchers); }
public RequestConfigMapping(RequestMatcher matcher, Collection<ConfigAttribute> attributes) { if (matcher == null) { throw new IllegalArgumentException("matcher cannot be null"); } Assert.notEmpty(attributes, "attributes cannot be null or emtpy"); this.matcher = matcher; this.attributes = attributes; }
@Override protected void configure(HttpSecurity http) throws Exception { // secure endpoints RequestMatcher matcher = getRequestMatcher(); if (matcher != null) { // Always protect them if present if (this.security.isRequireSsl()) { http.requiresChannel().anyRequest().requiresSecure(); } AuthenticationEntryPoint entryPoint = entryPoint(); http.exceptionHandling().authenticationEntryPoint(entryPoint); // Match all the requests for actuator endpoints ... http.requestMatcher(matcher); // ... but permitAll() for the non-sensitive ones configurePermittedRequests(http.authorizeRequests()); http.httpBasic().authenticationEntryPoint(entryPoint); // No cookies for management endpoints by default http.csrf().disable(); http.sessionManagement().sessionCreationPolicy( this.management.getSecurity().getSessions()); SpringBootWebSecurityConfiguration.configureHeaders(http.headers(), this.security.getHeaders()); } }
@Override protected void configure(HttpSecurity http) throws Exception { List<RequestMatcher> csrfMethods = new ArrayList<>(); Arrays.asList( "POST", "PUT", "PATCH", "DELETE" ) .forEach( method -> csrfMethods.add( new AntPathRequestMatcher( "/**", method ) ) ); http .sessionManagement().sessionCreationPolicy( SessionCreationPolicy.STATELESS ).and() .exceptionHandling().authenticationEntryPoint( restAuthenticationEntryPoint ).and() .authorizeRequests() .antMatchers( HttpMethod.GET, "/", "/webjars/**", "/*.html", "/favicon.ico", "/**/*.html", "/**/*.css", "/**/*.js" ).permitAll() .antMatchers("/auth/**").permitAll() .anyRequest().authenticated().and() .addFilterBefore(new TokenAuthenticationFilter(tokenHelper, jwtUserDetailsService), BasicAuthenticationFilter.class); http.csrf().disable(); }
/**** * 基于url匹配拦截时,转换为ExpressionBasedFilterInvocationSecurityMetadataSource * @param source * @return */ @Override @SuppressWarnings("unchecked") public void buildSecurityMetadataSource(){ Assert.notNull(filterSecurityInterceptor); this.buildRequestMap(); DefaultFilterInvocationSecurityMetadataSource originMetadata = (DefaultFilterInvocationSecurityMetadataSource)filterSecurityInterceptor.getSecurityMetadataSource(); //这个内置实现不支持一个url映射到多个表达式 // ExpressionBasedFilterInvocationSecurityMetadataSource fism = new ExpressionBasedFilterInvocationSecurityMetadataSource(requestMap, securityExpressionHandler); Map<RequestMatcher, Collection<ConfigAttribute>> originRequestMap = (Map<RequestMatcher, Collection<ConfigAttribute>>)ReflectUtils.getFieldValue(originMetadata, "requestMap", false); if(originRequestMap!=null && !originRequestMap.isEmpty()){ this.requestMap.putAll(originRequestMap); } DefaultFilterInvocationSecurityMetadataSource fism = new DefaultFilterInvocationSecurityMetadataSource(requestMap); this.filterSecurityInterceptor.setSecurityMetadataSource(fism); }
/** * Gets the filter security interceptor. * * @return the filter security interceptor */ @Bean(name = "fsi") public FilterSecurityInterceptor getFilterSecurityInterceptor() { FilterSecurityInterceptor interceptor = new FilterSecurityInterceptor(); interceptor.setAuthenticationManager(getProviderManager()); interceptor.setAccessDecisionManager(getAffirmativeBased()); LinkedHashMap<RequestMatcher, Collection<ConfigAttribute>> requestMap = new LinkedHashMap<>(); requestMap.put(new AntPathRequestMatcher("/adm/**"), SecurityConfig.createListFromCommaDelimitedString("ROLE_MANAGER,ROLE_MANAGER-GUI")); requestMap.put(new AntPathRequestMatcher("/adm/restartvm.ajax"), SecurityConfig .createListFromCommaDelimitedString("ROLE_POWERUSERPLUS,ROLE_MANAGER,ROLE_MANAGER-GUI")); requestMap.put(new AntPathRequestMatcher("/sql/**"), SecurityConfig .createListFromCommaDelimitedString("ROLE_POWERUSERPLUS,ROLE_MANAGER,ROLE_MANAGER-GUI")); requestMap.put(new AntPathRequestMatcher("/app/**"), SecurityConfig.createListFromCommaDelimitedString( "ROLE_POWERUSER,ROLE_POWERUSERPLUS,ROLE_MANAGER,ROLE_MANAGER-GUI")); requestMap.put(new AntPathRequestMatcher("/**"), SecurityConfig.createListFromCommaDelimitedString( "ROLE_PROBEUSER,ROLE_POWERUSER,ROLE_POWERUSERPLUS,ROLE_MANAGER,ROLE_MANAGER-GUI")); interceptor .setSecurityMetadataSource(new DefaultFilterInvocationSecurityMetadataSource(requestMap)); return interceptor; }
/** * Get Attributes map from cache if cache set. * @return Map */ @SuppressWarnings("unchecked") private Map<RequestMatcher, Collection<ConfigAttribute>> getAttributesMap(){ if(cache!=null){ Map<RequestMatcher, Collection<ConfigAttribute>> map; String key="ex.securityMetadataSource"; Element e=cache.get(key); if(e!=null && !e.isExpired()){ log.debug("Cache [Hit] ex.securityMetadataSource: {}",e); map= (Map<RequestMatcher, Collection<ConfigAttribute>>)e.getObjectValue(); }else{ map=processMap(); Element enew = new Element(key, map); cache.put(enew); log.debug("Cache [Update] ex.securityMetadataSource: {}",enew); } return map; } return processMap(); }
private void addSecureChannel(List<Filter> filters, Protocol protocol) { ChannelProcessingFilter channelProcessingFilter = new ChannelProcessingFilter(); channelProcessingFilter.setChannelDecisionManager(channelDecisionManager); RequestMatcher anyRequest = AnyRequestMatcher.INSTANCE; LinkedHashMap<RequestMatcher, Collection<ConfigAttribute>> requestMap = new LinkedHashMap<>(); Collection<ConfigAttribute> configAtts = new ArrayList<>(); switch (protocol) { case HTTP: configAtts.add(new SecurityConfig("ANY_CHANNEL")); break; case HTTPS: configAtts.add(new SecurityConfig("REQUIRES_SECURE_CHANNEL")); break; default: } requestMap.put(anyRequest, configAtts); FilterInvocationSecurityMetadataSource securityMetadataSource = new DefaultFilterInvocationSecurityMetadataSource(requestMap); channelProcessingFilter.setSecurityMetadataSource(securityMetadataSource); filters.add(channelProcessingFilter); }
@Profile("!test") @Bean(name = "csrfMatcher") public RequestMatcher csrfMatcher() { /** * Copy of default request matcher from * CsrfFilter$DefaultRequiresCsrfMatcher */ return new RequestMatcher() { private Pattern allowedMethods = Pattern .compile("^(GET|HEAD|TRACE|OPTIONS)$"); /* * (non-Javadoc) * * @see * org.springframework.security.web.util.matcher.RequestMatcher# * matches(javax.servlet.http.HttpServletRequest) */ public boolean matches(HttpServletRequest request) { return !allowedMethods.matcher(request.getMethod()).matches(); } }; }
@Bean(name = "authFilter") public Filter authFilter() throws Exception { log.info("Creating authFilter..."); RequestMatcher antReqMatch = new AntPathRequestMatcher(API_LOGIN_URL); List<RequestMatcher> reqMatches = new ArrayList<>(); reqMatches.add(antReqMatch); RequestMatcher reqMatch = new AndRequestMatcher(reqMatches); UsernamePasswordAuthenticationFilter filter = new UsernamePasswordAuthenticationFilter(); filter.setPostOnly(true); filter.setUsernameParameter(USERNAME); filter.setPasswordParameter(PASSWORD); filter.setRequiresAuthenticationRequestMatcher(reqMatch); filter.setAuthenticationSuccessHandler(apiAuthenticationSuccessHandler); filter.setAuthenticationFailureHandler(apiAuthenticationFailureHandler); filter.setAuthenticationManager(authenticationManager()); return filter; }
public JwtTokenAuthenticationProcessingFilter( AuthenticationFailureHandler failureHandler, TokenExtractor tokenExtractor, RequestMatcher matcher) { super(matcher); this.failureHandler = failureHandler; this.tokenExtractor = tokenExtractor; }
public void refresh() { if ((filterSecurityInterceptor == null) || (urlSourceFetcher == null)) { logger.info( "filterSecurityInterceptor : {}, urlSourceFetcher : {}", filterSecurityInterceptor, urlSourceFetcher); return; } logger.info("execute refresh"); Map<String, String> resourceMap = urlSourceFetcher.getSource(null); LinkedHashMap<RequestMatcher, Collection<ConfigAttribute>> requestMap = null; requestMap = new LinkedHashMap<RequestMatcher, Collection<ConfigAttribute>>(); for (Map.Entry<String, String> entry : resourceMap.entrySet()) { String key = entry.getKey(); String value = entry.getValue(); requestMap.put(new AntPathRequestMatcher(key), SecurityConfig.createListFromCommaDelimitedString(value)); } FilterInvocationSecurityMetadataSource source = new DefaultFilterInvocationSecurityMetadataSource( requestMap); filterSecurityInterceptor.setSecurityMetadataSource(source); }
@Autowired public JwtTokenAuthenticationProcessingFilter(RequestMatcher matcher, AuthenticationFailureHandler failureHandler, JwtTokenUtil jwtTokenUtil) { super(matcher); this.failureHandler = failureHandler; this.jwtTokenUtil = jwtTokenUtil; }
private boolean isNeedToVerify(HttpServletRequest request) { for (RequestMatcher matcher : authRequests) { if (matcher.matches(request)) { return true; } } return false; }
private boolean skipPathRequest(HttpServletRequest request, List<String> pathsToSkip ) { Assert.notNull(pathsToSkip, "pathsToSkip is null!"); List<RequestMatcher> m = pathsToSkip.stream().map(path -> new AntPathRequestMatcher(path)).collect(Collectors.toList()); OrRequestMatcher matchers = new OrRequestMatcher(m); return matchers.matches(request); }
@Autowired public JwtTokenAuthenticationProcessingFilter(AuthenticationFailureHandler failureHandler, TokenExtractor tokenExtractor, RequestMatcher matcher) { super(matcher); this.failureHandler = failureHandler; this.tokenExtractor = tokenExtractor; }
@Override public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException { FilterInvocation filterInvocation = (FilterInvocation) object; for (String url : resourceMap.keySet()) { RequestMatcher requestMatcher = new AntPathRequestMatcher(url); HttpServletRequest httpRequest = filterInvocation.getHttpRequest(); if (requestMatcher.matches(httpRequest)) { return resourceMap.get(url); } } return null; }
@SuppressWarnings("deprecation") public SkipPathRequestMatcher(List<String> pathsToSkip, String processingPath) { Assert.notNull(pathsToSkip); List<RequestMatcher> m = pathsToSkip.stream().map(path -> new AntPathRequestMatcher(path)).collect(Collectors.toList()); matchers = new OrRequestMatcher(m); processingMatcher = new AntPathRequestMatcher(processingPath); }
public SkipPathRequestMatcher(List<String> pathsToSkip, String processingPath) { Assert.notNull(pathsToSkip); List<RequestMatcher> m = pathsToSkip.stream().map(path -> new AntPathRequestMatcher(path)) .collect(Collectors.toList()); matchers = new OrRequestMatcher(m); processingMatcher = new AntPathRequestMatcher(processingPath); }
/** * 根据request请求获取访问资源所需权限 * @param object * @return * @throws IllegalArgumentException * @see org.springframework.security.access.SecurityMetadataSource#getAttributes(java.lang.Object) */ public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException { final HttpServletRequest request = ((FilterInvocation) object).getRequest(); Collection<ConfigAttribute> attrs = Collections.emptyList(); for (Map.Entry<RequestMatcher, Collection<ConfigAttribute>> entry : requestMap.entrySet()) { if (entry.getKey().matches(request)) { attrs = entry.getValue(); break; } } logger.info("URI资源:"+request.getRequestURI()+ " -> " + attrs); return attrs; }
/** * @return * @see org.springframework.security.access.SecurityMetadataSource#getAllConfigAttributes() */ public Collection<ConfigAttribute> getAllConfigAttributes() { Set<ConfigAttribute> allAttributes = new HashSet<ConfigAttribute>(); for (Map.Entry<RequestMatcher, Collection<ConfigAttribute>> entry : requestMap.entrySet()) { allAttributes.addAll(entry.getValue()); } return allAttributes; }
protected Map<RequestMatcher, Collection<ConfigAttribute>> bindRequestMap() { Map<RequestMatcher, Collection<ConfigAttribute>> map = new LinkedHashMap<RequestMatcher, Collection<ConfigAttribute>>(); Map<String, String> resMap = this.loadResuorce(); for (Map.Entry<String, String> entry : resMap.entrySet()) { String key = entry.getKey(); map.put(new AntPathRequestMatcher(key), SecurityConfig.createListFromCommaDelimitedString(entry.getValue())); } return map; }
@Test public void matchers() throws Exception { ServiceProviderEndpoints endpoints = new ServiceProviderEndpoints(); endpoints.setDefaultFailureURL("/failure"); endpoints.setIdpSelectionPageURL("/idp"); endpoints.setSsoLoginURL("/login"); endpoints.setDiscoveryProcessingURL("/discovery"); endpoints.setDefaultTargetURL("/default"); endpoints.setLogoutURL("/logout"); endpoints.setMetadataURL("/metadata"); endpoints.setSingleLogoutURL("/slo"); endpoints.setSsoHoKProcessingURL("/hok"); endpoints.setSsoProcessingURL("/sso"); RequestMatcher matcher = endpoints.getRequestMatcher(); assertThat(matcher.matches(mockRequest("/failure"))).isTrue(); assertThat(matcher.matches(mockRequest("/idp"))).isTrue(); assertThat(matcher.matches(mockRequest("/login"))).isTrue(); assertThat(matcher.matches(mockRequest("/discovery"))).isTrue(); assertThat(matcher.matches(mockRequest("/default"))).isTrue(); assertThat(matcher.matches(mockRequest("/logout"))).isTrue(); assertThat(matcher.matches(mockRequest("/metadata"))).isTrue(); assertThat(matcher.matches(mockRequest("/slo"))).isTrue(); assertThat(matcher.matches(mockRequest("/hok"))).isTrue(); assertThat(matcher.matches(mockRequest("/sso"))).isTrue(); assertThat(matcher.matches(mockRequest("/sanity-check"))).isFalse(); }
private RequestMatcher getRequestMatcher() { if (this.management.getSecurity().isEnabled()) { return LazyEndpointPathRequestMatcher .getRequestMatcher(this.contextResolver); } return null; }
private RequestMatcher createDelegate() { ServerProperties server = this.contextResolver.getApplicationContext() .getBean(ServerProperties.class); List<RequestMatcher> matchers = new ArrayList<RequestMatcher>(); EndpointHandlerMapping endpointHandlerMapping = getRequiredEndpointHandlerMapping(); for (String path : this.endpointPaths.getPaths(endpointHandlerMapping)) { matchers.add(new AntPathRequestMatcher(server.getPath(path))); } return (matchers.isEmpty() ? MATCH_NONE : new OrRequestMatcher(matchers)); }
@Override protected void configure(HttpSecurity http) throws Exception { http.requestMatcher(new RequestMatcher() { @Override public boolean matches(HttpServletRequest request) { return false; } }); }
@Override public void init(HttpSecurity http) { metadataProvider = identityProvider.metadataProvider(); ExtendedMetadata extendedMetadata = extendedMetadata(identityProvider.discoveryEnabled); extendedMetadataDelegate = extendedMetadataDelegate(extendedMetadata); serviceProvider.keyManager = serviceProvider.keyManager(); cachingMetadataManager = cachingMetadataManager(); webSSOProfile = new WebSSOProfileImpl(samlProcessor, cachingMetadataManager); samlAuthenticationProvider = samlAuthenticationProvider(webSSOProfileConsumer); bootstrap(); SAMLContextProvider contextProvider = contextProvider(); SAMLEntryPoint samlEntryPoint = samlEntryPoint(contextProvider); try { http .httpBasic() .authenticationEntryPoint(samlEntryPoint); CsrfConfigurer<HttpSecurity> csrfConfigurer = http.getConfigurer(CsrfConfigurer.class); if(csrfConfigurer != null) { // Workaround to get working with Spring Security 3.2. RequestMatcher ignored = new AntPathRequestMatcher("/saml/SSO"); RequestMatcher notIgnored = new NegatedRequestMatcher(ignored); RequestMatcher matcher = new AndRequestMatcher(new DefaultRequiresCsrfMatcher(), notIgnored); csrfConfigurer.requireCsrfProtectionMatcher(matcher); } } catch (Exception e) { e.printStackTrace(); } http .addFilterBefore(metadataGeneratorFilter(samlEntryPoint, extendedMetadata), ChannelProcessingFilter.class) .addFilterAfter(samlFilter(samlEntryPoint, contextProvider), BasicAuthenticationFilter.class) .authenticationProvider(samlAuthenticationProvider); }