Java Code Examples for org.springframework.security.access.ConfigAttribute

The following examples show how to use org.springframework.security.access.ConfigAttribute. These examples are extracted from open source projects. 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
/**
 * 判定是否拥有权限的决策方法
 * @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 2
/**
 * 判定用户请求的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 3
Source Project: itweet-boot   Source File: MyAccessDecisionManager.java    License: 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 4
Source Project: bdf3   Source File: UrlRoleVoter.java    License: 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 5
Source Project: wallride   Source File: ProxySecureChannelProcessor.java    License: 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 6
Source Project: onetwo   Source File: JFishMethodSecurityMetadataSource.java    License: 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 7
@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 8
Source Project: mall   Source File: DynamicSecurityMetadataSource.java    License: 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 9
@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 10
Source Project: grpc-spring-boot-starter   Source File: AccessPredicateVoter.java    License: MIT License 5 votes vote down vote up
@Override
public int vote(final Authentication authentication, final Object object,
        final Collection<ConfigAttribute> attributes) {
    final AccessPredicateConfigAttribute attr = find(attributes);
    if (attr == null) {
        return ACCESS_ABSTAIN;
    }
    final boolean allowed = attr.getAccessPredicate().test(authentication);
    return allowed ? ACCESS_GRANTED : ACCESS_DENIED;
}
 
Example 11
/**
 * 返回请求的资源需要的角色
 */
@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 12
@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 13
/**
 * 判定是否拥有权限的决策方法
 * @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 14
Source Project: bdf3   Source File: UrlFilterConfigAttribueProvider.java    License: Apache License 2.0 5 votes vote down vote up
@Override
@Cacheable(cacheNames = Constants.REQUEST_MAP_CACHE_KEY, keyGenerator = Constants.KEY_GENERATOR_BEAN_NAME)
public Map<String, Collection<ConfigAttribute>> provide() {
	List<Url> urls = urlService.findAll();
	Map<String, Collection<ConfigAttribute>> requestMap = new LinkedHashMap<String, Collection<ConfigAttribute>>();
	for (Url url : urls) {
		if (validate(url)) {
			requestMap.put(url.getPath(), url.getAttributes());
		}
	}
	return requestMap;
}
 
Example 15
@Override
public boolean supports( ConfigAttribute configAttribute )
{
    for ( AccessDecisionManager accessDecisionManager : accessDecisionManagers )
    {
        if ( accessDecisionManager.supports( configAttribute ) )
        {
            return true;
        }
    }

    return false;
}
 
Example 16
/**
 * 判定是否拥有权限的决策方法
 * @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
@Override
public boolean supports(ConfigAttribute attribute) {
	if (IS_AUTHORIZED_LOG_ACCESS_CONFIG.equals(attribute.getAttribute())) {
		return true;
	}
	else {
		return false;
	}
}
 
Example 18
Source Project: open-cloud   Source File: AccessManager.java    License: 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 19
Source Project: bdf3   Source File: AccessDecisionManagerImpl.java    License: 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 20
Source Project: bdf3   Source File: UrlSecurityMetadataSource.java    License: 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 21
Source Project: open-cloud   Source File: AccessManager.java    License: 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 22
/**
 * 加载资源-权限关系
 */
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 23
Source Project: mall-swarm   Source File: MallSecurityConfig.java    License: 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;
        }
    };
}
 
Example 24
/**
 * 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 Project: JetfireCloud   Source File: AuthenticationServiceTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testGetConfigAttributesByUrl_假如存在如上资源信息_当请求不存在method的资源时_那么返回NONEXISTENT_URL() {
    AuthenticationService authenticationService = new AuthenticationService(this.resourceConfigAttributes);
    ConfigAttribute attributesByUrl = authenticationService
            .findConfigAttributesByUrl(new HttpServletRequestAuthWrapper(new MockHttpServletRequest(), "/users/1/order", "POST"));
    Assert.assertEquals("NONEXISTENT_URL", attributesByUrl.getAttribute());
}
 
Example 26
Source Project: JetfireCloud   Source File: AuthenticationService.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 根据url和method查询到对应的权限信息
 *
 * @param authRequest
 * @return
 */
public ConfigAttribute findConfigAttributesByUrl(HttpServletRequest authRequest) {
    return this.resourceConfigAttributes.keySet().stream()
            .filter(requestMatcher -> requestMatcher.matches(authRequest))
            .map(requestMatcher -> this.resourceConfigAttributes.get(requestMatcher))
            .peek(urlConfigAttribute -> log.debug("url在资源池中配置:{}", urlConfigAttribute.getAttribute()))
            .findFirst()
            .orElse(new SecurityConfig(NONEXISTENT_URL));
}
 
Example 27
/**
 * 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 28
Source Project: onetwo   Source File: MultiWebExpressionVoter.java    License: 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 29
Source Project: oauth2-resource   Source File: MyAccessDecisionManager.java    License: 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 30
Source Project: onetwo   Source File: MethodWebExpressionVoter.java    License: 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;
}