初始化提交

This commit is contained in:
2021-01-20 18:30:23 +08:00
commit 3eb965f380
208 changed files with 8103 additions and 0 deletions

16
auth/authentication-server/.gitignore vendored Normal file
View File

@ -0,0 +1,16 @@
target/
logs/
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr

View File

@ -0,0 +1,107 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>business.chaoran</groupId>
<artifactId>authentication-server</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<!-- <packaging>jar</packaging>-->
<name>authentication-server</name>
<description>Demo Oauth2 project for Spring Cloud Oauth2 Authentication Server</description>
<parent>
<groupId>business.chaoran</groupId>
<artifactId>auth</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<dependencies>
<dependency>
<groupId>business.chaoran</groupId>
<artifactId>web</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
<!--oauth2认证-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-security</artifactId>
</dependency>
<!--Swagger2 - RESTful API文档-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
</dependency>
<!--jetcache缓存 -->
<dependency>
<groupId>com.alicp.jetcache</groupId>
<artifactId>jetcache-starter-redis</artifactId>
</dependency>
<!-- 独立运行依赖-->
<!-- <dependency>-->
<!-- <groupId>org.springframework.boot</groupId>-->
<!-- <artifactId>spring-boot-starter-web</artifactId>-->
<!-- </dependency>-->
<!-- tomcat部署运行依赖-->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</exclusion>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
</dependency>
</dependencies>
<!-- tomcat容器运行构建工具-->
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>2.1.4.RELEASE</version>
<executions>
<execution>
<goals>
<goal>build-info</goal>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>3.0.0</version>
</plugin>
</plugins>
<finalName>authentication-server</finalName>
</build>
</project>

View File

@ -0,0 +1,24 @@
package com.springboot.cloud.auth.authentication;
import com.alicp.jetcache.anno.config.EnableCreateCacheAnnotation;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients
@EnableCreateCacheAnnotation
public class Oauth2AuthenticationApplication extends SpringBootServletInitializer{
public static void main(String[] args) {
SpringApplication.run(Oauth2AuthenticationApplication.class, args);
}
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
return builder.sources(Oauth2AuthenticationApplication.class);
}
}

View File

@ -0,0 +1,104 @@
package com.springboot.cloud.auth.authentication.config;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.springboot.cloud.auth.authentication.events.BusReceiver;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer;
import org.springframework.amqp.rabbit.listener.adapter.MessageListenerAdapter;
import org.springframework.amqp.support.converter.ContentTypeDelegatingMessageConverter;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* 消息设置
*/
@Configuration
@Slf4j
public class BusConfig {
private static final String EXCHANGE_NAME = "spring-boot-exchange";
private static final String ROUTING_KEY = "organization-popedom";
@Value("${spring.application.name}")
private String appName;
/**
* 配置监听队列mq只能直接监听队列不能直接监听交换机
* @return 队列
*/
@Bean
Queue queue() {
String queueName = new Base64UrlNamingStrategy(appName + ".").generateName();
log.info("queue name:{}", queueName);
return new Queue(queueName, false);
}
/**
* 采用主题交换机
* @return 主题交换机
*/
@Bean
TopicExchange exchange() {
log.info("exchange:{}", EXCHANGE_NAME);
return new TopicExchange(EXCHANGE_NAME);
}
/**
* 将队列绑定到主题交换机上以router_key作为键
* @param queue
* @param exchange
* @return
*/
@Bean
Binding binding(Queue queue, TopicExchange exchange) {
log.info("binding {} to {} with {}", queue, exchange, ROUTING_KEY);
return BindingBuilder.bind(queue).to(exchange).with(ROUTING_KEY);
}
/**
* 设置消息处理监听器
* @param connectionFactory mq连接工厂用于配置mq服务器地址端口连接关闭或者断开监听器等等
* @param messageListenerAdapter 消息监听适配器用于收到消息后对消息进行处理或者是代理到其他对象进行处理的适配器默认处理方法为handleMessage
* @param queue 消息接收队列,可以配置多个队列
* @return 消息监听容器,可以设置消费者数量、最大最小数量、批量消费等等
*/
@Bean
SimpleMessageListenerContainer simpleMessageListenerContainer(ConnectionFactory connectionFactory, MessageListenerAdapter messageListenerAdapter, Queue queue) {
log.info("init simpleMessageListenerContainer {}", queue.getName());
SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(connectionFactory);
container.setQueueNames(queue.getName());
container.setMessageListener(messageListenerAdapter);
return container;
}
/**
* 设置消息监听适配器
* @param busReceiver 处理消息的代理对象
* @param messageConverter 消息转换器此处用Jackson作为json转换工具类
* @return
*/
@Bean
MessageListenerAdapter messageListenerAdapter(BusReceiver busReceiver, MessageConverter messageConverter) {
log.info("new listener");
return new MessageListenerAdapter(busReceiver, messageConverter);
}
/**
* 消息转换器
* @return Jackson转换器
*/
@Bean
public MessageConverter messageConverter() {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
return new ContentTypeDelegatingMessageConverter(new Jackson2JsonMessageConverter(objectMapper));
}
}

View File

@ -0,0 +1,21 @@
package com.springboot.cloud.auth.authentication.config;
/*
**********************************************
* DATE PERSON REASON
* 2020/12/7 FXY Created
**********************************************
*/
import com.springboot.cloud.common.web.interceptor.FeignBasicAuthRequestInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class InterceptConfig {
@Bean
public FeignBasicAuthRequestInterceptor interceptor(){
return new FeignBasicAuthRequestInterceptor();
}
}

View File

@ -0,0 +1,19 @@
package com.springboot.cloud.auth.authentication.config;
import com.springboot.cloud.auth.authentication.service.PopedomService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
@Component
class LoadResourceDefine {
@Autowired
private PopedomService popedomService;
@PostConstruct
public void resourceConfigAttributes() {
popedomService.loadPopedom();
}
}

View File

@ -0,0 +1,56 @@
package com.springboot.cloud.auth.authentication.config;
/*
**********************************************
* DATE PERSON REASON
* 2020-12-24 FXY Created
**********************************************
*/
import com.alibaba.cloud.nacos.registry.NacosAutoServiceRegistration;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.annotation.Configuration;
import javax.management.MBeanServer;
import javax.management.ObjectName;
import javax.management.Query;
import java.lang.management.ManagementFactory;
import java.util.Set;
@Configuration
@Slf4j
public class NacosRegisterConfig implements ApplicationRunner {
@Autowired(required = false)
private NacosAutoServiceRegistration registration;
private Integer port;
public NacosRegisterConfig() {
try {
this.port = Integer.parseInt(getTomcatPort());
} catch (Exception e) {
log.error("获取tomcat端口出错了原因{}", e.toString());
}
}
@Override
public void run(ApplicationArguments args) {
if (registration != null && port != null) {
registration.setPort(port);
registration.start();
}
}
//获取tomcat端口
private String getTomcatPort() throws Exception {
MBeanServer beanServer = ManagementFactory.getPlatformMBeanServer();
Set<ObjectName> objectNames = beanServer.queryNames(new ObjectName("*:type=Connector,*"), Query.match(Query.attr("protocol"), Query.value("HTTP/1.1")));
String port = objectNames.iterator().next().getKeyProperty("port");
return port;
}
}

View File

@ -0,0 +1,51 @@
package com.springboot.cloud.auth.authentication.config;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;
@Slf4j
@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
@Value("${spring.security.oauth2.jwt.signingKey}")
private String signingKey;
@Override
public void configure(ResourceServerSecurityConfigurer resourceServerSecurityConfigurer) {
resourceServerSecurityConfigurer
.tokenStore(tokenStore())
.resourceId("WEBS");
}
@Override
public void configure(HttpSecurity http) throws Exception {
log.debug("HttpSecurity configure method");
http.csrf().disable();
http.authorizeRequests()
.antMatchers("/actuator/**").permitAll()
.antMatchers("/v2/api-docs").permitAll()
.anyRequest().authenticated();
}
@Bean
public TokenStore tokenStore() {
return new JwtTokenStore(accessTokenConverter());
}
@Bean
public JwtAccessTokenConverter accessTokenConverter() {
JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
converter.setSigningKey(signingKey);
return converter;
}
}

View File

@ -0,0 +1,26 @@
package com.springboot.cloud.auth.authentication.entity;
/*
**********************************************
* DATE PERSON REASON
* 2020-12-29 FXY Created
**********************************************
*/
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.Date;
@Data
@NoArgsConstructor
public class License {
private String companyId;
private String franchiserId;
private String applicationCode;
private String grade;
private Date expireDate;
private boolean isForever;
private String state;
}

View File

@ -0,0 +1,32 @@
package com.springboot.cloud.auth.authentication.entity;
/*
**********************************************
* DATE PERSON REASON
* 2020-12-29 FXY Created
**********************************************
*/
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
public class Popedom {
private String id;
private String applicationCode;
private String name;
private String parentId;
private String url;
private String icon;
private String isMenu;
private String description;
private String path;
private String redirect;
private String component;
private String title;
private boolean alwaysShow;
private boolean hidden;
private String companyId;
private Integer orderNo;
}

View File

@ -0,0 +1,30 @@
package com.springboot.cloud.auth.authentication.events;
import com.springboot.cloud.auth.authentication.entity.Popedom;
import com.springboot.cloud.auth.authentication.service.PopedomService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.listener.adapter.MessageListenerAdapter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.List;
/**
* 消息接收者收到消息后进行处理内部反射调用默认回调方法handleMessage,方法参数由消息
* 发送方和接收方约定,方法参数尽可能作为一个对象,多个参数向上封装成一个对象
*
* @see MessageListenerAdapter
* @see org.springframework.amqp.core.MessageListener
*/
@Component
@Slf4j
public class BusReceiver {
@Autowired
private PopedomService popedomService;
public void handleMessage(List<Popedom> popedoms) {
log.info("Received Message:<{}>", popedoms);
popedomService.savePopedom(popedoms);
}
}

View File

@ -0,0 +1,24 @@
package com.springboot.cloud.auth.authentication.provider;
import com.springboot.cloud.auth.authentication.entity.License;
import com.springboot.cloud.auth.authentication.entity.Popedom;
import com.springboot.cloud.common.core.entity.vo.Result;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import java.util.List;
@FeignClient(name = "organization", fallback = PopedomProviderFallback.class, path = "organization")
//@FeignClient(name = "organization", fallback = PopedomProviderFallback.class)
public interface PopedomProvider {
@GetMapping(value = "/company/getAllPopedom")
Result<List<Popedom>> popedoms();
@GetMapping(value = "/company/getPopedom")
Result<List<Popedom>> popedoms(@RequestParam("companyId") String companyId,@RequestParam("username")String username);
@GetMapping(value = "/company/license")
Result<License> license(@RequestParam("companyId")String companyId,@RequestParam("applicationCode")String applicationCode);
}

View File

@ -0,0 +1,36 @@
package com.springboot.cloud.auth.authentication.provider;
import com.springboot.cloud.auth.authentication.entity.License;
import com.springboot.cloud.auth.authentication.entity.Popedom;
import com.springboot.cloud.common.core.entity.vo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
@Component
@Slf4j
public class PopedomProviderFallback implements PopedomProvider {
@Override
public Result<List<Popedom>> popedoms() {
log.error("认证服务启动时加载资源异常!未加载到资源!");
return Result.fail();
}
@Override
public Result<List<Popedom>> popedoms(String companyId, String username) {
log.error("认证服务查询用户异常!查询用户资源为空!");
return Result.success(new ArrayList<Popedom>());
}
@Override
public Result<License> license(String companyId, String applicationCode) {
log.error("认证服务查询企业应用有效期异常!企业应用过期!");
return Result.success(new License());
}
}

View File

@ -0,0 +1,34 @@
package com.springboot.cloud.auth.authentication.rest;
import com.springboot.cloud.auth.authentication.service.AuthenticationService;
import com.springboot.cloud.common.core.entity.vo.Result;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
@RestController
@Api("auth")
@Slf4j
public class AuthenticationController {
@Autowired
AuthenticationService authenticationService;
@ApiOperation(value = "权限验证", notes = "根据用户token访问的url和method判断用户是否有权限访问")
@ApiImplicitParams({
@ApiImplicitParam(paramType = "query", name = "url", value = "访问的url", required = true, dataType = "string"),
@ApiImplicitParam(paramType = "query", name = "method", value = "访问的method", required = true, dataType = "string")
})
@ApiResponses(@ApiResponse(code = 200, message = "处理成功", response = Result.class))
@PostMapping(value = "/auth/permission")
public Result decide(@RequestParam String url, HttpServletRequest request) {
boolean decide = authenticationService.decide(new HttpServletRequestAuthWrapper(request, url));
return Result.success(decide);
}
}

View File

@ -0,0 +1,22 @@
package com.springboot.cloud.auth.authentication.rest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
public class HttpServletRequestAuthWrapper extends HttpServletRequestWrapper {
private String url;
/**
* @param url
*/
public HttpServletRequestAuthWrapper(HttpServletRequest request, String url) {
super(request);
this.url = url;
}
@Override
public String getServletPath() {
return this.url;
}
}

View File

@ -0,0 +1,17 @@
package com.springboot.cloud.auth.authentication.service;
import org.springframework.stereotype.Service;
import javax.servlet.http.HttpServletRequest;
@Service
public interface AuthenticationService {
/**
* 校验权限
*
* @param authRequest
* @return 是否有权限
*/
boolean decide(HttpServletRequest authRequest);
}

View File

@ -0,0 +1,31 @@
package com.springboot.cloud.auth.authentication.service;
import com.google.common.base.Objects;
import lombok.Getter;
import org.springframework.http.HttpMethod;
import org.springframework.security.web.servlet.util.matcher.MvcRequestMatcher;
import org.springframework.web.servlet.handler.HandlerMappingIntrospector;
@Getter
public class NewMvcRequestMatcher extends MvcRequestMatcher {
private String pattern;
public NewMvcRequestMatcher(HandlerMappingIntrospector introspector, String pattern) {
super(introspector, pattern);
this.pattern = pattern;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
NewMvcRequestMatcher that = (NewMvcRequestMatcher) o;
return Objects.equal(pattern, that.pattern);
}
@Override
public int hashCode() {
return Objects.hashCode(pattern);
}
}

View File

@ -0,0 +1,52 @@
package com.springboot.cloud.auth.authentication.service;
import com.springboot.cloud.auth.authentication.entity.Popedom;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.stereotype.Service;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
@Service
public interface PopedomService {
/**
* 动态新增更新权限
*
* @param popedoms
*/
void savePopedom(List<Popedom> popedoms);
/**
* 动态删除权限
*
* @param popedom
*/
void removePopedom(Popedom popedom);
/**
* 加载权限资源数据
*/
void loadPopedom();
/**
* 根据url和method查询到对应的权限信息
*
* @param authRequest
* @return
*/
List<ConfigAttribute> findConfigAttributesByUrl(HttpServletRequest authRequest);
/**
* 根据用户名查询 该用户所拥有的角色对应的资源信息
* @param companyId
* @param username
* @return
*/
List<Popedom> queryByUsername(String companyId,String username);
/**
* 资源对应的应用是否过期
*/
boolean license(String companyId, String applicationCode);
}

View File

@ -0,0 +1,84 @@
package com.springboot.cloud.auth.authentication.service.impl;
import com.springboot.cloud.auth.authentication.entity.Popedom;
import com.springboot.cloud.auth.authentication.service.AuthenticationService;
import com.springboot.cloud.auth.authentication.service.PopedomService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Optional;
@Service
@Slf4j
public class AuthenticationServiceImpl implements AuthenticationService {
@Autowired
private PopedomService popedomService;
/**
* @param authRequest 访问的url,method
* @return 有权限true, 无权限或全局资源中未找到请求url返回否
*/
@Override
public boolean decide(HttpServletRequest authRequest) {
log.debug("正在访问的url是:{}", authRequest.getServletPath());
//获取用户认证信息
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
//获取此url访问对应的权限资源信息
List<ConfigAttribute> configAttributes = popedomService.findConfigAttributesByUrl(authRequest);
if (configAttributes.size() == 0) {
//如果未匹配到资源,则返回未授权
return false;
} else if (configAttributes.size() == 1) {
//默认授权所有资源,所有资源都会匹配,如果仅匹配到一个资源,则必定不是功能接口
return true;
} else {
String companyId = Optional.ofNullable(authRequest.getParameter("companyId")).orElseGet(String::new);
// String companyId = Optional.ofNullable(UserContextHolder.getInstance().getCurrentCompany()).orElseGet(String::new);
//获取此访问用户所有角色拥有的权限资源
List<Popedom> userPopedoms = findPopedomByUsername(companyId, authentication.getName());
//用户拥有权限资源 与 url要求的资源进行对比
return isMatch(companyId,configAttributes, userPopedoms);
}
}
/**
* url对应资源与用户拥有资源进行匹配
* 前端传入所在公司
* @param userPopedoms
* @return
*/
public boolean isMatch(String companyId,List<ConfigAttribute> urlConfigAttributes, List<Popedom> userPopedoms) {
//首先检查用户所属角色是否有资源权限
Optional<Popedom> optionalPopedom = userPopedoms.stream().filter(popedom -> urlConfigAttributes.contains(new SecurityConfig(popedom.getId()))).findAny();
if(optionalPopedom.isPresent()){
//再检查用户所在公司应用是否过期
return popedomService.license(companyId, optionalPopedom.orElseGet(Popedom::new).getApplicationCode());
}else{
return false;
}
}
/**
* 根据用户所被授予的角色,查询到用户所拥有的资源
*
* @param username
* @return
*/
private List<Popedom> findPopedomByUsername(String companyId, String username) {
//用户被授予的角色资源
List<Popedom> popedoms = popedomService.queryByUsername(companyId, username);
if (log.isDebugEnabled()) {
log.debug("用户被授予角色的资源数量是:{}, 资源集合信息为:{}", popedoms.size(), popedoms);
}
return popedoms;
}
}

View File

@ -0,0 +1,127 @@
package com.springboot.cloud.auth.authentication.service.impl;
import com.springboot.cloud.auth.authentication.entity.License;
import com.springboot.cloud.auth.authentication.entity.Popedom;
import com.springboot.cloud.auth.authentication.provider.PopedomProvider;
import com.springboot.cloud.auth.authentication.service.NewMvcRequestMatcher;
import com.springboot.cloud.auth.authentication.service.PopedomService;
import com.springboot.cloud.common.core.entity.vo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.servlet.util.matcher.MvcRequestMatcher;
import org.springframework.security.web.util.matcher.RequestMatcher;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.handler.HandlerMappingIntrospector;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;
@Service
@Slf4j
public class PopedomServiceImpl implements PopedomService {
@Autowired
private HandlerMappingIntrospector mvcHandlerMappingIntrospector;
@Autowired
private PopedomProvider popedomProvider;
/**
* 系统中权限分组集合
* key:companyId,value:{key:url,value:config}
*/
private static final Map<String, Map<RequestMatcher, ConfigAttribute>> popedomConfigAttributes = new HashMap<>();
@Override
public synchronized void savePopedom(List<Popedom> popedoms) {
popedoms.stream().forEach(popedom -> {
if (popedomConfigAttributes.containsKey(popedom.getCompanyId())) {
//如果包含company对应的权限表则更新
Map<RequestMatcher, ConfigAttribute> attributeMap = popedomConfigAttributes.get(popedom.getCompanyId());
attributeMap.put(this.newMvcRequestMatcher(popedom.getUrl()), new SecurityConfig(popedom.getId()));
} else {
//如果不包含company对应的权限表则新增
Map<RequestMatcher, ConfigAttribute> map = new HashMap<>();
map.put(this.newMvcRequestMatcher(popedom.getUrl()), new SecurityConfig(popedom.getId()));
popedomConfigAttributes.put(popedom.getCompanyId(), map);
}
});
log.info("popedomConfigAttributes size:{}", popedomConfigAttributes.size());
}
@Override
public synchronized void removePopedom(Popedom popedom) {
if (popedomConfigAttributes.containsKey(popedom.getCompanyId())) {
Map<RequestMatcher, ConfigAttribute> attributeMap = popedomConfigAttributes.get(popedom.getCompanyId());
attributeMap.remove(this.newMvcRequestMatcher(popedom.getUrl()));
}
log.info("resourceConfigAttributes size:{}", popedomConfigAttributes.size());
}
@Override
public synchronized void loadPopedom() {
Result<List<Popedom>> resourcesResult = popedomProvider.popedoms();
if (resourcesResult.isFail()) {
System.exit(1);
}
List<Popedom> popedoms = resourcesResult.getData();
//先根据公司分组,然后放入内存
Map<String, Map<RequestMatcher, ConfigAttribute>> map = popedoms.stream().filter(a -> null != a.getUrl() && !a.getUrl().equals("")).collect(Collectors.groupingBy(Popedom::getCompanyId, Collectors.toMap(a -> newMvcRequestMatcher(a.getUrl()), a -> new SecurityConfig(a.getId()))));
popedomConfigAttributes.putAll(map);
log.debug("init resourceConfigAttributes:{}", popedomConfigAttributes);
}
@Override
public List<ConfigAttribute> findConfigAttributesByUrl(HttpServletRequest authRequest) {
String companyId = Optional.ofNullable(authRequest.getParameter("companyId")).orElseGet(String::new);
// String companyId = Optional.ofNullable(UserContextHolder.getInstance().getCurrentCompany()).orElseGet(String::new);
if (popedomConfigAttributes.containsKey(companyId)) {
Map<RequestMatcher, ConfigAttribute> attributeMap = popedomConfigAttributes.get(companyId);
return attributeMap.keySet().stream()
.filter(requestMatcher -> requestMatcher.matches(authRequest))
.map(requestMatcher -> attributeMap.get(requestMatcher))
.peek(urlConfigAttribute -> log.debug("url在资源池中配置{}", urlConfigAttribute.getAttribute()))
.collect(Collectors.toList());
} else {
return Collections.emptyList();
}
}
@Override
public List<Popedom> queryByUsername(String companyId, String username) {
return popedomProvider.popedoms(companyId, username).getData();
}
@Override
public boolean license(String companyId, String applicationCode) {
Result<License> licenseResult = popedomProvider.license(companyId, applicationCode);
if (licenseResult.isFail()) {
return false;
}
License data = licenseResult.getData();
if (null == data) {
return false;
}
if (data.isForever()) {
return true;
}
if (data.getExpireDate().getTime() > new Date().getTime()) {
return true;
} else {
return false;
}
}
/**
* 创建RequestMatcher
*
* @param url
* @return
*/
private MvcRequestMatcher newMvcRequestMatcher(String url) {
return new NewMvcRequestMatcher(mvcHandlerMappingIntrospector, url);
}
}

View File

@ -0,0 +1,54 @@
package com.springboot.cloud.auth.authentication;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Lists;
import org.junit.Test;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.web.servlet.util.matcher.MvcRequestMatcher;
import org.springframework.web.servlet.handler.HandlerMappingIntrospector;
import java.util.List;
import java.util.stream.Collectors;
public class ApplicationTests {
@Test
public void testMethod() {
List<SimpleGrantedAuthority> authorities;
SimpleGrantedAuthority admin = new SimpleGrantedAuthority("ADMIN");
SimpleGrantedAuthority user = new SimpleGrantedAuthority("USER");
authorities = Lists.newArrayList(admin, user);
authorities.stream().map(authority -> authority.getAuthority()).collect(Collectors.toList());
}
@Test
public void testMethod1() throws JsonProcessingException {
// Resource resource = new Resource();
// resource.setCode("user_manager:all");
// resource.setMethod("GET");
// resource.setUrl("/users/a");
//
// ObjectMapper objectMapper = new ObjectMapper();
// objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
//
// System.out.println(objectMapper.writeValueAsString(resource));
}
@Test
public void testMatcher() {
MvcRequestMatcher mvcRequestMatcher = new MvcRequestMatcher(new HandlerMappingIntrospector(), "/users/{id}");
System.out.println(mvcRequestMatcher.matches(new MockHttpServletRequest("GET", "/users/1")));
System.out.println(mvcRequestMatcher.matches(new MockHttpServletRequest("GET", "/users/aaa")));
System.out.println(mvcRequestMatcher.matches(new MockHttpServletRequest("GET", "/users")));
System.out.println(mvcRequestMatcher.matches(new MockHttpServletRequest("POST", "/users/1")));
System.out.println(mvcRequestMatcher.matches(new MockHttpServletRequest("PUT", "/users/1")));
System.out.println(mvcRequestMatcher.matches(new MockHttpServletRequest("DELETE", "/users/1")));
}
}

View File

@ -0,0 +1,31 @@
package com.springboot.cloud.auth.authentication.service.impl;
import com.google.common.collect.Sets;
import com.springboot.cloud.auth.authentication.entity.Popedom;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.security.access.SecurityConfig;
import java.util.Set;
public class AuthenticationServiceImplTest {
@Test
public void testIsMatch_假如存在如上资源信息_当给定包含在资源信息时_那么返回true() {
AuthenticationServiceImpl authenticationServiceImpl = new AuthenticationServiceImpl();
Popedom popedom = new Popedom();
popedom.setApplicationCode("user_manager:view");
Set<Popedom> popedoms = Sets.newHashSet(popedom);
// Assert.assertTrue(authenticationServiceImpl.isMatch(new SecurityConfig("user_manager:view"), popedoms));
}
@Test
public void testIsMatch_假如存在如上资源信息_当给不包含在资源信息时_那么返回false() {
AuthenticationServiceImpl authenticationServiceImpl = new AuthenticationServiceImpl();
Popedom popedom = new Popedom();
popedom.setApplicationCode("user_manager:manager");
Set<Popedom> popedoms = Sets.newHashSet(popedom);
// Assert.assertFalse(authenticationServiceImpl.isMatch(new SecurityConfig("user_manager:view"), popedoms));
}
}

View File

@ -0,0 +1,73 @@
package com.springboot.cloud.auth.authentication.service.impl;
import com.springboot.cloud.auth.authentication.provider.PopedomProvider;
import com.springboot.cloud.auth.authentication.rest.HttpServletRequestAuthWrapper;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.security.access.ConfigAttribute;
//@RunWith(SpringRunner.class)
//@SpringBootTest
public class PopedomServiceImplTest {
/* private Map<RequestMatcher, ConfigAttribute> resourceConfigAttributes = new HashMap() {
{
MvcRequestMatcher mvcRequestMatcher1 = new MvcRequestMatcher(new HandlerMappingIntrospector(), "/users");
mvcRequestMatcher1.setMethod(HttpMethod.resolve("POST"));
MvcRequestMatcher mvcRequestMatcher2 = new MvcRequestMatcher(new HandlerMappingIntrospector(), "/users/{id}");
mvcRequestMatcher2.setMethod(HttpMethod.resolve("PUT"));
MvcRequestMatcher mvcRequestMatcher3 = new MvcRequestMatcher(new HandlerMappingIntrospector(), "/users/{id}");
mvcRequestMatcher3.setMethod(HttpMethod.resolve("DELETE"));
MvcRequestMatcher mvcRequestMatcher4 = new MvcRequestMatcher(new HandlerMappingIntrospector(), "/users/{id}");
mvcRequestMatcher4.setMethod(HttpMethod.resolve("GET"));
MvcRequestMatcher mvcRequestMatcher5 = new MvcRequestMatcher(new HandlerMappingIntrospector(), "/users/{id}/order");
mvcRequestMatcher5.setMethod(HttpMethod.resolve("GET"));
put(mvcRequestMatcher1, new SecurityConfig("user_manager:btn_add"));
put(mvcRequestMatcher2, new SecurityConfig("user_manager:btn_edit"));
put(mvcRequestMatcher3, new SecurityConfig("user_manager:btn_del"));
put(mvcRequestMatcher4, new SecurityConfig("user_manager:view"));
put(mvcRequestMatcher5, new SecurityConfig("user_order:view"));
}
};*/
@InjectMocks
private PopedomServiceImpl popedomServiceImpl;
@Mock
private PopedomProvider popedomProvider;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
}
@Test
@Ignore
public void testGetConfigAttributesByUrl_假如存在如上资源信息_当请求不存在method的资源时_那么返回NONEXISTENT_URL() {
// ConfigAttribute attributesByUrl = popedomServiceImpl
// .findConfigAttributesByUrl("", new HttpServletRequestAuthWrapper(new MockHttpServletRequest(), "/users/1/order"));
// Assert.assertEquals("NONEXISTENT_URL", attributesByUrl.getAttribute());
}
@Test
@Ignore
public void testGetConfigAttributesByUrl_假如存在如上资源信息_当请求url存在参数时_那么返回匹配的资源信息() {
// ConfigAttribute attributesByUrl = popedomServiceImpl
// .findConfigAttributesByUrl("", new HttpServletRequestAuthWrapper(new MockHttpServletRequest(), "/users/1/order"));
// Assert.assertEquals("NONEXISTENT_URL", attributesByUrl.getAttribute());
}
@Test
@Ignore
public void testGetConfigAttributesByUrl_假如存在如上资源信息_当请求存在的资源时_那么返回url和method都匹配的资源信息() {
// ConfigAttribute attributesByUrl = popedomServiceImpl
// .findConfigAttributesByUrl("", new HttpServletRequestAuthWrapper(new MockHttpServletRequest(), "/users"));
// Assert.assertEquals("user_manager:btn_add", attributesByUrl.getAttribute());
}
}