org.springframework.security.access.ConfigAttribute Java Examples

The following examples show how to use org.springframework.security.access.ConfigAttribute. 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: ProxySecureChannelProcessor.java    From wallride with Apache License 2.0 6 votes vote down vote up
@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 #2
Source File: UrlRoleVoter.java    From bdf3 with Apache License 2.0 6 votes vote down vote up
public int vote(Authentication authentication, Object object,
		Collection<ConfigAttribute> attributes) {
	if(authentication == null) {
		return ACCESS_DENIED;
	}
	
	int result = ACCESS_ABSTAIN;
	Collection<? extends GrantedAuthority> authorities = extractAuthorities(authentication);

	for (ConfigAttribute attribute : attributes) {
		if (this.supports(attribute)) {
			result = ACCESS_DENIED;

			for (GrantedAuthority authority : authorities) {
				if (attribute.getAttribute().equals(authority.getAuthority())) {
					return ACCESS_GRANTED;
				}
			}
		}
	}

	return result;
}
 
Example #3
Source File: CustomPermissionAllowedMethodSecurityMetadataSource.java    From tutorials with MIT License 6 votes vote down vote up
@Override
protected Collection<ConfigAttribute> findAttributes(Method method, Class<?> targetClass) {
    Annotation[] annotations = AnnotationUtils.getAnnotations(method);
    List<ConfigAttribute> attributes = new ArrayList<>();

    // if the class is annotated as @Controller we should by default deny access to every method
    if (AnnotationUtils.findAnnotation(targetClass, Controller.class) != null) {
        attributes.add(DENY_ALL_ATTRIBUTE);
    }

    if (annotations != null) {
        for (Annotation a : annotations) {
            // but not if the method has at least a PreAuthorize or PostAuthorize annotation
            if (a instanceof PreAuthorize || a instanceof PostAuthorize) {
                return null;
            }
        }
    }
    return attributes;
}
 
Example #4
Source File: DynamicSecurityMetadataSource.java    From mall with Apache License 2.0 6 votes vote down vote up
@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 #5
Source File: CustomFilterInvocationSecurityMetadataSource.java    From spring-security with Apache License 2.0 6 votes vote down vote up
/**
 * 判定用户请求的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 #6
Source File: MyAccessDecisionManager.java    From itweet-boot with Apache License 2.0 6 votes vote down vote up
@Override
public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes) throws AccessDeniedException, InsufficientAuthenticationException {

    if(null== configAttributes || configAttributes.size() <=0) {
        return;
    }
    ConfigAttribute c;
    String needRole;
    for(Iterator<ConfigAttribute> iter = configAttributes.iterator(); iter.hasNext(); ) {
        c = iter.next();
        needRole = c.getAttribute();
        for(GrantedAuthority ga : authentication.getAuthorities()) {
            if(needRole.trim().equals(ga.getAuthority())) {
                return;
            }
        }
    }
    throw new AccessDeniedException("no right");
}
 
Example #7
Source File: CustomAccessDecisionManager.java    From spring-security with Apache License 2.0 6 votes vote down vote up
/**
 * 判定是否拥有权限的决策方法
 * @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();
         // security 默认角色
         if(url.equals("ROLE_ANONYMOUS")){
            return;
         }
         if(CommonUtil.matchers(url, request)){
            return;
         }
    }
    throw new AccessDeniedException("没有权限访问");
}
 
Example #8
Source File: LDAccessDecisionManager.java    From document-management-software with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> properties)
		throws AccessDeniedException, InsufficientAuthenticationException {

	if (authentication instanceof AnonymousAuthenticationToken) {
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes())
				.getRequest();
		if ("login".equals(request.getParameter("anonymous"))) {
			String tenant = "default";
			if (StringUtils.isNotEmpty(request.getParameter("tenant")))
				tenant = request.getParameter("tenant");

			ContextProperties config = Context.get().getProperties();
			boolean enabled = "true".equals(config.get(tenant + ".anonymous.enabled"));
			if (enabled) {
				return;
			}
		}
	}

	super.decide(authentication, object, properties);
}
 
Example #9
Source File: JFishMethodSecurityMetadataSource.java    From onetwo with Apache License 2.0 6 votes vote down vote up
private List<ConfigAttribute> extractAttributes(Class<?>...codeClasses){
	if(codeClasses!=null){
		List<ConfigAttribute> perms = Stream.of(codeClasses)
				.map(cls->{
					if(menuInfoParser==null){
						throw new BaseException("no menuInfoParser found!");
					}
					String code = SecurityUtils.createSecurityExpression(menuInfoParser.getCode(cls));
					Expression exp = securityExpressionHandler.getExpressionParser().parseExpression(code);
					WebExpressionConfigAttribute config = new WebExpressionConfigAttribute(exp);
					return config;
				})
				.collect(Collectors.toList());
		return perms;
	}
	return ImmutableList.of();
}
 
Example #10
Source File: AuthorizationService.java    From codeway_service with GNU General Public License v3.0 5 votes vote down vote up
/**
 * url对应资源与用户拥有资源进行匹配
 * @param urlConfigAttribute
 * @param userResources
 */
public boolean isMatch(ConfigAttribute urlConfigAttribute, Set<Resource> userResources) {
 boolean isMatchBool = userResources.stream().anyMatch(
   resource -> resource.getCode().equals(urlConfigAttribute.getAttribute()));
 if (!isMatchBool) {
  LogBack.error("url编码错误,请检查角色是否有此权限!");
  throw new AccessDeniedException("url编码错误,请检查角色是否有此权限!");
 }
 return true;
}
 
Example #11
Source File: AuthoritySource.java    From BlogManagePlatform with Apache License 2.0 5 votes vote down vote up
/**
 * 根据url和请求方式,获取对应的权限
 * @author Frodez
 * @date 2018-12-13
 */
@Override
public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
	FilterInvocation invocation = (FilterInvocation) object;
	// 这里的url是截去根路径后的url
	String url = invocation.getHttpRequest().getRequestURI();
	if (urlTypeCache.containsKey(url)) {
		// 根据不同请求方式获取对应权限
		return urlTypeCache.get(url).get(HttpMethod.resolve(invocation.getHttpRequest().getMethod()));
	}
	//如果未获取权限,则添加无访问权限角色
	return defaultDeniedRoles;
}
 
Example #12
Source File: ExpressionReactiveAccessDecisionManager.java    From spring-security-reactive with Apache License 2.0 5 votes vote down vote up
@Override
public Mono<Boolean> decide(Authentication authentication, ServerWebExchange object, Flux<ConfigAttribute> configAttributes) {
	ConfigAttribute attribute = configAttributes.blockFirst();
	EvaluationContext context = handler.createEvaluationContext(authentication, object);
	Expression expression = handler.getExpressionParser().parseExpression(attribute.getAttribute());
	return Mono.just(ExpressionUtils.evaluateAsBoolean(expression, context));
}
 
Example #13
Source File: ActionLoggerInterceptor.java    From onetwo with Apache License 2.0 5 votes vote down vote up
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 #14
Source File: SecureResourceFilterInvocationDefinitionSource.java    From microservice-integration with MIT License 5 votes vote down vote up
@Override
public void afterPropertiesSet() throws Exception {
    logger.info("afterPropertiesSet");
    //用来匹配访问资源路径
    this.matcher = new AntPathMatcher();
    //可以有多个权限
    Collection<ConfigAttribute> atts = new ArrayList<>();
    ConfigAttribute c1 = new SecurityConfig("ROLE_USER");
    atts.add(c1);
    map.put("/api/permission/apiPermissions", atts);
}
 
Example #15
Source File: MyInvocationSecurityMetadataSourceService.java    From spring-boot-demo with MIT License 5 votes vote down vote up
/**
 * 返回请求的资源需要的角色
 */
@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 #16
Source File: LogAccessConfigAuthorizedVoter.java    From lognavigator with Apache License 2.0 5 votes vote down vote up
@Override
public boolean supports(ConfigAttribute attribute) {
	if (IS_AUTHORIZED_LOG_ACCESS_CONFIG.equals(attribute.getAttribute())) {
		return true;
	}
	else {
		return false;
	}
}
 
Example #17
Source File: MultiWebExpressionVoter.java    From onetwo with Apache License 2.0 5 votes vote down vote up
private CodeSecurityConfig findConfigAttribute(
		Collection<ConfigAttribute> attributes) {
	for (ConfigAttribute attribute : attributes) {
		if (attribute instanceof CodeSecurityConfig) {
			return (CodeSecurityConfig) attribute;
		}
	}
	return null;
}
 
Example #18
Source File: ExpressionFilterInvocationSecurityMetadataSource.java    From oauth2-resource with MIT License 5 votes vote down vote up
/**
 * 加载资源-权限关系
 */
private void loadResource(HttpServletRequest request) {
    try {
        List<ResourceEntity> resourceEntityList = resourceEntityMapper.selectByExample(new ResourceEntityExample());
        if (resourceEntityList == null || resourceEntityList.size() == 0) {
            log.warn("DB中没有查到资源权限列表,请先配置resource_entity!");
        } else {
            resourceMap.clear();
            Collection<ConfigAttribute> array;
            ConfigAttribute cfg;
            ServletContext sc = request.getServletContext();
            ApplicationContext ac = WebApplicationContextUtils.getRequiredWebApplicationContext(sc);

            HandlerMappingIntrospector introspector = ac.getBean(HANDLER_MAPPING_INTROSPECTOR_BEAN_NAME, HandlerMappingIntrospector.class);

            for (ResourceEntity resourceEntity : resourceEntityList) {
                array = new ArrayList<>();
                cfg = new ExpressionConfigAttribute(expressionHandler.getExpressionParser().parseExpression(resourceEntity.getPermission()));
                array.add(cfg);
                resourceMap.put(new MvcRequestMatcher(introspector, resourceEntity.getUrl()), array);
            }
        }
    } catch (Exception e) {
        if (log.isErrorEnabled()) {
            log.error("加载权限列表异常", e);
        }
    }

}
 
Example #19
Source File: LogicalOrAccessDecisionManager.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public boolean supports( ConfigAttribute configAttribute )
{
    for ( AccessDecisionManager accessDecisionManager : accessDecisionManagers )
    {
        if ( accessDecisionManager.supports( configAttribute ) )
        {
            return true;
        }
    }

    return false;
}
 
Example #20
Source File: ExpressionFilterInvocationSecurityMetadataSource.java    From oauth2-resource with MIT License 5 votes vote down vote up
/**
     * 此方法是为了判定用户请求的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: MyAccessDecisionManager.java    From oauth2-resource with MIT License 5 votes vote down vote up
/**
 * 方法是判定是否拥有权限的决策方法,
 * (1)authentication 是释CustomUserService中循环添加到 GrantedAuthority 对象中的权限信息集合.
 * (2)object 包含客户端发起的请求的request信息,可转换为 HttpServletRequest request = ((FilterInvocation) object).getHttpRequest();
 * (3)configAttributes 为FilterInvocationSecurityMetadataSource的getAttributes(Object object)这个方法返回的结果,此方法是为了判定用户请求的url 是否在权限表中,如果在权限表中,则返回给 decide 方法
 */
@SuppressWarnings("unchecked")
@Override
public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes)
    throws AccessDeniedException, InsufficientAuthenticationException {
    int deny = 0;
    for (AccessDecisionVoter voter : getDecisionVoters()) {
        int result = voter.vote(authentication, object, configAttributes);

        if (logger.isDebugEnabled()) {
            logger.debug("Voter: " + voter + ", returned: " + result);
        }
        switch (result) {
            case AccessDecisionVoter.ACCESS_GRANTED:
                return;
            case AccessDecisionVoter.ACCESS_DENIED:
                deny++;
                break;
            default:
                break;
        }
    }

    if (deny > 0) {
        throw new AccessDeniedException(messages.getMessage(
            "AbstractAccessDecisionManager.accessDenied", "Access is denied"));
    }

    // To get this far, every AccessDecisionVoter abstained
    checkAllowIfAllAbstainDecisions();
}
 
Example #22
Source File: AccessManager.java    From open-cloud with MIT License 5 votes vote down vote up
public boolean mathAuthorities(HttpServletRequest request, Authentication authentication, String requestPath) {
    Collection<ConfigAttribute> attributes = getAttributes(requestPath);
    int result = 0;
    int expires = 0;
    if (authentication == null) {
        return false;
    } else {
        if (CommonConstants.ROOT.equals(authentication.getName())) {
            // 默认超级管理员账号,直接放行
            return true;
        }
        Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
        Iterator var6 = attributes.iterator();
        while (var6.hasNext()) {
            ConfigAttribute attribute = (ConfigAttribute) var6.next();
            Iterator var8 = authorities.iterator();
            while (var8.hasNext()) {
                GrantedAuthority authority = (GrantedAuthority) var8.next();
                if (attribute.getAttribute().equals(authority.getAuthority())) {
                    result++;
                    if (authority instanceof OpenAuthority) {
                        OpenAuthority customer = (OpenAuthority) authority;
                        if (customer.getIsExpired() != null && customer.getIsExpired()) {
                            // 授权过期数
                            expires++;
                        }
                    }
                }
            }
        }
        log.debug("mathAuthorities result[{}] expires[{}]", result, expires);
        if (expires > 0) {
            // 授权已过期
            throw new AccessDeniedException(ErrorCode.ACCESS_DENIED_AUTHORITY_EXPIRED.getMessage());
        }
        return result > 0;
    }
}
 
Example #23
Source File: RelaodableDelegatingMethodSecurityMetadataSource.java    From onetwo with Apache License 2.0 5 votes vote down vote up
@Override
public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
	if(debug && delegatingMethodSecurityMetadataSource instanceof DelegatingMethodSecurityMetadataSource){
		Map<?, ?> attributeCache = (Map<?, ?>)ReflectUtils.getFieldValue(delegatingMethodSecurityMetadataSource, "attributeCache");
		attributeCache.clear();
	}
	return delegatingMethodSecurityMetadataSource.getAttributes(object);
}
 
Example #24
Source File: ModuleAccessVoter.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Votes. Votes ACCESS_ABSTAIN if the object class is not supported. Votes
 * ACCESS_GRANTED if there is a granted authority which equals attribute
 * prefix + module name, or the module name is in the always accessible set.
 * Otherwise votes ACCESS_DENIED.
 */
@Override
public int vote( Authentication authentication, Object object, Collection<ConfigAttribute> attributes )
{
    if ( !supports( object.getClass() ) )
    {
        log.debug( "ACCESS_ABSTAIN [" + object.toString() + "]: Class not supported." );

        return ACCESS_ABSTAIN;
    }

    ActionConfig target = (ActionConfig) object;

    if ( alwaysAccessible.contains( target.getPackageName() ) )
    {
        log.debug( "ACCESS_GRANTED [" + target.getPackageName() + "] by configuration." );

        return ACCESS_GRANTED;
    }

    String requiredAuthority = attributePrefix + target.getPackageName();

    for ( GrantedAuthority grantedAuthority : authentication.getAuthorities() )
    {
        if ( grantedAuthority.getAuthority().equals( requiredAuthority ) )
        {
            log.debug( "ACCESS_GRANTED [" + target.getPackageName() + "]" );

            return ACCESS_GRANTED;
        }
    }

    log.debug( "ACCESS_DENIED [" + target.getPackageName() + "]" );

    return ACCESS_DENIED;
}
 
Example #25
Source File: AccessDecisionManagerImpl.java    From bdf3 with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings({ "rawtypes", "unchecked" })
@Override
public void decide(Authentication authentication, Object object,
		Collection<ConfigAttribute> configAttributes)
		throws AccessDeniedException, InsufficientAuthenticationException {
	if (userService.isAdministrator()) {
		return;
	}
	int deny = 0;
	for (AccessDecisionVoter voter : getDecisionVoters()) {
		if (voter.supports(object.getClass())) {
			int result = voter.vote(authentication, object, configAttributes);
			if (logger.isDebugEnabled()) {
				logger.debug("Voter: " + voter + ", returned: " + result);
			}
			switch (result) {
			case AccessDecisionVoter.ACCESS_GRANTED:
				return;
			case AccessDecisionVoter.ACCESS_DENIED:
				deny++;
				break;
			default:
				break;
			}
		}
	}

	if (deny > 0) {
		throw new AccessDeniedException(messages.getMessage(
				"AbstractAccessDecisionManager.accessDenied", "Access is denied"));
	}

	setAllowIfAllAbstainDecisions(allowIfAllAbstainDecisions);
	checkAllowIfAllAbstainDecisions();

}
 
Example #26
Source File: UrlSecurityMetadataSource.java    From bdf3 with Apache License 2.0 5 votes vote down vote up
public Collection<ConfigAttribute> getAttributes(Object object) {
	final HttpServletRequest request = ((FilterInvocation) object).getRequest();
	try {
		for (Map.Entry<RequestMatcher, Collection<ConfigAttribute>> entry : getRequestMap()
			.entrySet()) {
			if (entry.getKey().matches(request)) {
				return entry.getValue();
			}
		}
	} catch (Exception e) {
		e.printStackTrace();
	}
	
	return null;
}
 
Example #27
Source File: AccessManager.java    From open-cloud with MIT License 5 votes vote down vote up
private Collection<ConfigAttribute> getAttributes(String requestPath) {
    // 匹配动态权限
    AtomicReference<Collection<ConfigAttribute>> attributes = new AtomicReference<>();
    resourceLocator.getConfigAttributes().keySet().stream()
            .filter(r -> !"/**".equals(r))
            .filter(r -> pathMatch.match(r, requestPath))
            .findFirst().ifPresent(r -> {
        attributes.set(resourceLocator.getConfigAttributes().get(r));
    });
    if (attributes.get() != null) {
        return attributes.get();
    }
    return SecurityConfig.createList("AUTHORITIES_REQUIRED");
}
 
Example #28
Source File: MethodWebExpressionVoter.java    From onetwo with Apache License 2.0 5 votes vote down vote up
private WebExpressionConfigAttribute findConfigAttribute(
		Collection<ConfigAttribute> attributes) {
	for (ConfigAttribute attribute : attributes) {
		if (attribute instanceof WebExpressionConfigAttribute) {
			return (WebExpressionConfigAttribute) attribute;
		}
	}
	return null;
}
 
Example #29
Source File: UrlSourceBuilder.java    From lemon with Apache License 2.0 5 votes vote down vote up
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);
}
 
Example #30
Source File: MallSecurityConfig.java    From mall-swarm with Apache License 2.0 5 votes vote down vote up
@Bean
public DynamicSecurityService dynamicSecurityService() {
    return new DynamicSecurityService() {
        @Override
        public Map<String, ConfigAttribute> loadDataSource() {
            Map<String, ConfigAttribute> map = new ConcurrentHashMap<>();
            List<UmsResource> resourceList = resourceService.listAll();
            for (UmsResource resource : resourceList) {
                map.put(resource.getUrl(), new org.springframework.security.access.SecurityConfig(resource.getId() + ":" + resource.getName()));
            }
            return map;
        }
    };
}