org.springframework.security.web.FilterInvocation Java Examples
The following examples show how to use
org.springframework.security.web.FilterInvocation.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: DynamicSecurityMetadataSource.java From mall with Apache License 2.0 | 6 votes |
@Override public Collection<ConfigAttribute> getAttributes(Object o) throws IllegalArgumentException { if (configAttributeMap == null) this.loadDataSource(); List<ConfigAttribute> configAttributes = new ArrayList<>(); //获取当前访问的路径 String url = ((FilterInvocation) o).getRequestUrl(); String path = URLUtil.getPath(url); PathMatcher pathMatcher = new AntPathMatcher(); Iterator<String> iterator = configAttributeMap.keySet().iterator(); //获取访问该路径所需资源 while (iterator.hasNext()) { String pattern = iterator.next(); if (pathMatcher.match(pattern, path)) { configAttributes.add(configAttributeMap.get(pattern)); } } // 未设置操作请求权限,返回空集合 return configAttributes; }
Example #2
Source File: ProxyInsecureChannelProcessor.java From wallride with Apache License 2.0 | 6 votes |
@Override public void decide(FilterInvocation invocation, Collection<ConfigAttribute> config) throws IOException, ServletException { if ((invocation == null) || (config == null)) { throw new IllegalArgumentException("Nulls cannot be provided"); } String forwardedProto = invocation.getHttpRequest().getHeader("X-Forwarded-Proto"); for (ConfigAttribute attribute : config) { if (supports(attribute)) { if (forwardedProto != null) { if (forwardedProto.equals("https")) { getEntryPoint().commence(invocation.getRequest(), invocation.getResponse()); } } else { if (invocation.getHttpRequest().isSecure()) { getEntryPoint().commence(invocation.getRequest(), invocation.getResponse()); } } } } }
Example #3
Source File: CustomFilterInvocationSecurityMetadataSource.java From spring-security with Apache License 2.0 | 6 votes |
/** * 判定用户请求的url是否在权限表中,如果在权限表中,则返回给CustomAccessDecisionManager类的decide方法,用来判定用户是否有此权限。 * 如果不在则返回null,跳过角色管理(decide方法),直接访问。 * 当然也可以在decide方法中判断该请求是否需要权限判定。 * * 如果我们只有极个别的请求不需要鉴权,就不需要去查permission表了。如下所示 * @param o 从该参数中能获取到请求的url,request对象 * @return null 跳过decide方法 * @throws IllegalArgumentException */ @Override public Collection<ConfigAttribute> getAttributes(Object o) throws IllegalArgumentException { final HttpServletRequest request = ((FilterInvocation) o).getRequest(); //如果匹配到以下url,则不需要进行角色判断。 if (matchers("/images/**", request) || matchers("/js/**", request) || matchers("/css/**", request) || matchers("/fonts/**", request) || matchers("/", request) || matchers("/login", request) || matchers("/getVerifyCode", request) || matchers("/auth/**", request)) { return null; } Set<ConfigAttribute> allAttributes = new HashSet<>(); ConfigAttribute configAttribute = new CustomConfigAttribute(request); allAttributes.add(configAttribute); return allAttributes; }
Example #4
Source File: ExpressionVoter.java From oauth2-resource with MIT License | 6 votes |
@Override public int vote(Authentication authentication, FilterInvocation fi, Collection<ConfigAttribute> attributes) { assert authentication != null; assert fi != null; assert attributes != null; ExpressionConfigAttribute eca = findConfigAttribute(attributes); if (eca == null) { return ACCESS_ABSTAIN; } EvaluationContext ctx = expressionHandler.createEvaluationContext(authentication, fi); int result = ExpressionUtils.evaluateAsBoolean(eca.getAuthorizeExpression(), ctx) ? ACCESS_GRANTED : ACCESS_DENIED; return result; }
Example #5
Source File: CustomFilterInvocationSecurityMetadataSource.java From spring-security with Apache License 2.0 | 6 votes |
/** * 判定用户请求的url是否在权限表中,如果在权限表中,则返回给CustomAccessDecisionManager类的decide方法,用来判定用户是否有此权限。 * 如果不在则返回null,跳过角色管理(decide方法),直接访问。 * 当然也可以在decide方法中判断该请求是否需要权限判定。 * * 如果我们只有极个别的请求不需要鉴权,就不需要去查permission表了。如下所示 * @param o 从该参数中能获取到请求的url,request对象 * @return null 跳过decide方法 * @throws IllegalArgumentException */ @Override public Collection<ConfigAttribute> getAttributes(Object o) throws IllegalArgumentException { final HttpServletRequest request = ((FilterInvocation) o).getRequest(); //如果匹配到以下url,则不需要进行角色判断。 if (matchers("/images/**", request) || matchers("/js/**", request) || matchers("/css/**", request) || matchers("/fonts/**", request) || matchers("/", request) || matchers("/login", request) || matchers("/getVerifyCode", request)) { return null; } Set<ConfigAttribute> allAttributes = new HashSet<>(); ConfigAttribute configAttribute = new CustomConfigAttribute(request); allAttributes.add(configAttribute); return allAttributes; }
Example #6
Source File: CustomSecurityFilter.java From Auth-service with MIT License | 6 votes |
@Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { logger.info("doFilter in Security "); FilterInvocation fi = new FilterInvocation(servletRequest, servletResponse, filterChain); //beforeInvocation会调用SecureResourceDataSource中的逻辑 InterceptorStatusToken token = super.beforeInvocation(fi); try { fi.getChain().doFilter(fi.getRequest(), fi.getResponse()); //执行下一个拦截器 } finally { logger.info("through filter"); super.afterInvocation(token, null); //throw new AccessDeniedException("no right"); } }
Example #7
Source File: SecureResourceFilterInvocationDefinitionSource.java From Auth-service with MIT License | 6 votes |
@Override public Collection<ConfigAttribute> getAttributes(Object o) throws IllegalArgumentException { logger.info("getAttributes"); //应该做instanceof FilterInvocation filterInvocation = (FilterInvocation) o; //String method = filterInvocation.getHttpRequest().getMethod(); String requestURI = filterInvocation.getRequestUrl(); //循环资源路径,当访问的Url和资源路径url匹配时,返回该Url所需要的权限 for (Iterator<Map.Entry<String, Collection<ConfigAttribute>>> iter = map.entrySet().iterator(); iter.hasNext(); ) { Map.Entry<String, Collection<ConfigAttribute>> entry = iter.next(); String url = entry.getKey(); if (matcher.match(url, requestURI)) { return map.get(requestURI); } } return null; }
Example #8
Source File: ProxySecureChannelProcessor.java From wallride with Apache License 2.0 | 6 votes |
@Override public void decide(FilterInvocation invocation, Collection<ConfigAttribute> config) throws IOException, ServletException { Assert.isTrue((invocation != null) && (config != null), "Nulls cannot be provided"); String forwardedProto = invocation.getHttpRequest().getHeader("X-Forwarded-Proto"); for (ConfigAttribute attribute : config) { if (supports(attribute)) { if (forwardedProto != null) { if (!forwardedProto.equals("https")) { getEntryPoint().commence(invocation.getRequest(), invocation.getResponse()); } } else { if (!invocation.getHttpRequest().isSecure()) { getEntryPoint().commence(invocation.getRequest(), invocation.getResponse()); } } } } }
Example #9
Source File: OptionsEndpointFilter.java From webauthn4j-spring-security with Apache License 2.0 | 6 votes |
@Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { FilterInvocation fi = new FilterInvocation(request, response, chain); if (!processFilter(fi.getRequest())) { chain.doFilter(request, response); return; } try { OptionsResponse optionsResponse = processRequest(fi.getRequest()); writeResponse(fi.getResponse(), optionsResponse); } catch (RuntimeException e) { logger.debug(e); writeErrorResponse(fi.getResponse(), e); } }
Example #10
Source File: MyFilterInvocationSecurityMetadataSource.java From base-admin with MIT License | 5 votes |
/** * 在我们初始化的权限数据中找到对应当前url的权限数据 */ @Override public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException { FilterInvocation fi = (FilterInvocation) object; HttpServletRequest request = fi.getRequest(); //遍历我们初始化的权限数据,找到对应的url对应的权限 for (Map.Entry<RequestMatcher, Collection<ConfigAttribute>> entry : requestMap .entrySet()) { if (entry.getKey().matches(request)) { return entry.getValue(); } } return null; }
Example #11
Source File: CustomFilterSecurityInterceptor.java From bbs with GNU Affero General Public License v3.0 | 5 votes |
public void invoke( FilterInvocation fi ) throws IOException, ServletException{ InterceptorStatusToken token = super.beforeInvocation(fi); try{ fi.getChain().doFilter(fi.getRequest(), fi.getResponse()); }finally{ super.afterInvocation(token, null); } }
Example #12
Source File: MolgenisAccessDecisionVoterTest.java From molgenis with GNU Lesser General Public License v3.0 | 5 votes |
@Test void vote_menuPluginSlashGranted() { FilterInvocation filterInvocation = when(mock(FilterInvocation.class).getRequestUrl()) .thenReturn("/menu/menuid/plugingranted/") .getMock(); assertEquals(ACCESS_GRANTED, voter.vote(null, filterInvocation, null)); }
Example #13
Source File: MolgenisAccessDecisionVoterTest.java From molgenis with GNU Lesser General Public License v3.0 | 5 votes |
@Test void vote_menuPluginGranted() { FilterInvocation filterInvocation = when(mock(FilterInvocation.class).getRequestUrl()) .thenReturn("/menu/menuid/plugingranted") .getMock(); assertEquals(ACCESS_GRANTED, voter.vote(null, filterInvocation, null)); }
Example #14
Source File: DynamicallyUrlInterceptor.java From base-admin with MIT License | 5 votes |
public void invoke(FilterInvocation fi) throws IOException, ServletException { if ((fi.getRequest() != null) && (fi.getRequest().getAttribute(FILTER_APPLIED) != null) && observeOncePerRequest) { // filter already applied to this request and user wants us to observe // once-per-request handling, so don't re-do security checking fi.getChain().doFilter(fi.getRequest(), fi.getResponse()); } else { // first time this request being called, so perform security checking if (fi.getRequest() != null) { fi.getRequest().setAttribute(FILTER_APPLIED, Boolean.TRUE); } InterceptorStatusToken token = super.beforeInvocation(fi); try { fi.getChain().doFilter(fi.getRequest(), fi.getResponse()); } finally { super.finallyInvocation(token); } super.afterInvocation(token, null); } }
Example #15
Source File: CustomFilterSecurityInterceptor.java From spring-security with Apache License 2.0 | 5 votes |
public void invoke(FilterInvocation fi) throws IOException, ServletException { //fi里面有一个被拦截的url //里面调用CustomFilterInvocationSecurityMetadataSource的getAttributes(Object object)这个方法判断该请求是否需要进行角色判断 //也就是CustomAccessDecisionManager类的decide方法 InterceptorStatusToken token = super.beforeInvocation(fi); try { //执行下一个拦截器 fi.getChain().doFilter(fi.getRequest(), fi.getResponse()); } finally { super.afterInvocation(token, null); } }
Example #16
Source File: CustomAccessDecisionManager.java From spring-security with Apache License 2.0 | 5 votes |
/** * 判定是否拥有权限的决策方法 * @param authentication CustomUserDetailsService类loadUserByUsername()方法中返回值 * @param o 包含客户端发起的请求的request信息。 * @param collection CustomFilterInvocationSecurityMetadataSource类的getAttribute()方法返回值 * @throws AccessDeniedException * @throws InsufficientAuthenticationException */ @Override public void decide(Authentication authentication, Object o, Collection<ConfigAttribute> collection) throws AccessDeniedException, InsufficientAuthenticationException { HttpServletRequest request = ((FilterInvocation) o).getHttpRequest(); String url; for (GrantedAuthority ga : authentication.getAuthorities()) { url = ga.getAuthority(); if(url.equals(request.getRequestURI())){ return; } } throw new AccessDeniedException("没有权限访问"); }
Example #17
Source File: MyFilterSecurityInterceptor.java From maintain with MIT License | 5 votes |
public void invoke(FilterInvocation fi) throws IOException, ServletException { // fi里面有一个被拦截的url // 里面调用MyInvocationSecurityMetadataSource的getAttributes(Object // object)这个方法获取fi对应的所有权限 // 再调用MyAccessDecisionManager的decide方法来校验用户的权限是否足够 InterceptorStatusToken token = super.beforeInvocation(fi); try { // 执行下一个拦截器 fi.getChain().doFilter(fi.getRequest(), fi.getResponse()); } finally { super.afterInvocation(token, null); } }
Example #18
Source File: MyInvocationSecurityMetadataSourceService.java From spring-boot-demo with MIT License | 5 votes |
/** * 返回请求的资源需要的角色 */ @Override public Collection<ConfigAttribute> getAttributes(Object o) throws IllegalArgumentException { //object 中包含用户请求的request 信息 HttpServletRequest request = ((FilterInvocation) o).getHttpRequest(); for (Iterator<String> it = map.keySet().iterator(); it.hasNext(); ) { String url = it.next(); log.info("url==>{},request==>{}", url, request.getRequestURI()); if (new AntPathRequestMatcher(url).matches(request)) { return map.get(url); } } return new ArrayList<>(); }
Example #19
Source File: AuthorityManager.java From BlogManagePlatform with Apache License 2.0 | 5 votes |
/** * 判定是否拥有权限<br> * authentication是UserDetailsServiceImpl中添加到GrantedAuthority中的权限信息.<br> * object包含客户端请求的request信息,可转换为HttpServletRequest,方法如下:<br> * request = ((FilterInvocation) object).getHttpRequest()<br> * attributes是DatabaseSecurityMetadataSource的getAttributes方法的返回值.<br> * 如果用户不具有请求的url的权限,抛出AccessDeniedException.<br> * @author Frodez * @date 2018-12-03 */ @Override public void decide(Authentication auth, Object object, Collection<ConfigAttribute> permissions) throws AccessDeniedException, InsufficientAuthenticationException { FilterInvocation invocation = (FilterInvocation) object; if (!Matcher.needVerify(invocation.getHttpRequest())) { // 如果是免验证路径,则直接放行,因为免验证路径下为了防止报错,设置了一个默认的无访问权限 return; } //如果用户不带有权限,说明用户信息可能有问题,必须直接驳回 //详情见frodez.config.security.filter.TokenFilter.doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) //和frodez.config.security.user.UserDetailsServiceImpl.loadUserByUsername(String username)方法 if (EmptyUtil.yes(auth.getAuthorities())) { throw new AccessDeniedException("无访问权限!"); } // 当包含无访问权限时,直接驳回(此时只有无访问权限一个权限) if (permissions.contains(defaultDeniedRole)) { throw new AccessDeniedException("无访问权限!"); } Set<String> auths = StreamUtil.set(auth.getAuthorities(), GrantedAuthority::getAuthority); for (ConfigAttribute permission : permissions) { if (auths.contains(permission.getAttribute())) { return; } } // 当token携带权限与资源所需访问权限不符时,驳回 throw new AccessDeniedException("无访问权限!"); }
Example #20
Source File: ExpressionFilterInvocationSecurityMetadataSource.java From oauth2-resource with MIT License | 5 votes |
/** * 此方法是为了判定用户请求的url 是否在权限表中,如果在权限表中,则返回给 decide 方法。 * object-->FilterInvocation */ @Override public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException { FilterInvocation filterInvocation = (FilterInvocation) object; HttpServletRequest request = filterInvocation.getHttpRequest(); if (resourceMap == null || resourceMap.size() == 0) { loadResource(request); } String requestUrl = filterInvocation.getRequestUrl(); for (Map.Entry<RequestMatcher, Collection<ConfigAttribute>> entry : resourceMap .entrySet()) { if (entry.getKey().matches(request)) { log.info("【" + requestUrl + "】匹配到DB权限列表"); return entry.getValue(); } } log.info("【" + requestUrl + "】不在DB权限列表当中,尝试匹配代码中的权限配置..."); /// return null; //默认白名单通过 // 返回代码定义的默认配置(authenticated、permitAll等) Collection<ConfigAttribute> configAttributes = hardCodedSecurityMetadataSource.getAttributes(object); if (configAttributes == null || configAttributes.size() == 0) { log.info("【" + requestUrl + "】不在代码中的权限配置"); } else { log.info("【" + requestUrl + "】匹配到代码中硬编码的配置或默认配置"); } return configAttributes; }
Example #21
Source File: MyFilterSecurityInterceptor.java From demo-project with MIT License | 5 votes |
public void invoke(FilterInvocation fi) throws IOException, ServletException { InterceptorStatusToken token = super.beforeInvocation(fi); try { fi.getChain().doFilter(fi.getRequest(), fi.getResponse()); } finally { super.afterInvocation(token, null); } }
Example #22
Source File: LogAccessConfigAuthorizedVoterTest.java From lognavigator with Apache License 2.0 | 5 votes |
@Test public void testPreHandle_UserNotAuthorizedButRoleAuthorized() throws Exception { FilterInvocation filterInvocation = new FilterInvocation("/logs/log-with-onerole-and-oneuser-authorized/list", "GET"); TestingAuthenticationToken authenticatedUser = new TestingAuthenticationToken("anyuser", null, "onerole"); SecurityContextHolder.getContext().setAuthentication(authenticatedUser); int resultAccess = logAccessConfigAuthorizedVoter.vote(authenticatedUser, filterInvocation, Arrays.asList(GOOD_ATTRIBUTE)); Assert.assertEquals(AccessDecisionVoter.ACCESS_GRANTED, resultAccess); }
Example #23
Source File: MyFilterSecurityInterceptor.java From springboot-security-wechat with Apache License 2.0 | 5 votes |
public void invoke(FilterInvocation fi) throws IOException, ServletException { //fi里面有一个被拦截的url //里面调用MyInvocationSecurityMetadataSource的getAttributes(Object object)这个方法获取fi对应的所有权限 //再调用MyAccessDecisionManager的decide方法来校验用户的权限是否足够 InterceptorStatusToken token = super.beforeInvocation(fi); try { //执行下一个拦截器 fi.getChain().doFilter(fi.getRequest(), fi.getResponse()); } finally { super.afterInvocation(token, null); } }
Example #24
Source File: MolgenisAccessDecisionVoterTest.java From molgenis with GNU Lesser General Public License v3.0 | 5 votes |
@Test void vote_pluginDenied() { FilterInvocation filterInvocation = when(mock(FilterInvocation.class).getRequestUrl()) .thenReturn("/plugin/plugindenied") .getMock(); assertEquals(ACCESS_DENIED, voter.vote(null, filterInvocation, null)); }
Example #25
Source File: RbacWebSecurityExpressionRoot.java From spring-backend-boilerplate with Apache License 2.0 | 5 votes |
public RbacWebSecurityExpressionRoot(Authentication a, FilterInvocation fi, PermissionService permissionService, ResourceService resourceService) { super(a, fi); this.filterInvocation = fi; this.permissionService = permissionService; this.resourceService = resourceService; }
Example #26
Source File: ExposeAttemptedPathAuthorizationAuditListener.java From tutorials with MIT License | 5 votes |
private void onAuthorizationFailureEvent(AuthorizationFailureEvent event) { Map<String, Object> data = new HashMap<>(); data.put("type", event.getAccessDeniedException().getClass().getName()); data.put("message", event.getAccessDeniedException().getMessage()); data.put("requestUrl", ((FilterInvocation)event.getSource()).getRequestUrl() ); if (event.getAuthentication().getDetails() != null) { data.put("details", event.getAuthentication().getDetails()); } publish(new AuditEvent(event.getAuthentication().getName(), AUTHORIZATION_FAILURE, data)); }
Example #27
Source File: ActionLoggerInterceptor.java From onetwo with Apache License 2.0 | 5 votes |
private AdminActionLog createActionLog(HttpServletRequest request, HttpServletResponse response, Object handler){ LoginUserDetails loginUser = SecurityUtils.getCurrentLoginUser(); AdminActionLog log = new AdminActionLog(); FilterInvocation fi = new FilterInvocation(RequestUtils.getServletPath(request), request.getMethod()); Collection<ConfigAttribute> attrs = filterSecurityInterceptor.obtainSecurityMetadataSource().getAttributes(fi); if(attrs!=null){ attrs.stream() .filter(attr->CodeSecurityConfig.class.isInstance(attr)) .findAny() .ifPresent(attr->{ CodeSecurityConfig codeAttr = (CodeSecurityConfig) attr; log.setPermissionCode(codeAttr.getCode()); log.setPermissionName(codeAttr.getAuthorityName()); }); } if(loginUser!=null){ log.setUserId(loginUser.getUserId()); log.setUserName(loginUser.getUsername()); } log.setActionTime(new Date()); /*String actionInput = StringUtils.substring(jsonMapper.toJson(request.getParameterMap()), 0, 1000); log.setActionInput(actionInput);*/ // log.setActionOutput(actionOutput); log.setActionUrl(RequestUtils.getContextRequestPath(request)); log.setOperatorIp(RequestUtils.getRemoteAddr(request)); log.setHttpMethod(request.getMethod()); log.setIsSuccess(true); return log; }
Example #28
Source File: MolgenisAccessDecisionVoterTest.java From molgenis with GNU Lesser General Public License v3.0 | 5 votes |
@Test void vote_menuPluginWithParamsDenied() { FilterInvocation filterInvocation = when(mock(FilterInvocation.class).getRequestUrl()) .thenReturn("/menu/menuid/plugindenied?key=val") .getMock(); assertEquals(ACCESS_DENIED, voter.vote(null, filterInvocation, null)); }
Example #29
Source File: FilterSecurityInterceptor.java From bdf3 with Apache License 2.0 | 5 votes |
public void invoke(FilterInvocation fi) throws IOException, ServletException { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if ((fi.getRequest() != null) && (fi.getRequest().getAttribute(FILTER_APPLIED) != null) && observeOncePerRequest || (auth.isAuthenticated() && auth.getPrincipal() instanceof String && "anonymousUser".equals(auth.getPrincipal()))) { // filter already applied to this request and user wants us to observe // once-per-request handling, so don't re-do security checking fi.getChain().doFilter(fi.getRequest(), fi.getResponse()); } else { // first time this request being called, so perform security checking if (fi.getRequest() != null) { fi.getRequest().setAttribute(FILTER_APPLIED, Boolean.TRUE); } InterceptorStatusToken token = super.beforeInvocation(fi); try { fi.getChain().doFilter(fi.getRequest(), fi.getResponse()); } finally { super.finallyInvocation(token); } super.afterInvocation(token, null); } }
Example #30
Source File: LogAccessConfigAuthorizedVoterTest.java From lognavigator with Apache License 2.0 | 5 votes |
@Test(expected=AccessDeniedException.class) public void testPreHandle_UserNotAuthorized() throws Exception { FilterInvocation filterInvocation = new FilterInvocation("/logs/log-with-oneuser-authorized/list", "GET"); TestingAuthenticationToken authenticatedUser = new TestingAuthenticationToken("not-authorized-user", null); SecurityContextHolder.getContext().setAuthentication(authenticatedUser); logAccessConfigAuthorizedVoter.vote(authenticatedUser, filterInvocation, Arrays.asList(GOOD_ATTRIBUTE)); }