org.springframework.security.access.SecurityConfig Java Examples

The following examples show how to use org.springframework.security.access.SecurityConfig. 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: MyInvocationSecurityMetadataSourceService.java    From spring-boot-demo with MIT License 6 votes vote down vote up
/**
 * 初始化 所有资源 对应的角色
 */
public void loadResourceDefine() {
    map = new HashMap<>(16);
    //权限资源 和 角色对应的表  也就是 角色权限 中间表
    List<RolePermisson> rolePermissons = permissionMapper.getRolePermissions();

    //某个资源 可以被哪些角色访问
    for (RolePermisson rolePermisson : rolePermissons) {

        String url = rolePermisson.getUrl();
        String roleName = rolePermisson.getRoleName();
        ConfigAttribute role = new SecurityConfig(roleName);

        if (map.containsKey(url)) {
            map.get(url).add(role);
        } else {
            List<ConfigAttribute> list = new ArrayList<>();
            list.add(role);
            map.put(url, list);
        }
    }
}
 
Example #2
Source File: UrlResourcePopulator.java    From lemon with Apache License 2.0 6 votes vote down vote up
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);
}
 
Example #3
Source File: MyFilterInvocationSecurityMetadataSource.java    From base-admin with MIT License 6 votes vote down vote up
/**
 * 更新权限集合
 */
public void setRequestMap(List<SysAuthorityVo> authorityVoList){
    Map<RequestMatcher, Collection<ConfigAttribute>> map = new ConcurrentHashMap<>();
    for (SysAuthorityVo sysAuthorityVo : authorityVoList) {
        String authorityName = sysAuthorityVo.getAuthorityName();
        if (StringUtils.isEmpty(sysAuthorityVo.getAuthorityContent())) continue;
        for (String url : sysAuthorityVo.getAuthorityContent().split(",")) {
            Collection<ConfigAttribute> value = map.get(new AntPathRequestMatcher(url));
            if (StringUtils.isEmpty(value)) {
                ArrayList<ConfigAttribute> configs = new ArrayList<>();
                configs.add(new SecurityConfig(authorityName));
                map.put(new AntPathRequestMatcher(url), configs);
            } else {
                value.add(new SecurityConfig(authorityName));
            }
        }
    }
    this.requestMap = map;
}
 
Example #4
Source File: TestUrlResourcePopulator.java    From lemon with Apache License 2.0 6 votes vote down vote up
public void execute(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);
}
 
Example #5
Source File: SecurityAccessMetadataSource.java    From cola-cloud with MIT License 6 votes vote down vote up
public void loadUrlRoleMapping() {
    if(metadata != null){
        metadata.clear();
    }else{
        this.metadata = new HashMap<>();
    }
    //从缓存中获取数据
    Cache cache = cacheManager.getCache(ResourceCacheConstant.URL_ROLE_MAPPING_CACHE);
    Cache.ValueWrapper valueWrapper = cache.get(serviceId);
    Map<String, Set<String>> urlRoleMapping = null;
    if (valueWrapper != null) {
        urlRoleMapping = (Map<String, Set<String>>) valueWrapper.get();
    }
    //组装SpringSecurrty的数据
    if (urlRoleMapping != null) {
        for (Map.Entry<String, Set<String>> entry : urlRoleMapping.entrySet()) {
            Set<String> roleCodes = entry.getValue();
            Collection<ConfigAttribute> configs = CollectionUtils.collect(roleCodes.iterator(), input -> new SecurityConfig(input));
            this.metadata.put(entry.getKey(), configs);
        }
    }
}
 
Example #6
Source File: CustomInvocationSecurityMetadataSourceService.java    From bbs with GNU Affero General Public License v3.0 6 votes vote down vote up
private void loadResourceDefine() {
   	// 在Web服务器启动时,提取系统中的所有权限。
	//应当是资源为key, 权限为value。 资源通常为url, 权限就是那些以ROLE_为前缀的角色。 一个资源可以由多个权限来访问。
	List<PermissionObject> query = aclService.findModulePermission();

	if(query != null && query.size() >0){
		for (PermissionObject permissionObject : query) {	
			String methods = null;
			if(permissionObject.getMethods() != null && !"".equals(permissionObject.getMethods())){
				methods = permissionObject.getMethods();
			}
			RequestMatcher matcher = new MyAntPathRequestMatcher(permissionObject.getUrl(), methods,true);
			Collection<ConfigAttribute> atts = new ArrayList<ConfigAttribute>();//权限
			ConfigAttribute ca = new SecurityConfig(permissionObject.getPermissionName()); 
			atts.add(ca);
			if(requestMap.get(matcher) != null){//处理附加URL情况	
				requestMap.get(matcher).add(ca);
			}else{
				requestMap.put(matcher,atts);
			}
		}
	}
}
 
Example #7
Source File: SecurityMetadataSource.java    From hermes with Apache License 2.0 6 votes vote down vote up
/**
 * 设置配置参数
 * 
 * @param roleResource
 */
protected void putConfigAttributes(List<RoleResource> roleResources) {
	// 初始化
	Map<String, Collection<ConfigAttribute>> sources = new HashMap<String, Collection<ConfigAttribute>>();

	// 遍历数据进行归并
	for (RoleResource roleResource : roleResources) {
		// 判断映射中是否已经添加相关资源
		// 若尚未添加则进行处理
		if (!sources.containsKey(roleResource.getResource())) {
			// 添加数据
			sources.put(roleResource.getResource(), new LinkedList<ConfigAttribute>());

			// 加载并处理导航信息
			Navigation navigation = navigationService.loadById(roleResource.getResource());
			if (navigation != null && navigation.isAppPath()) {
				attributesMap.put(navigation.getTruePath(), sources.get(roleResource.getResource()));
				Logger.info("find path '%s'.", navigation.getTruePath());
			}
		}

		// 追加配置参数
		sources.get(roleResource.getResource()).add(new SecurityConfig(roleResource.getRole().getAuthCode()));
	}
}
 
Example #8
Source File: AuthoritySource.java    From BlogManagePlatform with Apache License 2.0 6 votes vote down vote up
/**
 * 初始化
 * @author Frodez
 * @date 2019-02-17
 */
@PostConstruct
private void init() {
	clear();
	List<Endpoint> endpoints = ContextUtil.bean(EndpointMapper.class).selectAll();
	//设置默认无权限角色
	defaultDeniedRoles = List.of(new SecurityConfig(ContextUtil.bean(SecurityProperties.class).getAuth().getDeniedRole()));
	//设置所有权限的缓存
	allCache = endpoints.stream().map((iter) -> new SecurityConfig(iter.getName())).collect(Collectors.toList());
	//设置按url和请求方式区分的权限缓存
	urlTypeCache = new HashMap<>();
	for (Endpoint endpoint : endpoints) {
		Map<HttpMethod, Collection<ConfigAttribute>> urlMap = urlTypeCache.get(endpoint.getPath());
		if (urlMap == null) {
			urlMap = buildNewUrlMap(endpoint);
		} else {
			modifyUrlMap(urlMap, endpoint);
		}
	}
	Assert.notNull(defaultDeniedRoles, "defaultDeniedRoles must not be null");
	Assert.notNull(allCache, "allCache must not be null");
	Assert.notNull(urlTypeCache, "urlTypeCache must not be null");
}
 
Example #9
Source File: SecurityFilterConfig.java    From cosmo with Apache License 2.0 6 votes vote down vote up
@Bean
public FilterRegistrationBean<?> securityFilterChain() {
    FilterSecurityInterceptor securityFilter = new FilterSecurityInterceptor();
    securityFilter.setAuthenticationManager(this.authManager);
    securityFilter.setAccessDecisionManager(this.davDecisionManager);
    LinkedHashMap<RequestMatcher, Collection<ConfigAttribute>> metadata = new LinkedHashMap<RequestMatcher, Collection<ConfigAttribute>>();
    metadata.put(AnyRequestMatcher.INSTANCE, SecurityConfig.createList(ROLES));
    securityFilter.setSecurityMetadataSource(new DefaultFilterInvocationSecurityMetadataSource(metadata));

    /*
     * Note that the order in which filters are defined is highly important.
     */
    SecurityFilterChain filterChain = new DefaultSecurityFilterChain(AnyRequestMatcher.INSTANCE,
            this.cosmoExceptionFilter, this.extraTicketFilter, this.ticketFilter,
            new BasicAuthenticationFilter(authManager, this.authEntryPoint), securityFilter);
    FilterChainProxy proxy = new FilterChainProxy(filterChain);
    proxy.setFirewall(this.httpFirewall);
    FilterRegistrationBean<?> filterBean = new FilterRegistrationBean<>(proxy);
    filterBean.addUrlPatterns(PATH_DAV);
    return filterBean;
}
 
Example #10
Source File: LoadResourceDefine.java    From JetfireCloud with Apache License 2.0 6 votes vote down vote up
@Bean
public Map<RequestMatcher, ConfigAttribute> resourceConfigAttributes() {
    Set<Resource> resources = resourceService.findAll();
    Map<RequestMatcher, ConfigAttribute> map = resources.stream()
            .collect(Collectors.toMap(
                    resource -> {
                        MvcRequestMatcher mvcRequestMatcher = new MvcRequestMatcher(mvcHandlerMappingIntrospector, resource.getUrl());
                        mvcRequestMatcher.setMethod(HttpMethod.resolve(resource.getMethod()));
                        return mvcRequestMatcher;
                    },
                    resource -> new SecurityConfig(resource.getCode())
                    )
            );
    log.debug("resourceConfigAttributes:{}", map);
    return map;
}
 
Example #11
Source File: MethodResourcePopulator.java    From lemon with Apache License 2.0 5 votes vote down vote up
public void execute(
        DelegatingMethodSecurityMetadataSource delegatingMethodSecurityMetadataSource,
        Map<String, String> resourceMap) {
    Assert.notNull(delegatingMethodSecurityMetadataSource);
    Assert.notNull(resourceMap);

    logger.info("refresh method resource");

    Map<String, List<ConfigAttribute>> methodMap = null;
    methodMap = new LinkedHashMap<String, List<ConfigAttribute>>();

    for (Map.Entry<String, String> entry : resourceMap.entrySet()) {
        methodMap.put(entry.getKey(), SecurityConfig
                .createListFromCommaDelimitedString(entry.getValue()));
    }

    MethodSecurityMetadataSource source = new MapBasedMethodSecurityMetadataSource(
            methodMap);
    List<MethodSecurityMetadataSource> sources = new ArrayList<MethodSecurityMetadataSource>();
    sources.add(source);

    List<MethodSecurityMetadataSource> methodSecurityMetadataSources = delegatingMethodSecurityMetadataSource
            .getMethodSecurityMetadataSources();
    methodSecurityMetadataSources.clear();
    methodSecurityMetadataSources.addAll(sources);

    Map attributeCache = (Map) BeanUtils.safeGetFieldValue(
            delegatingMethodSecurityMetadataSource, "attributeCache");
    attributeCache.clear();
}
 
Example #12
Source File: ResourceService.java    From SpringCloud with Apache License 2.0 5 votes vote down vote up
@Override
public ConfigAttribute findConfigAttributesByUrl(HttpServletRequest authRequest) {
    return resourceConfigAttributes.keySet().stream()
            .filter(requestMatcher -> requestMatcher.matches(authRequest))
            .map(requestMatcher -> resourceConfigAttributes.get(requestMatcher))
            .peek(urlConfigAttribute -> log.debug("url在资源池中配置:{}", urlConfigAttribute.getAttribute()))
            .findFirst()
            .orElse(new SecurityConfig("NONEXISTENT_URL"));
}
 
Example #13
Source File: AuthenticationServiceTest.java    From SpringCloud with Apache License 2.0 5 votes vote down vote up
@Test
public void testIsMatch_假如存在如上资源信息_当给定包含在资源信息时_那么返回true() {
    AuthenticationService authenticationService = new AuthenticationService();
    Resource resource = new Resource();
    resource.setCode("user_manager:view");
    Set<Resource> resources = Sets.newHashSet(resource);
    Assert.assertTrue(authenticationService.isMatch(new SecurityConfig("user_manager:view"), resources));
}
 
Example #14
Source File: AuthenticationServiceTest.java    From SpringCloud with Apache License 2.0 5 votes vote down vote up
@Test
public void testIsMatch_假如存在如上资源信息_当给不包含在资源信息时_那么返回false() {
    AuthenticationService authenticationService = new AuthenticationService();
    Resource resource = new Resource();
    resource.setCode("user_manager:manager");
    Set<Resource> resources = Sets.newHashSet(resource);
    Assert.assertFalse(authenticationService.isMatch(new SecurityConfig("user_manager:view"), resources));
}
 
Example #15
Source File: ServerWebExchangeMetadataSource.java    From spring-security-reactive with Apache License 2.0 5 votes vote down vote up
public Flux<ConfigAttribute> getConfigAttributes(ServerWebExchange exchange) {
	for(Map.Entry<ServerWebExchangeMatcher,SecurityConfig> entry : mappings.entrySet()) {
		if(entry.getKey().matches(exchange).isMatch()) {
			return Flux.just(entry.getValue());
		}
	}
	return Flux.empty();
}
 
Example #16
Source File: StrutsAuthorityUtils.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static Collection<ConfigAttribute> getConfigAttributes( Collection<String> authorities )
{
    Collection<ConfigAttribute> configAttributes = new HashSet<>();

    for ( String authority : authorities )
    {
        configAttributes.add( new SecurityConfig( authority ) );
    }

    return configAttributes;
}
 
Example #17
Source File: StandaloneSecurityHandler.java    From ranger with Apache License 2.0 5 votes vote down vote up
public void login(String userName, String password,
		ApplicationContext context) throws Exception {
	// [1] Create AUTH Token
	Authentication token = new UsernamePasswordAuthenticationToken(
			userName, password);

	// [2] Authenticate User
	AuthenticationManager am = (AuthenticationManager) context
			.getBean(AUTH_MANAGER_BEAN_NAME);
	token = am.authenticate(token);

	// [3] Check User Access
	AffirmativeBased accessDecisionManager = (AffirmativeBased) context
			.getBean(ACCESS_DECISION_MANAGER_BEAN_NAME);
	Collection<ConfigAttribute> list = new ArrayList<ConfigAttribute>();
	SecurityConfig config = new SecurityConfig(RangerConstants.ROLE_SYS_ADMIN);
	list.add(config);
	accessDecisionManager.decide(token, null, list);

	// [4] set token in spring context
	SecurityContextHolder.getContext().setAuthentication(token);

	// [5] Process Success login
	InetAddress thisIp = InetAddress.getLocalHost();
	sessionMgr.processStandaloneSuccessLogin(
			XXAuthSession.AUTH_TYPE_PASSWORD, thisIp.getHostAddress());
}
 
Example #18
Source File: AuthorizationService.java    From codeway_service with GNU General Public License v3.0 5 votes vote down vote up
/**
    * 根据url和method查询到对应的权限信息
    * @param authRequest request
    * @return ConfigAttribute
    */
   public ConfigAttribute findConfigAttributesByUrl(HttpServletRequest authRequest) {

	ConfigAttribute configAttribute = resourceConfigAttributes.keySet().stream()
			.filter(requestMatcher -> requestMatcher.matches(authRequest))
			.map(requestMatcher -> resourceConfigAttributes.get(requestMatcher))
			.peek(urlConfigAttribute -> LogBack.info("url在资源池中配置:{}", urlConfigAttribute.getAttribute()))
			.findFirst()
			.orElse(new SecurityConfig(NONEXISTENT_URL));
	return configAttribute;
}
 
Example #19
Source File: MethodSourceBuilder.java    From lemon with Apache License 2.0 5 votes vote down vote up
public void refresh() {
    if ((delegatingMethodSecurityMetadataSource == null)
            || (methodSourceFetcher == null)) {
        logger.info(
                "delegatingMethodSecurityMetadataSource : {}, methodSourceFetcher : {}",
                delegatingMethodSecurityMetadataSource, methodSourceFetcher);

        return;
    }

    logger.info("execute refresh");

    Map<String, List<ConfigAttribute>> methodMap = null;
    methodMap = new LinkedHashMap<String, List<ConfigAttribute>>();

    Map<String, String> resourceMap = methodSourceFetcher.getSource(null);

    for (Map.Entry<String, String> entry : resourceMap.entrySet()) {
        methodMap.put(entry.getKey(), SecurityConfig
                .createListFromCommaDelimitedString(entry.getValue()));
    }

    MethodSecurityMetadataSource source = new MapBasedMethodSecurityMetadataSource(
            methodMap);
    List<MethodSecurityMetadataSource> sources = new ArrayList<MethodSecurityMetadataSource>();
    sources.add(source);

    List<MethodSecurityMetadataSource> methodSecurityMetadataSources = delegatingMethodSecurityMetadataSource
            .getMethodSecurityMetadataSources();
    methodSecurityMetadataSources.clear();
    methodSecurityMetadataSources.addAll(sources);

    Map attributeCache = (Map) BeanUtils.safeGetFieldValue(
            delegatingMethodSecurityMetadataSource, "attributeCache");
    attributeCache.clear();
}
 
Example #20
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 #21
Source File: ConfigAwareSecurityMetadataSource.java    From engine with GNU General Public License v3.0 5 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public Collection<ConfigAttribute> getAttributes(final Object object) throws IllegalArgumentException {
    Callback<SecurityMetadataSource> callback = () -> {
        HierarchicalConfiguration siteConfig = ConfigUtils.getCurrentConfig();
        if (siteConfig != null) {
            List<HierarchicalConfiguration> restrictionsConfig = siteConfig.configurationsAt(URL_RESTRICTION_KEY);
            if (CollectionUtils.isNotEmpty(restrictionsConfig)) {
                LinkedHashMap<RequestMatcher, Collection<ConfigAttribute>> map = new LinkedHashMap<>();
                for (HierarchicalConfiguration restrictionConfig : restrictionsConfig) {
                    String url = restrictionConfig.getString(URL_RESTRICTION_URL_KEY);
                    String expression = restrictionConfig.getString(URL_RESTRICTION_EXPRESSION_KEY);
                    if (StringUtils.isNotEmpty(url) && StringUtils.isNotEmpty(expression)) {
                        AntPathRequestMatcher matcher = new AntPathRequestMatcher(url);
                        map.put(matcher, singleton(new SecurityConfig(expression)));
                    }
                }
                return new ExpressionBasedFilterInvocationSecurityMetadataSource(map,
                    new DefaultWebSecurityExpressionHandler());
            }
        }
        return new DefaultFilterInvocationSecurityMetadataSource(new LinkedHashMap<>());
    };

    SiteContext siteContext = SiteContext.getCurrent();
    if (siteContext != null) {
        SecurityMetadataSource metadataSource =
            cacheTemplate.getObject(siteContext.getContext(), callback, URL_RESTRICTIONS_CACHE_KEY);

        return metadataSource.getAttributes(object);
    }
    return null;
}
 
Example #22
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 #23
Source File: AuthorizationService.java    From codeway_service with GNU General Public License v3.0 5 votes vote down vote up
/**
 * 所有资源列表
 * 一个页面的数组组装可能存在多个ajax,这里我使用逗号分隔的url字段来处理
 */
public Map<RequestMatcher, ConfigAttribute> resourceConfigAttributes() {

	Set<Resource> resources = this.findResourceByCondition();

	// 处理逗号分隔的url
	Set<Resource> extendSets = new HashSet<>();
	resources.forEach(resource -> {
		if (StringUtils.isNotEmpty(resource.getUrl()) && resource.getUrl().contains(",")){
			Arrays.asList(resource.getUrl().split(",")).forEach(urlSplit -> {
				try {
					Resource resourceClone = (Resource)resource.clone();
					resourceClone.setId(String.valueOf(idGenerate.nextId()));
					resourceClone.setUrl(urlSplit);
					extendSets.add(resourceClone);
				} catch (CloneNotSupportedException e) {
					LogBack.error(e.getMessage());
					e.printStackTrace();
				}

			});
		}
	});
	resources.removeIf(resource -> StringUtils.isNotEmpty(resource.getUrl()) && resource.getUrl().contains(","));
	resources.addAll(extendSets);

	Map<RequestMatcher, ConfigAttribute> map = resources.stream().collect(Collectors.toMap(
			resource -> {
				MvcRequestMatcher mvcRequestMatcher = new MvcRequestMatcher(mvcHandlerMappingIntrospector, resource.getUrl());
				mvcRequestMatcher.setMethod(HttpMethod.resolve(resource.getMethod()));
				return mvcRequestMatcher;
			},
			resource -> new SecurityConfig(resource.getCode())
			)
	);
	return map;
}
 
Example #24
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 #25
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 #26
Source File: AuthorizationService.java    From codeway_service with GNU General Public License v3.0 5 votes vote down vote up
/**
 * 所有资源列表
 * 一个页面的数组组装可能存在多个ajax,这里我使用逗号分隔的url字段来处理
 */
public Map<RequestMatcher, ConfigAttribute> resourceConfigAttributes() {

	Set<Resource> resources = this.findResourceByCondition();

	// 处理逗号分隔的url
	Set<Resource> extendSets = new HashSet<>();
	resources.forEach(resource -> {
		if (StringUtils.isNotEmpty(resource.getUrl()) && resource.getUrl().contains(",")){
			Arrays.asList(resource.getUrl().split(",")).forEach(urlSplit -> {
				try {
					Resource resourceClone = (Resource)resource.clone();
					resourceClone.setId(String.valueOf(idGenerate.nextId()));
					resourceClone.setUrl(urlSplit);
					extendSets.add(resourceClone);
				} catch (CloneNotSupportedException e) {
					LogBack.error(e.getMessage());
					e.printStackTrace();
				}

			});
		}
	});
	resources.removeIf(resource -> StringUtils.isNotEmpty(resource.getUrl()) && resource.getUrl().contains(","));
	resources.addAll(extendSets);

	Map<RequestMatcher, ConfigAttribute> map = resources.stream().collect(Collectors.toMap(
			resource -> {
				MvcRequestMatcher mvcRequestMatcher = new MvcRequestMatcher(mvcHandlerMappingIntrospector, resource.getUrl());
				mvcRequestMatcher.setMethod(HttpMethod.resolve(resource.getMethod()));
				return mvcRequestMatcher;
			},
			resource -> new SecurityConfig(resource.getCode())
			)
	);
	return map;
}
 
Example #27
Source File: AuthorizationService.java    From codeway_service with GNU General Public License v3.0 5 votes vote down vote up
/**
    * 根据url和method查询到对应的权限信息
    * @param authRequest request
    * @return ConfigAttribute
    */
   public ConfigAttribute findConfigAttributesByUrl(HttpServletRequest authRequest) {

	ConfigAttribute configAttribute = resourceConfigAttributes.keySet().stream()
			.filter(requestMatcher -> requestMatcher.matches(authRequest))
			.map(requestMatcher -> resourceConfigAttributes.get(requestMatcher))
			.peek(urlConfigAttribute -> LogBack.info("url在资源池中配置:{}", urlConfigAttribute.getAttribute()))
			.findFirst()
			.orElse(new SecurityConfig(NONEXISTENT_URL));
	return configAttribute;
}
 
Example #28
Source File: AuthenticationService.java    From JetfireCloud with 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 #29
Source File: AuthenticationServiceTest.java    From JetfireCloud with Apache License 2.0 5 votes vote down vote up
@Test
public void testIsMatch_假如存在如上资源信息_当给定包含在资源信息时_那么返回true() {
    AuthenticationService authenticationService = new AuthenticationService(null);
    Resource resource = new Resource();
    resource.setCode("user_manager:view");
    Set<Resource> resources = Sets.newHashSet(resource);
    Assert.assertTrue(authenticationService.isMatch(new SecurityConfig("user_manager:view"), resources));
}
 
Example #30
Source File: AuthenticationServiceTest.java    From JetfireCloud with Apache License 2.0 5 votes vote down vote up
@Test
public void testIsMatch_假如存在如上资源信息_当给不包含在资源信息时_那么返回false() {
    AuthenticationService authenticationService = new AuthenticationService(null);
    Resource resource = new Resource();
    resource.setCode("user_manager:manager");
    Set<Resource> resources = Sets.newHashSet(resource);
    Assert.assertFalse(authenticationService.isMatch(new SecurityConfig("user_manager:view"), resources));
}