From e5d1fbedcfdd63f9e6883ef5d2fb23782bae520d Mon Sep 17 00:00:00 2001 From: 陈杰 <504987307@qq.com> Date: Thu, 27 Feb 2020 09:59:27 +0800 Subject: [PATCH] 认证中心 登录接口 --- cloud/autho/pom.xml | 139 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++------------------------------ cloud/autho/src/main/java/com/sincere/autho/AuthoApplication.java | 2 ++ cloud/autho/src/main/java/com/sincere/autho/Swagger2.java | 52 ++++++++++++++++++++++++++++++++++++++++++++++++++++ cloud/autho/src/main/java/com/sincere/autho/annotation/EnableLogging.java | 22 ---------------------- cloud/autho/src/main/java/com/sincere/autho/annotation/datasource/DataSource.java | 16 ---------------- cloud/autho/src/main/java/com/sincere/autho/annotation/log/LogAnnotation.java | 26 -------------------------- cloud/autho/src/main/java/com/sincere/autho/autoconfigure/LoggingConfigurationSelector.java | 23 ----------------------- cloud/autho/src/main/java/com/sincere/autho/autoconfigure/datasource/DataSourceAspect.java | 42 ------------------------------------------ cloud/autho/src/main/java/com/sincere/autho/autoconfigure/log/LogAnnotationAspect.java | 133 ------------------------------------------------------------------------------------------------------------------------------------- cloud/autho/src/main/java/com/sincere/autho/config/OAuth2ServerConfig.java | 260 -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- cloud/autho/src/main/java/com/sincere/autho/config/SecurityConfig.java | 129 --------------------------------------------------------------------------------------------------------------------------------- cloud/autho/src/main/java/com/sincere/autho/config/ValidateCodeSecurityConfig.java | 29 ----------------------------- cloud/autho/src/main/java/com/sincere/autho/control/LoginController.java | 35 +++++++++++++++++++++++++++++++++++ cloud/autho/src/main/java/com/sincere/autho/control/OAuth2Controller.java | 482 -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- cloud/autho/src/main/java/com/sincere/autho/control/UserController.java | 16 ---------------- cloud/autho/src/main/java/com/sincere/autho/dto/BaseDto.java | 36 ++++++++++++++++++++++++++++++++++++ cloud/autho/src/main/java/com/sincere/autho/dto/req/LoginReqDto.java | 32 ++++++++++++++++++++++++++++++++ cloud/autho/src/main/java/com/sincere/autho/handler/ExceptionHandlerAdvice.java | 63 --------------------------------------------------------------- cloud/autho/src/main/java/com/sincere/autho/handler/OauthLogoutHandler.java | 90 ------------------------------------------------------------------------------------------ cloud/autho/src/main/java/com/sincere/autho/log/dao/LogDao.java | 13 ------------- cloud/autho/src/main/java/com/sincere/autho/log/service/LogService.java | 11 ----------- cloud/autho/src/main/java/com/sincere/autho/log/service/impl/LogServiceImpl.java | 34 ---------------------------------- cloud/autho/src/main/java/com/sincere/autho/mapper/UserMapper.java | 10 ++++++++++ cloud/autho/src/main/java/com/sincere/autho/service/LoginService.java | 8 ++++++++ cloud/autho/src/main/java/com/sincere/autho/service/RedisAuthorizationCodeServices.java | 58 ---------------------------------------------------------- cloud/autho/src/main/java/com/sincere/autho/service/RedisClientDetailsService.java | 153 --------------------------------------------------------------------------------------------------------------------------------------------------------- cloud/autho/src/main/java/com/sincere/autho/service/impl/LoginServiceImpl.java | 25 +++++++++++++++++++++++++ cloud/autho/src/main/java/com/sincere/autho/token/RedisTemplateTokenStore.java | 331 ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- cloud/autho/src/main/java/com/sincere/autho/utils/SpringUtil.java | 35 ----------------------------------- cloud/autho/src/main/java/com/sincere/autho/utils/SysUserUtil.java | 41 ----------------------------------------- cloud/autho/src/main/resources/application.yaml | 98 +++++++++++++++----------------------------------------------------------------------------------- cloud/autho/src/main/resources/mapper/UserMapper.xml | 14 ++++++++++++++ cloud/common/src/main/java/com/sincere/common/util/TokenUtils.java | 2 +- cloud/getaway/src/main/java/com/sincere/getaway/client/filter/AccessFilter.java | 6 +++--- cloud/getaway/src/main/resources/application.yml | 8 +++++++- cloud/user_search/src/main/java/com/sincere/userSearch/controller/UserController.java | 4 ++-- cloud/user_search/src/main/resources/application.yaml | 2 +- 37 files changed, 352 insertions(+), 2128 deletions(-) create mode 100644 cloud/autho/src/main/java/com/sincere/autho/Swagger2.java delete mode 100644 cloud/autho/src/main/java/com/sincere/autho/annotation/EnableLogging.java delete mode 100644 cloud/autho/src/main/java/com/sincere/autho/annotation/datasource/DataSource.java delete mode 100644 cloud/autho/src/main/java/com/sincere/autho/annotation/log/LogAnnotation.java delete mode 100644 cloud/autho/src/main/java/com/sincere/autho/autoconfigure/LoggingConfigurationSelector.java delete mode 100644 cloud/autho/src/main/java/com/sincere/autho/autoconfigure/datasource/DataSourceAspect.java delete mode 100644 cloud/autho/src/main/java/com/sincere/autho/autoconfigure/log/LogAnnotationAspect.java delete mode 100644 cloud/autho/src/main/java/com/sincere/autho/config/OAuth2ServerConfig.java delete mode 100644 cloud/autho/src/main/java/com/sincere/autho/config/SecurityConfig.java delete mode 100644 cloud/autho/src/main/java/com/sincere/autho/config/ValidateCodeSecurityConfig.java create mode 100644 cloud/autho/src/main/java/com/sincere/autho/control/LoginController.java delete mode 100644 cloud/autho/src/main/java/com/sincere/autho/control/OAuth2Controller.java delete mode 100644 cloud/autho/src/main/java/com/sincere/autho/control/UserController.java create mode 100644 cloud/autho/src/main/java/com/sincere/autho/dto/BaseDto.java create mode 100644 cloud/autho/src/main/java/com/sincere/autho/dto/req/LoginReqDto.java delete mode 100644 cloud/autho/src/main/java/com/sincere/autho/handler/ExceptionHandlerAdvice.java delete mode 100644 cloud/autho/src/main/java/com/sincere/autho/handler/OauthLogoutHandler.java delete mode 100644 cloud/autho/src/main/java/com/sincere/autho/log/dao/LogDao.java delete mode 100644 cloud/autho/src/main/java/com/sincere/autho/log/service/LogService.java delete mode 100644 cloud/autho/src/main/java/com/sincere/autho/log/service/impl/LogServiceImpl.java create mode 100644 cloud/autho/src/main/java/com/sincere/autho/mapper/UserMapper.java create mode 100644 cloud/autho/src/main/java/com/sincere/autho/service/LoginService.java delete mode 100644 cloud/autho/src/main/java/com/sincere/autho/service/RedisAuthorizationCodeServices.java delete mode 100644 cloud/autho/src/main/java/com/sincere/autho/service/RedisClientDetailsService.java create mode 100644 cloud/autho/src/main/java/com/sincere/autho/service/impl/LoginServiceImpl.java delete mode 100644 cloud/autho/src/main/java/com/sincere/autho/token/RedisTemplateTokenStore.java delete mode 100644 cloud/autho/src/main/java/com/sincere/autho/utils/SpringUtil.java delete mode 100644 cloud/autho/src/main/java/com/sincere/autho/utils/SysUserUtil.java create mode 100644 cloud/autho/src/main/resources/mapper/UserMapper.xml diff --git a/cloud/autho/pom.xml b/cloud/autho/pom.xml index 06b0023..6e23c94 100644 --- a/cloud/autho/pom.xml +++ b/cloud/autho/pom.xml @@ -13,63 +13,142 @@ autho Demo project for Spring Boot - - 1.8 - Greenwich.SR2 - - com.sincere common - 0.0.1-SNAPSHOT + 1.0.0 - org.springframework.cloud - spring-cloud-starter-oauth2 + org.springframework.boot + spring-boot-starter-test + test - org.springframework.cloud - spring-cloud-starter-security - 2.1.3.RELEASE + spring-cloud-starter-feign + 1.3.6.RELEASE org.springframework.cloud - spring-cloud-starter-openfeign + spring-cloud-openfeign-core + 2.1.2.RELEASE - - org.springframework.boot - spring-boot-starter-data-redis + org.apache.commons + commons-lang3 + 3.3.2 - io.grpc - grpc-core - 1.18.0 + org.mybatis.spring.boot + mybatis-spring-boot-starter + 1.3.0 - - io.springfox - springfox-swagger2 - 2.9.2 + com.microsoft.sqlserver + mssql-jdbc + 6.4.0.jre8 - - io.springfox - springfox-swagger-ui - 2.9.2 + org.springframework.boot + spring-boot-starter-web - + + + + org.springframework.cloud + spring-cloud-dependencies + ${spring-cloud.version} + pom + import + + + + + + quartz_server + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.1 + + 1.8 + 1.8 + UTF-8 + + + + + + org.apache.maven.plugins + maven-jar-plugin + + + + com.sincere.userSearch.UserApplication + true + lib/ + + + ./config/ + + + + config/** + + + + + - org.springframework.boot - spring-boot-maven-plugin + org.apache.maven.plugins + maven-dependency-plugin + + + copy + package + + copy-dependencies + + + + ${project.build.directory}/lib + + + + + + + + org.apache.maven.plugins + maven-resources-plugin + 2.5 + + UTF-8 + + + + + maven-source-plugin + 2.2 + + true + + + + compile + + jar + + + - diff --git a/cloud/autho/src/main/java/com/sincere/autho/AuthoApplication.java b/cloud/autho/src/main/java/com/sincere/autho/AuthoApplication.java index 7bd0a97..fcbc35b 100644 --- a/cloud/autho/src/main/java/com/sincere/autho/AuthoApplication.java +++ b/cloud/autho/src/main/java/com/sincere/autho/AuthoApplication.java @@ -1,11 +1,13 @@ package com.sincere.autho; +import org.mybatis.spring.annotation.MapperScan; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; @EnableDiscoveryClient @SpringBootApplication +@MapperScan("com.sincere.autho.mapper") public class AuthoApplication { public static void main(String[] args) { diff --git a/cloud/autho/src/main/java/com/sincere/autho/Swagger2.java b/cloud/autho/src/main/java/com/sincere/autho/Swagger2.java new file mode 100644 index 0000000..92d536c --- /dev/null +++ b/cloud/autho/src/main/java/com/sincere/autho/Swagger2.java @@ -0,0 +1,52 @@ +package com.sincere.autho; + +import io.swagger.annotations.ApiOperation; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import springfox.documentation.builders.ApiInfoBuilder; +import springfox.documentation.builders.ParameterBuilder; +import springfox.documentation.builders.PathSelectors; +import springfox.documentation.builders.RequestHandlerSelectors; +import springfox.documentation.schema.ModelRef; +import springfox.documentation.service.ApiInfo; +import springfox.documentation.service.Parameter; +import springfox.documentation.spi.DocumentationType; +import springfox.documentation.spring.web.plugins.Docket; +import springfox.documentation.swagger2.annotations.EnableSwagger2; + +import java.util.ArrayList; +import java.util.List; + +@EnableSwagger2 +@Configuration //让Spring来加载该类配置 +public class Swagger2 { + + @Bean + public Docket createRestApi() { + ParameterBuilder ticketPar = new ParameterBuilder(); + List pars = new ArrayList(); + ticketPar.name("X-Authorization").description("user token") + .modelRef(new ModelRef("string")).parameterType("header") + .required(false).build(); //header中的ticket参数非必填,传空也可以 + pars.add(ticketPar.build()); + + + return new Docket(DocumentationType.SWAGGER_2) + .apiInfo(apiInfo()) + .enableUrlTemplating(true) + .select() + // 扫描所有有注解的api,用这种方式更灵活 + .apis(RequestHandlerSelectors.basePackage("com.sincere.autho.control")) + .paths(PathSelectors.any()) + .build().globalOperationParameters(pars); + + } + private ApiInfo apiInfo() { + return new ApiInfoBuilder() + .title("Spring Boot中使用Swagger2构建RESTful APIs") + .description("接口文档") + .termsOfServiceUrl("") + .version("1.0") + .build(); + } +} diff --git a/cloud/autho/src/main/java/com/sincere/autho/annotation/EnableLogging.java b/cloud/autho/src/main/java/com/sincere/autho/annotation/EnableLogging.java deleted file mode 100644 index 938ca89..0000000 --- a/cloud/autho/src/main/java/com/sincere/autho/annotation/EnableLogging.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.sincere.autho.annotation; - -import com.sincere.autho.autoconfigure.LoggingConfigurationSelector; -import org.springframework.context.annotation.Import; - -import java.lang.annotation.*; - - -/** - * 启动日志框架支持 - * @author owen - * @create 2017年7月2日 - */ - -@Target(ElementType.TYPE) -@Retention(RetentionPolicy.RUNTIME) -@Documented -//自动装配starter -@Import(LoggingConfigurationSelector.class) -public @interface EnableLogging{ -// String name() ; -} \ No newline at end of file diff --git a/cloud/autho/src/main/java/com/sincere/autho/annotation/datasource/DataSource.java b/cloud/autho/src/main/java/com/sincere/autho/annotation/datasource/DataSource.java deleted file mode 100644 index b0acc1d..0000000 --- a/cloud/autho/src/main/java/com/sincere/autho/annotation/datasource/DataSource.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.sincere.autho.annotation.datasource; - -import java.lang.annotation.*; - - -/** - * 数据源选择 - * @author owen - * @create 2017年7月2日 - */ -@Target({ElementType.METHOD, ElementType.TYPE}) -@Retention(RetentionPolicy.RUNTIME) -@Documented -public @interface DataSource { - String name(); -} \ No newline at end of file diff --git a/cloud/autho/src/main/java/com/sincere/autho/annotation/log/LogAnnotation.java b/cloud/autho/src/main/java/com/sincere/autho/annotation/log/LogAnnotation.java deleted file mode 100644 index bc01d2d..0000000 --- a/cloud/autho/src/main/java/com/sincere/autho/annotation/log/LogAnnotation.java +++ /dev/null @@ -1,26 +0,0 @@ -package com.sincere.autho.annotation.log; - -import java.lang.annotation.*; - -/** - * 日志注解 - * @author owen - * @create 2017年7月2日 - */ -@Target({ElementType.METHOD, ElementType.TYPE}) -@Retention(RetentionPolicy.RUNTIME) -@Documented -public @interface LogAnnotation { - - /** - * 模块 - * @return - */ - String module(); - - /** - * 记录执行参数 - * @return - */ - boolean recordRequestParam() default true; -} diff --git a/cloud/autho/src/main/java/com/sincere/autho/autoconfigure/LoggingConfigurationSelector.java b/cloud/autho/src/main/java/com/sincere/autho/autoconfigure/LoggingConfigurationSelector.java deleted file mode 100644 index 9caae02..0000000 --- a/cloud/autho/src/main/java/com/sincere/autho/autoconfigure/LoggingConfigurationSelector.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.sincere.autho.autoconfigure; - -import org.springframework.context.annotation.ImportSelector; -import org.springframework.core.type.AnnotationMetadata; - -/** - * @author owen - * @create 2017年7月2日 - * 装配bean - */ -public class LoggingConfigurationSelector implements ImportSelector { - - @Override - public String[] selectImports(AnnotationMetadata importingClassMetadata) { - // TODO Auto-generated method stub -// importingClassMetadata.getAllAnnotationAttributes(EnableEcho.class.getName()); - return new String[] { - "com.sincere.autho.autoconfigure.datasource.DataSourceAspect", - "com.sincere.autho.autoconfigure.log.LogAnnotationAspect" - }; - } - -} diff --git a/cloud/autho/src/main/java/com/sincere/autho/autoconfigure/datasource/DataSourceAspect.java b/cloud/autho/src/main/java/com/sincere/autho/autoconfigure/datasource/DataSourceAspect.java deleted file mode 100644 index 7f49439..0000000 --- a/cloud/autho/src/main/java/com/sincere/autho/autoconfigure/datasource/DataSourceAspect.java +++ /dev/null @@ -1,42 +0,0 @@ -package com.sincere.autho.autoconfigure.datasource; - -import com.sincere.autho.annotation.datasource.DataSource; -import com.sincere.common.config.DataSourceHolder; -import com.sincere.common.config.DataSourceKey; -import org.aspectj.lang.JoinPoint; -import org.aspectj.lang.annotation.After; -import org.aspectj.lang.annotation.Aspect; -import org.aspectj.lang.annotation.Before; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.core.annotation.Order; - -/** - * 切换数据源Advice - */ -@Aspect -@Order(-1) // 保证该AOP在@Transactional之前执行 -public class DataSourceAspect { - - private static final Logger logger = LoggerFactory.getLogger(DataSourceAspect.class); - - @Before("@annotation(ds)") - public void changeDataSource(JoinPoint point, DataSource ds) throws Throwable { - String dsId = ds.name(); - try { - DataSourceKey dataSourceKey = DataSourceKey.valueOf(dsId); - DataSourceHolder.setDataSourceKey(dataSourceKey); - } catch (Exception e) { - logger.error("数据源[{}]不存在,使用默认数据源 > {}", ds.name(), point.getSignature()); - } - - - } - - @After("@annotation(ds)") - public void restoreDataSource(JoinPoint point, DataSource ds) { - logger.debug("Revert DataSource : {transIdo} > {}", ds.name(), point.getSignature()); - DataSourceHolder.clearDataSourceKey(); - } - -} \ No newline at end of file diff --git a/cloud/autho/src/main/java/com/sincere/autho/autoconfigure/log/LogAnnotationAspect.java b/cloud/autho/src/main/java/com/sincere/autho/autoconfigure/log/LogAnnotationAspect.java deleted file mode 100644 index 3ae57e9..0000000 --- a/cloud/autho/src/main/java/com/sincere/autho/autoconfigure/log/LogAnnotationAspect.java +++ /dev/null @@ -1,133 +0,0 @@ -package com.sincere.autho.autoconfigure.log; - -import com.alibaba.fastjson.JSON; -import com.alibaba.fastjson.JSONObject; -import com.sincere.autho.annotation.log.LogAnnotation; -import com.sincere.autho.log.service.LogService; -import com.sincere.autho.log.service.impl.LogServiceImpl; -import com.sincere.autho.utils.SysUserUtil; -import com.sincere.common.model.log.SysLog; -import com.sincere.common.model.system.LoginAppUser; -import com.sincere.common.util.SpringUtils; -import org.aspectj.lang.ProceedingJoinPoint; -import org.aspectj.lang.annotation.Around; -import org.aspectj.lang.annotation.Aspect; -import org.aspectj.lang.reflect.MethodSignature; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.core.annotation.Order; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import java.util.ArrayList; -import java.util.Date; -import java.util.List; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.ThreadLocalRandom; - -/** - * 保存日志 - * - * @author owen - * @create 2017年7月2日 - */ -@Aspect -@Order(-1) // 保证该AOP在@Transactional之前执行 -public class LogAnnotationAspect { - - private static final Logger logger = LoggerFactory.getLogger(LogAnnotationAspect.class); - - @Around("@annotation(ds)") - public Object logSave(ProceedingJoinPoint joinPoint, LogAnnotation ds) throws Throwable { - - // 请求流水号 - String transid = getRandom(); - // 记录开始时间 - long start = System.currentTimeMillis(); - // 获取方法参数 - String url = null; - String httpMethod = null; - Object result = null; - List httpReqArgs = new ArrayList(); - SysLog log = new SysLog(); - log.setCreateTime(new Date()); - LoginAppUser loginAppUser = SysUserUtil.getLoginAppUser(); - if (loginAppUser != null) { - log.setUsername(loginAppUser.getUsername()); - } - - MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature(); - - LogAnnotation logAnnotation = methodSignature.getMethod().getDeclaredAnnotation(LogAnnotation.class); - log.setModule(logAnnotation.module() + ":" + methodSignature.getDeclaringTypeName() + "/" - + methodSignature.getName()); - - Object[] args = joinPoint.getArgs();// 参数值 - url = methodSignature.getDeclaringTypeName() + "/"+ methodSignature.getName(); - for (Object object : args) { - if (object instanceof HttpServletRequest) { - HttpServletRequest request = (HttpServletRequest) object; - url = request.getRequestURI(); - httpMethod = request.getMethod(); - } else if (object instanceof HttpServletResponse) { - } else { - - httpReqArgs.add(object); - } - } - - try { - String params = JSONObject.toJSONString(httpReqArgs); - log.setParams(params); - // 打印请求参数参数 - logger.info("开始请求,transid={}, url={} , httpMethod={}, reqData={} ", transid, url, httpMethod, params); - } catch (Exception e) { - logger.error("记录参数失败:{}", e.getMessage()); - } - - try { - // 调用原来的方法 - result = joinPoint.proceed(); - log.setFlag(Boolean.TRUE); - } catch (Exception e) { - log.setFlag(Boolean.FALSE); - log.setRemark(e.getMessage()); - - throw e; - } finally { - - CompletableFuture.runAsync(() -> { - try { - if (logAnnotation.recordRequestParam()) { - LogService logService = SpringUtils.getBean(LogServiceImpl.class); - logService.save(log); - } - } catch (Exception e) { - logger.error("记录参数失败:{}", e.getMessage()); - } - - }); - // 获取回执报文及耗时 - logger.info("请求完成, transid={}, 耗时={}, resp={}:", transid, (System.currentTimeMillis() - start), - result == null ? null : JSON.toJSONString(result)); - - } - return result; - } - - /** - * 生成日志随机数 - * - * @return - */ - public String getRandom() { - int i = 0; - StringBuilder st = new StringBuilder(); - while (i < 5) { - i++; - st.append(ThreadLocalRandom.current().nextInt(10)); - } - return st.toString() + System.currentTimeMillis(); - } - -} \ No newline at end of file diff --git a/cloud/autho/src/main/java/com/sincere/autho/config/OAuth2ServerConfig.java b/cloud/autho/src/main/java/com/sincere/autho/config/OAuth2ServerConfig.java deleted file mode 100644 index a13ca6f..0000000 --- a/cloud/autho/src/main/java/com/sincere/autho/config/OAuth2ServerConfig.java +++ /dev/null @@ -1,260 +0,0 @@ - -package com.sincere.autho.config; - -import com.sincere.autho.service.RedisAuthorizationCodeServices; -import com.sincere.autho.service.RedisClientDetailsService; -import com.sincere.autho.token.RedisTemplateTokenStore; -import com.sincere.common.props.PermitUrlProperties; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.autoconfigure.AutoConfigureAfter; -import org.springframework.boot.context.properties.EnableConfigurationProperties; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.data.redis.core.RedisTemplate; -import org.springframework.security.authentication.AuthenticationManager; -import org.springframework.security.config.annotation.web.builders.HttpSecurity; -import org.springframework.security.config.annotation.web.builders.WebSecurity; -import org.springframework.security.core.userdetails.UserDetailsService; -import org.springframework.security.oauth2.common.OAuth2AccessToken; -import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer; -import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter; -import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer; -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.AuthorizationServerEndpointsConfigurer; -import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer; -import org.springframework.security.oauth2.provider.code.RandomValueAuthorizationCodeServices; -import org.springframework.security.oauth2.provider.error.WebResponseExceptionTranslator; -import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter; -import org.springframework.security.oauth2.provider.token.store.JwtTokenStore; -import org.springframework.security.web.util.matcher.RequestMatcher; -import org.springframework.stereotype.Component; -import org.springframework.util.AntPathMatcher; - -import javax.annotation.Resource; -import javax.servlet.http.HttpServletRequest; -import javax.sql.DataSource; - -/** - * @author owen 624191343@qq.com - * @version 创建时间:2017年11月12日 上午22:57:51 - */ -@Configuration -public class OAuth2ServerConfig { - - @Resource - private DataSource dataSource; - @Resource - private RedisTemplate redisTemplate; - - /** - * 声明 ClientDetails实现 - */ - @Bean - public RedisClientDetailsService redisClientDetailsService() { - RedisClientDetailsService clientDetailsService = new RedisClientDetailsService(dataSource); - clientDetailsService.setRedisTemplate(redisTemplate); - return clientDetailsService; - } - - - @Bean - public RandomValueAuthorizationCodeServices authorizationCodeServices() { - RedisAuthorizationCodeServices redisAuthorizationCodeServices = new RedisAuthorizationCodeServices(); - redisAuthorizationCodeServices.setRedisTemplate(redisTemplate); - return redisAuthorizationCodeServices; - } - - /** - * @author owen 624191343@qq.com - * @version 创建时间:2017年11月12日 上午22:57:51 默认token存储在内存中 - * DefaultTokenServices默认处理 - */ - @Component - @Configuration - @EnableAuthorizationServer - @AutoConfigureAfter(AuthorizationServerEndpointsConfigurer.class) - public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter { - /** - * 注入authenticationManager 来支持 password grant type - */ - @Autowired - private AuthenticationManager authenticationManager; - - @Autowired - private UserDetailsService userDetailsService; - - @Autowired(required = false) - private RedisTemplateTokenStore redisTokenStore; - - @Autowired(required = false) - private JwtTokenStore jwtTokenStore; - @Autowired(required = false) - private JwtAccessTokenConverter jwtAccessTokenConverter; - - @Autowired - private WebResponseExceptionTranslator webResponseExceptionTranslator; - - @Autowired - private RedisClientDetailsService redisClientDetailsService; - - @Autowired(required = false) - private RandomValueAuthorizationCodeServices authorizationCodeServices; - - /** - * 配置身份认证器,配置认证方式,TokenStore,TokenGranter,OAuth2RequestFactory - */ - public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception { - - if (jwtTokenStore != null) { - endpoints.tokenStore(jwtTokenStore).authenticationManager(authenticationManager) - // 支持 - .userDetailsService(userDetailsService); - // password - // grant - // type; - } else if (redisTokenStore != null) { - endpoints.tokenStore(redisTokenStore).authenticationManager(authenticationManager) - // 支持 - .userDetailsService(userDetailsService); - // password - // grant - // type; - } - - if (jwtAccessTokenConverter != null) { - endpoints.accessTokenConverter(jwtAccessTokenConverter); - } - - endpoints.authorizationCodeServices(authorizationCodeServices); - - endpoints.exceptionTranslator(webResponseExceptionTranslator); - - } - - /** - * 配置应用名称 应用id - * 配置OAuth2的客户端相关信息 - */ - @Override - public void configure(ClientDetailsServiceConfigurer clients) throws Exception { - - // if(clientDetailsService!=null){ - // clients.withClientDetails(clientDetailsService); - // }else{ - // clients.inMemory().withClient("neusoft1").secret("neusoft1") - // .authorizedGrantTypes("authorization_code", "password", - // "refresh_token").scopes("all") - // .resourceIds(SERVER_RESOURCE_ID).accessTokenValiditySeconds(1200) - // .refreshTokenValiditySeconds(50000) - // .and().withClient("neusoft2").secret("neusoft2") - // .authorizedGrantTypes("authorization_code", "password", - // "refresh_token").scopes("all") - // .resourceIds(SERVER_RESOURCE_ID).accessTokenValiditySeconds(1200) - // .refreshTokenValiditySeconds(50000) - // ; - // } - clients.withClientDetails(redisClientDetailsService); - redisClientDetailsService.loadAllClientToCache(); - } - - /** - * 对应于配置AuthorizationServer安全认证的相关信息,创建ClientCredentialsTokenEndpointFilter核心过滤器 - */ - @Override - public void configure(AuthorizationServerSecurityConfigurer security) throws Exception { - // url:/oauth/token_key,exposes - security.tokenKeyAccess("permitAll()") - /// public key for token - /// verification if using - /// JWT tokens - // url:/oauth/check_token - .checkTokenAccess("isAuthenticated()") - // allow check token - .allowFormAuthenticationForClients(); - - // security.allowFormAuthenticationForClients(); - //// security.tokenKeyAccess("permitAll()"); - // security.tokenKeyAccess("isAuthenticated()"); - } - - } - - /** - * 资源服务 - */ - @Configuration - @EnableResourceServer - @EnableConfigurationProperties(PermitUrlProperties.class) - public class ResourceServerConfig extends ResourceServerConfigurerAdapter { - - @Autowired - private PermitUrlProperties permitUrlProperties; - - public void configure(WebSecurity web) throws Exception { - web.ignoring().antMatchers("/health"); - web.ignoring().antMatchers("/oauth/user/token"); - web.ignoring().antMatchers("/oauth/client/token"); - } - - @Override - public void configure(HttpSecurity http) throws Exception { - http.requestMatcher( - /** - * 判断来源请求是否包含oauth2授权信息 - */ - new RequestMatcher() { - private AntPathMatcher antPathMatcher = new AntPathMatcher(); - - @Override - public boolean matches(HttpServletRequest request) { - // 请求参数中包含access_token参数 - if (request.getParameter(OAuth2AccessToken.ACCESS_TOKEN) != null) { - return true; - } - - // 头部的Authorization值以Bearer开头 - String auth = request.getHeader("Authorization"); - if (auth != null) { - if (auth.startsWith(OAuth2AccessToken.BEARER_TYPE)) { - return true; - } - } - if (antPathMatcher.match(request.getRequestURI(), "/oauth/userinfo")) { - return true; - } - if (antPathMatcher.match(request.getRequestURI(), "/oauth/remove/token")) { - return true; - } - if (antPathMatcher.match(request.getRequestURI(), "/oauth/get/token")) { - return true; - } - if (antPathMatcher.match(request.getRequestURI(), "/oauth/refresh/token")) { - return true; - } - - if (antPathMatcher.match(request.getRequestURI(), "/oauth/token/list")) { - return true; - } - - if (antPathMatcher.match("/clients/**", request.getRequestURI())) { - return true; - } - - if (antPathMatcher.match("/services/**", request.getRequestURI())) { - return true; - } - if (antPathMatcher.match("/redis/**", request.getRequestURI())) { - return true; - } - return false; - } - } - - ).authorizeRequests().antMatchers(permitUrlProperties.getIgnored()).permitAll().anyRequest() - .authenticated(); - } - - } - -} diff --git a/cloud/autho/src/main/java/com/sincere/autho/config/SecurityConfig.java b/cloud/autho/src/main/java/com/sincere/autho/config/SecurityConfig.java deleted file mode 100644 index aaf5a22..0000000 --- a/cloud/autho/src/main/java/com/sincere/autho/config/SecurityConfig.java +++ /dev/null @@ -1,129 +0,0 @@ -package com.sincere.autho.config; - -import com.sincere.autho.handler.OauthLogoutHandler; -import com.sincere.common.props.PermitUrlProperties; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.context.properties.EnableConfigurationProperties; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.security.authentication.AuthenticationManager; -import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; -import org.springframework.security.config.annotation.web.builders.HttpSecurity; -import org.springframework.security.config.annotation.web.builders.WebSecurity; -import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; -import org.springframework.security.config.http.SessionCreationPolicy; -import org.springframework.security.core.userdetails.UserDetailsService; -import org.springframework.security.crypto.password.PasswordEncoder; -import org.springframework.security.web.AuthenticationEntryPoint; -import org.springframework.security.web.authentication.AuthenticationFailureHandler; -import org.springframework.security.web.authentication.AuthenticationSuccessHandler; -import org.springframework.security.web.authentication.logout.HttpStatusReturningLogoutSuccessHandler; - -/** - * spring security配置 - * 在WebSecurityConfigurerAdapter不拦截oauth要开放的资源 - */ -@Configuration -//@EnableWebSecurity -//@EnableGlobalMethodSecurity(prePostEnabled = true) -@EnableConfigurationProperties(PermitUrlProperties.class) -public class SecurityConfig extends WebSecurityConfigurerAdapter { - - @Autowired - private AuthenticationSuccessHandler authenticationSuccessHandler; - @Autowired - private AuthenticationFailureHandler authenticationFailureHandler; - // @Autowired - // private LogoutSuccessHandler logoutSuccessHandler; - @Autowired(required = false) - private AuthenticationEntryPoint authenticationEntryPoint; - @Autowired - private UserDetailsService userDetailsService; - - @Autowired - private PasswordEncoder passwordEncoder; - - @Autowired - private OauthLogoutHandler oauthLogoutHandler; - @Autowired - private PermitUrlProperties permitUrlProperties ; - - @Autowired - private ValidateCodeSecurityConfig validateCodeSecurityConfig ; - - @Override - public void configure(WebSecurity web) throws Exception { - web.ignoring().antMatchers("/v2/api-docs", "/configuration/ui", "/swagger-resources", "/configuration/security", - "/swagger-ui.html", "/webjars/**", "/doc.html", "/login.html"); - web.ignoring().antMatchers("/js/**"); - web.ignoring().antMatchers("/css/**"); - web.ignoring().antMatchers("/health"); - // 忽略登录界面 - web.ignoring().antMatchers("/login.html"); - web.ignoring().antMatchers("/index.html"); - web.ignoring().antMatchers("/oauth/user/token"); - web.ignoring().antMatchers("/oauth/client/token"); - web.ignoring().antMatchers("/validata/code/**"); - web.ignoring().antMatchers(permitUrlProperties.getIgnored()); - - } - /** - * 认证管理 - * - * @return 认证管理对象 - * @throws Exception - * 认证异常信息 - */ - @Override - @Bean - public AuthenticationManager authenticationManagerBean() throws Exception { - return super.authenticationManagerBean(); - } - - @Override - protected void configure(HttpSecurity http) throws Exception { - http.csrf().disable(); - - http.authorizeRequests() - .anyRequest().authenticated(); - http.formLogin().loginPage("/login.html").loginProcessingUrl("/user/login") - .successHandler(authenticationSuccessHandler).failureHandler(authenticationFailureHandler); - - // 基于密码 等模式可以无session,不支持授权码模式 - if (authenticationEntryPoint != null) { - http.exceptionHandling().authenticationEntryPoint(authenticationEntryPoint); - http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS); - - } else { - // 授权码模式单独处理,需要session的支持,此模式可以支持所有oauth2的认证 - http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED); - } - - http.logout().logoutSuccessUrl("/login.html") - .logoutSuccessHandler(new HttpStatusReturningLogoutSuccessHandler()) - .addLogoutHandler(oauthLogoutHandler).clearAuthentication(true); - - //增加验证码处理 - http.apply(validateCodeSecurityConfig) ; - // http.logout().logoutUrl("/logout").logoutSuccessHandler(logoutSuccessHandler); - // 解决不允许显示在iframe的问题 - http.headers().frameOptions().disable(); - http.headers().cacheControl(); - - } - - /** - * 全局用户信息 - * - * @param auth - * 认证管理 - * @throws Exception - * 用户认证异常信息 - */ - @Autowired - public void globalUserDetails(AuthenticationManagerBuilder auth) throws Exception { - auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder); - } - - -} diff --git a/cloud/autho/src/main/java/com/sincere/autho/config/ValidateCodeSecurityConfig.java b/cloud/autho/src/main/java/com/sincere/autho/config/ValidateCodeSecurityConfig.java deleted file mode 100644 index 7fc7cd6..0000000 --- a/cloud/autho/src/main/java/com/sincere/autho/config/ValidateCodeSecurityConfig.java +++ /dev/null @@ -1,29 +0,0 @@ -/** - * - */ -package com.sincere.autho.config; - -import org.springframework.security.config.annotation.SecurityConfigurerAdapter; -import org.springframework.security.config.annotation.web.builders.HttpSecurity; -import org.springframework.security.web.DefaultSecurityFilterChain; -import org.springframework.security.web.authentication.preauth.AbstractPreAuthenticatedProcessingFilter; -import org.springframework.stereotype.Component; - -import javax.annotation.Resource; -import javax.servlet.Filter; - -/** - * 校验码相关安全配置 - * - * @author zlt - */ -@Component("validateCodeSecurityConfig") -public class ValidateCodeSecurityConfig extends SecurityConfigurerAdapter { - @Resource - private Filter validateCodeFilter; - - @Override - public void configure(HttpSecurity http) { - http.addFilterBefore(validateCodeFilter, AbstractPreAuthenticatedProcessingFilter.class); - } -} diff --git a/cloud/autho/src/main/java/com/sincere/autho/control/LoginController.java b/cloud/autho/src/main/java/com/sincere/autho/control/LoginController.java new file mode 100644 index 0000000..c2a6174 --- /dev/null +++ b/cloud/autho/src/main/java/com/sincere/autho/control/LoginController.java @@ -0,0 +1,35 @@ +package com.sincere.autho.control; + +import com.sincere.autho.dto.BaseDto; +import com.sincere.autho.dto.req.LoginReqDto; +import com.sincere.autho.service.LoginService; +import com.sincere.common.util.TokenUtils; +import io.swagger.annotations.Api; +import org.apache.commons.lang3.StringUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class LoginController { + + @Autowired + LoginService loginService ; + + + @RequestMapping(value = "/login" , method = RequestMethod.POST) + public BaseDto login(@RequestBody LoginReqDto loginReqDto){ + BaseDto result = new BaseDto<>() ; + String userId = loginService.login(loginReqDto); + if(StringUtils.isNotBlank(userId)){ + result.setMessage("登录成功"); + result.setData(TokenUtils.buildToken(userId)); + }else { + result.setStatus(false); + result.setMessage("账号密码错误"); + } + return result ; + } +} diff --git a/cloud/autho/src/main/java/com/sincere/autho/control/OAuth2Controller.java b/cloud/autho/src/main/java/com/sincere/autho/control/OAuth2Controller.java deleted file mode 100644 index 2bcb2de..0000000 --- a/cloud/autho/src/main/java/com/sincere/autho/control/OAuth2Controller.java +++ /dev/null @@ -1,482 +0,0 @@ -package com.sincere.autho.control; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.sincere.autho.annotation.log.LogAnnotation; -import com.sincere.autho.service.RedisClientDetailsService; -import com.sincere.autho.utils.SpringUtil; -import com.sincere.common.commons.PageResult; -import com.sincere.common.model.system.LoginAppUser; -import com.sincere.common.model.system.SysPermission; -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; -import io.swagger.annotations.ApiParam; -import org.apache.commons.collections.MapUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.dao.DataAccessException; -import org.springframework.data.redis.connection.RedisConnection; -import org.springframework.data.redis.core.Cursor; -import org.springframework.data.redis.core.RedisCallback; -import org.springframework.data.redis.core.RedisTemplate; -import org.springframework.data.redis.core.ScanOptions; -import org.springframework.http.HttpStatus; -import org.springframework.security.authentication.AuthenticationManager; -import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; -import org.springframework.security.core.Authentication; -import org.springframework.security.core.context.SecurityContextHolder; -import org.springframework.security.crypto.password.PasswordEncoder; -import org.springframework.security.oauth2.common.OAuth2AccessToken; -import org.springframework.security.oauth2.common.exceptions.UnapprovedClientAuthenticationException; -import org.springframework.security.oauth2.provider.*; -import org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationDetails; -import org.springframework.security.oauth2.provider.client.ClientCredentialsTokenGranter; -import org.springframework.security.oauth2.provider.refresh.RefreshTokenGranter; -import org.springframework.security.oauth2.provider.request.DefaultOAuth2RequestFactory; -import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices; -import org.springframework.security.oauth2.provider.token.TokenStore; -import org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.bind.annotation.RestController; - -import javax.annotation.Resource; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import java.io.IOException; -import java.util.*; - -/** - * @author 作者 owen E-mail: 624191343@qq.com - * @version 创建时间:2018年4月28日 下午2:18:54 类说明 - */ - -@Api(tags = "OAuth2相关操作") -@RestController -public class OAuth2Controller { - - private static final Logger logger = LoggerFactory.getLogger(OAuth2Controller.class); - @Resource - private ObjectMapper objectMapper; // springmvc启动时自动装配json处理类 - @Autowired - private PasswordEncoder passwordEncoder; - - @Autowired - private TokenStore tokenStore; - - @Autowired - private RedisTemplate redisTemplate; - - @ApiOperation(value = "用户名密码获取token") - @PostMapping("/oauth/user/token") - public void getUserTokenInfo( - @ApiParam(required = true, name = "username", value = "账号") @RequestParam(value = "username") String username, - @ApiParam(required = true, name = "password", value = "密码") @RequestParam(value = "password") String password, - HttpServletRequest request, HttpServletResponse response) { - String clientId = request.getHeader("client_id"); - String clientSecret = request.getHeader("client_secret"); - - try { - - if (clientId == null || "".equals(clientId)) { - throw new UnapprovedClientAuthenticationException("请求头中无client_id信息"); - } - - if (clientSecret == null || "".equals(clientSecret)) { - throw new UnapprovedClientAuthenticationException("请求头中无client_secret信息"); - } - - RedisClientDetailsService clientDetailsService = SpringUtil.getBean(RedisClientDetailsService.class); - - ClientDetails clientDetails = clientDetailsService.loadClientByClientId(clientId); - - if (clientDetails == null) { - throw new UnapprovedClientAuthenticationException("clientId对应的信息不存在"); - } else if (!passwordEncoder.matches(clientSecret, clientDetails.getClientSecret())) { - throw new UnapprovedClientAuthenticationException("clientSecret不匹配"); - } - - TokenRequest tokenRequest = new TokenRequest(MapUtils.EMPTY_MAP, clientId, clientDetails.getScope(), - "customer"); - - OAuth2Request oAuth2Request = tokenRequest.createOAuth2Request(clientDetails); - - UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(username, password); - - AuthenticationManager authenticationManager = SpringUtil.getBean(AuthenticationManager.class); - - Authentication authentication = authenticationManager.authenticate(token); - SecurityContextHolder.getContext().setAuthentication(authentication); - - OAuth2Authentication oAuth2Authentication = new OAuth2Authentication(oAuth2Request, authentication); - - AuthorizationServerTokenServices authorizationServerTokenServices = SpringUtil - .getBean("defaultAuthorizationServerTokenServices", AuthorizationServerTokenServices.class); - - OAuth2AccessToken oAuth2AccessToken = authorizationServerTokenServices - .createAccessToken(oAuth2Authentication); - - oAuth2Authentication.setAuthenticated(true); - - response.setContentType("application/json;charset=UTF-8"); - response.getWriter().write(objectMapper.writeValueAsString(oAuth2AccessToken)); - response.getWriter().flush(); - response.getWriter().close(); - - } catch (Exception e) { - - response.setStatus(HttpStatus.UNAUTHORIZED.value()); - - response.setContentType("application/json;charset=UTF-8"); - - Map rsp = new HashMap<>(); - rsp.put("resp_code", HttpStatus.UNAUTHORIZED.value() + ""); - rsp.put("rsp_msg", e.getMessage()); - - try { - response.getWriter().write(objectMapper.writeValueAsString(rsp)); - response.getWriter().flush(); - response.getWriter().close(); - } catch (JsonProcessingException e1) { - // TODO Auto-generated catch block - e1.printStackTrace(); - } catch (IOException e1) { - // TODO Auto-generated catch block - e1.printStackTrace(); - } - - } - } - - - @ApiOperation(value = "clientId获取token") - @PostMapping("/oauth/client/token") - @LogAnnotation(module = "autho", recordRequestParam = false) - public void getClientTokenInfo(HttpServletRequest request, HttpServletResponse response) { - - String clientId = request.getHeader("client_id"); - String clientSecret = request.getHeader("client_secret"); - try { - - if (clientId == null || "".equals(clientId)) { - throw new UnapprovedClientAuthenticationException("请求参数中无clientId信息"); - } - - if (clientSecret == null || "".equals(clientSecret)) { - throw new UnapprovedClientAuthenticationException("请求参数中无clientSecret信息"); - } - - RedisClientDetailsService clientDetailsService = SpringUtil.getBean(RedisClientDetailsService.class); - - ClientDetails clientDetails = clientDetailsService.loadClientByClientId(clientId); - - if (clientDetails == null) { - throw new UnapprovedClientAuthenticationException("clientId对应的信息不存在"); - } else if (!passwordEncoder.matches(clientSecret, clientDetails.getClientSecret())) { - throw new UnapprovedClientAuthenticationException("clientSecret不匹配"); - } - - Map map = new HashMap<>(); - map.put("client_secret", clientSecret); - map.put("client_id", clientId); - map.put("grant_type", "client_credentials"); - TokenRequest tokenRequest = new TokenRequest(map, clientId, clientDetails.getScope(), "client_credentials"); - - OAuth2Request oAuth2Request = tokenRequest.createOAuth2Request(clientDetails); - - AuthorizationServerTokenServices authorizationServerTokenServices = SpringUtil - .getBean("defaultAuthorizationServerTokenServices", AuthorizationServerTokenServices.class); - OAuth2RequestFactory requestFactory = new DefaultOAuth2RequestFactory(clientDetailsService); - ClientCredentialsTokenGranter clientCredentialsTokenGranter = new ClientCredentialsTokenGranter( - authorizationServerTokenServices, clientDetailsService, requestFactory); - - clientCredentialsTokenGranter.setAllowRefresh(true); - OAuth2AccessToken oAuth2AccessToken = clientCredentialsTokenGranter.grant("client_credentials", - tokenRequest); - - response.setContentType("application/json;charset=UTF-8"); - response.getWriter().write(objectMapper.writeValueAsString(oAuth2AccessToken)); - response.getWriter().flush(); - response.getWriter().close(); - - } catch (Exception e) { - - response.setStatus(HttpStatus.UNAUTHORIZED.value()); - response.setContentType("application/json;charset=UTF-8"); - Map rsp = new HashMap<>(); - rsp.put("resp_code", HttpStatus.UNAUTHORIZED.value() + ""); - rsp.put("rsp_msg", e.getMessage()); - - try { - response.getWriter().write(objectMapper.writeValueAsString(rsp)); - response.getWriter().flush(); - response.getWriter().close(); - } catch (JsonProcessingException e1) { - // TODO Auto-generated catch block - e1.printStackTrace(); - } catch (IOException e1) { - // TODO Auto-generated catch block - e1.printStackTrace(); - } - - } - } - - @ApiOperation(value = "access_token刷新token") - @PostMapping(value = "/oauth/refresh/token", params = "access_token") - public void refreshTokenInfo(String access_token, HttpServletRequest request, HttpServletResponse response) { - - // 拿到当前用户信息 - try { - Authentication user = SecurityContextHolder.getContext().getAuthentication(); - - if (user != null) { - if (user instanceof OAuth2Authentication) { - Authentication athentication = (Authentication) user; - OAuth2AuthenticationDetails details = (OAuth2AuthenticationDetails) athentication.getDetails(); - } - - } - OAuth2AccessToken accessToken = tokenStore.readAccessToken(access_token); - OAuth2Authentication auth = (OAuth2Authentication) user; - RedisClientDetailsService clientDetailsService = SpringUtil.getBean(RedisClientDetailsService.class); - - ClientDetails clientDetails = clientDetailsService - .loadClientByClientId(auth.getOAuth2Request().getClientId()); - - AuthorizationServerTokenServices authorizationServerTokenServices = SpringUtil - .getBean("defaultAuthorizationServerTokenServices", AuthorizationServerTokenServices.class); - OAuth2RequestFactory requestFactory = new DefaultOAuth2RequestFactory(clientDetailsService); - - RefreshTokenGranter refreshTokenGranter = new RefreshTokenGranter(authorizationServerTokenServices, - clientDetailsService, requestFactory); - - Map map = new HashMap<>(); - map.put("grant_type", "refresh_token"); - map.put("refresh_token", accessToken.getRefreshToken().getValue()); - TokenRequest tokenRequest = new TokenRequest(map, auth.getOAuth2Request().getClientId(), - auth.getOAuth2Request().getScope(), "refresh_token"); - - OAuth2AccessToken oAuth2AccessToken = refreshTokenGranter.grant("refresh_token", tokenRequest); - - tokenStore.removeAccessToken(accessToken); - - response.setContentType("application/json;charset=UTF-8"); - response.getWriter().write(objectMapper.writeValueAsString(oAuth2AccessToken)); - response.getWriter().flush(); - response.getWriter().close(); - } catch (Exception e) { - response.setStatus(HttpStatus.UNAUTHORIZED.value()); - response.setContentType("application/json;charset=UTF-8"); - Map rsp = new HashMap<>(); - rsp.put("resp_code", HttpStatus.UNAUTHORIZED.value() + ""); - rsp.put("rsp_msg", e.getMessage()); - - try { - response.getWriter().write(objectMapper.writeValueAsString(rsp)); - response.getWriter().flush(); - response.getWriter().close(); - } catch (JsonProcessingException e1) { - // TODO Auto-generated catch block - e1.printStackTrace(); - } catch (IOException e1) { - // TODO Auto-generated catch block - e1.printStackTrace(); - } - } - - } - - /** - * 移除access_token和refresh_token - * - * @param access_token - */ - @ApiOperation(value = "移除token") - @PostMapping(value = "/oauth/remove/token", params = "access_token") - public void removeToken(String access_token) { - - // 拿到当前用户信息 - Authentication user = SecurityContextHolder.getContext().getAuthentication(); - - if (user != null) { - if (user instanceof OAuth2Authentication) { - Authentication athentication = (Authentication) user; - OAuth2AuthenticationDetails details = (OAuth2AuthenticationDetails) athentication.getDetails(); - } - - } - OAuth2AccessToken accessToken = tokenStore.readAccessToken(access_token); - if (accessToken != null) { - // 移除access_token - tokenStore.removeAccessToken(accessToken); - - // 移除refresh_token - if (accessToken.getRefreshToken() != null) { - tokenStore.removeRefreshToken(accessToken.getRefreshToken()); - } - - } - } - - @ApiOperation(value = "获取token信息") - @PostMapping(value = "/oauth/get/token", params = "access_token") - public OAuth2AccessToken getTokenInfo(String access_token) { - - // 拿到当前用户信息 - Authentication user = SecurityContextHolder.getContext().getAuthentication(); - - if (user != null) { - if (user instanceof OAuth2Authentication) { - Authentication athentication = (Authentication) user; - OAuth2AuthenticationDetails details = (OAuth2AuthenticationDetails) athentication.getDetails(); - } - - } - OAuth2AccessToken accessToken = tokenStore.readAccessToken(access_token); - - return accessToken; - - } - - /** - * 当前登陆用户信息 - * security获取当前登录用户的方法是SecurityContextHolder.getContext().getAuthentication() - * 这里的实现类是org.springframework.security.oauth2.provider.OAuth2Authentication - * - * @return - */ - @ApiOperation(value = "当前登陆用户信息") - @RequestMapping(value = { "/oauth/userinfo" }, produces = "application/json") // 获取用户信息。/auth/user - public Map getCurrentUserDetail() { - Map userInfo = new HashMap<>(); - userInfo.put("user", SecurityContextHolder.getContext().getAuthentication().getPrincipal()); - logger.debug("认证详细信息:" + SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString()); - - List permissions = new ArrayList<>(); - - new ArrayList(SecurityContextHolder.getContext().getAuthentication().getAuthorities()).forEach(o -> { - SysPermission sysPermission = new SysPermission(); - sysPermission.setPermission(o.toString()); - permissions.add(sysPermission); - }); - // userInfo.put("authorities", - // AuthorityUtils.authorityListToSet(SecurityContextHolder.getContext().getAuthentication().getAuthorities()) - // ); - userInfo.put("permissions", permissions); - - userInfo.put("resp_code", "200"); - - logger.info("返回信息:{}", userInfo); - - return userInfo; - } - - @ApiOperation(value = "token列表") - @PostMapping("/oauth/token/list") - public PageResult> getUserTokenInfo(@RequestParam Map params) - throws Exception { - List> list = new ArrayList<>(); - - Set keys = redisTemplate.keys("access:" + "*") ; -// Object key1 = keys.toArray()[0]; -// Object token1 = redisTemplate.opsForValue().get(key1); - //根据分页参数获取对应数据 - // List pages = findKeysForPage("access:" + "*", MapUtils.getInteger(params, "page"),MapUtils.getInteger(params, "limit")); - - for (Object key: keys.toArray()) { -// String key = page; -// String accessToken = StringUtils.substringAfter(key, "access:"); -// OAuth2AccessToken token = tokenStore.readAccessToken(accessToken); - OAuth2AccessToken token = (OAuth2AccessToken)redisTemplate.opsForValue().get(key); - HashMap map = new HashMap(); - - try { - map.put("token_type", token.getTokenType()); - map.put("token_value", token.getValue()); - map.put("expires_in", token.getExpiresIn()+""); - } catch (Exception e) { - - } - - - OAuth2Authentication oAuth2Auth = tokenStore.readAuthentication(token); - Authentication authentication = oAuth2Auth.getUserAuthentication(); - - map.put("client_id", oAuth2Auth.getOAuth2Request().getClientId()); - map.put("grant_type", oAuth2Auth.getOAuth2Request().getGrantType()); - - if (authentication instanceof UsernamePasswordAuthenticationToken) { - UsernamePasswordAuthenticationToken authenticationToken = (UsernamePasswordAuthenticationToken) authentication; - - if(authenticationToken.getPrincipal() instanceof LoginAppUser ){ - LoginAppUser user = (LoginAppUser) authenticationToken.getPrincipal(); - map.put("user_id", user.getId()+""); - map.put("user_name", user.getUsername()+""); - map.put("user_head_imgurl", user.getHeadImgUrl()+""); - } - - - }else if (authentication instanceof PreAuthenticatedAuthenticationToken){ - //刷新token方式 - PreAuthenticatedAuthenticationToken authenticationToken = (PreAuthenticatedAuthenticationToken) authentication; - if(authenticationToken.getPrincipal() instanceof LoginAppUser ){ - LoginAppUser user = (LoginAppUser) authenticationToken.getPrincipal(); - map.put("user_id", user.getId()+""); - map.put("user_name", user.getUsername()+""); - map.put("user_head_imgurl", user.getHeadImgUrl()+""); - } - - } - list.add(map); - - } - - - - return PageResult.>builder().data(list).code(0).count((long) keys.size()).build(); - - } - - public List findKeysForPage(String patternKey, int pageNum, int pageSize) { - - Set execute = redisTemplate.execute(new RedisCallback>() { - - @Override - public Set doInRedis(RedisConnection connection) throws DataAccessException { - - Set binaryKeys = new HashSet<>(); - - Cursor cursor = connection - .scan(new ScanOptions.ScanOptionsBuilder().match(patternKey).count(1000).build()); - int tmpIndex = 0; - int startIndex = (pageNum - 1) * pageSize; - int end = pageNum * pageSize; - while (cursor.hasNext()) { - if (tmpIndex >= startIndex && tmpIndex < end) { - binaryKeys.add(new String(cursor.next())); - tmpIndex++; - continue; - } - - // 获取到满足条件的数据后,就可以退出了 - if (tmpIndex >= end) { - break; - } - - tmpIndex++; - cursor.next(); - } - connection.close(); - return binaryKeys; - } - }); - - List result = new ArrayList(pageSize); - result.addAll(execute); - return result; - } - -} diff --git a/cloud/autho/src/main/java/com/sincere/autho/control/UserController.java b/cloud/autho/src/main/java/com/sincere/autho/control/UserController.java deleted file mode 100644 index c9d55d7..0000000 --- a/cloud/autho/src/main/java/com/sincere/autho/control/UserController.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.sincere.autho.control; - -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.RestController; - -import java.security.Principal; - -@RestController -public class UserController { - - @GetMapping("/user") - public Principal user(Principal user){ - return user; - } - -} diff --git a/cloud/autho/src/main/java/com/sincere/autho/dto/BaseDto.java b/cloud/autho/src/main/java/com/sincere/autho/dto/BaseDto.java new file mode 100644 index 0000000..8460a46 --- /dev/null +++ b/cloud/autho/src/main/java/com/sincere/autho/dto/BaseDto.java @@ -0,0 +1,36 @@ +package com.sincere.autho.dto; + +public class BaseDto { + + private String message ; + private boolean status ; + private T data ; + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } + + public boolean isStatus() { + return status; + } + + public void setStatus(boolean status) { + this.status = status; + } + + public T getData() { + return data; + } + + public void setData(T data) { + this.data = data; + } + + public BaseDto() { + this.status = true ; + } +} diff --git a/cloud/autho/src/main/java/com/sincere/autho/dto/req/LoginReqDto.java b/cloud/autho/src/main/java/com/sincere/autho/dto/req/LoginReqDto.java new file mode 100644 index 0000000..bafe7cc --- /dev/null +++ b/cloud/autho/src/main/java/com/sincere/autho/dto/req/LoginReqDto.java @@ -0,0 +1,32 @@ +package com.sincere.autho.dto.req; + +public class LoginReqDto { + + private String account ; + private String password ; + private int userType ; // 2:学生;3:家长;其他都是老师 + + public String getAccount() { + return account; + } + + public void setAccount(String account) { + this.account = account; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + public int getUserType() { + return userType; + } + + public void setUserType(int userType) { + this.userType = userType; + } +} diff --git a/cloud/autho/src/main/java/com/sincere/autho/handler/ExceptionHandlerAdvice.java b/cloud/autho/src/main/java/com/sincere/autho/handler/ExceptionHandlerAdvice.java deleted file mode 100644 index 26279d4..0000000 --- a/cloud/autho/src/main/java/com/sincere/autho/handler/ExceptionHandlerAdvice.java +++ /dev/null @@ -1,63 +0,0 @@ -package com.sincere.autho.handler; - -import io.grpc.StatusRuntimeException; -import org.springframework.http.HttpStatus; -import org.springframework.security.access.AccessDeniedException; -import org.springframework.web.bind.annotation.ExceptionHandler; -import org.springframework.web.bind.annotation.ResponseStatus; -import org.springframework.web.bind.annotation.RestControllerAdvice; - -import java.util.HashMap; -import java.util.Map; - - -/** - * @author 作者 owen E-mail: 624191343@qq.com - * @version 创建时间:2017年11月12日 上午22:57:51 - * 异常通用处理 -*/ -@RestControllerAdvice -public class ExceptionHandlerAdvice { - - /** - * IllegalArgumentException异常处理返回json - * 状态码:400 - * @param exception - * @return - */ - @ExceptionHandler({ IllegalArgumentException.class }) - @ResponseStatus(HttpStatus.BAD_REQUEST) - public Map badRequestException(IllegalArgumentException exception) { - Map data = new HashMap<>(); - data.put("resp_code", HttpStatus.BAD_REQUEST.value()); - data.put("resp_msg", exception.getMessage()); - - return data; - } - /** - * AccessDeniedException异常处理返回json - * 状态码:403 - * @param exception - * @return - */ - @ExceptionHandler({ AccessDeniedException.class }) - @ResponseStatus(HttpStatus.FORBIDDEN) - public Map badMethodExpressException(AccessDeniedException exception) { - Map data = new HashMap<>(); - data.put("resp_code", HttpStatus.FORBIDDEN.value()); - data.put("resp_msg", exception.getMessage()); - - return data; - } - @ExceptionHandler({ StatusRuntimeException.class }) - @ResponseStatus(HttpStatus.BAD_REQUEST) - public Map badRequestException(StatusRuntimeException exception) { - Map data = new HashMap<>(); - data.put("resp_code", HttpStatus.INTERNAL_SERVER_ERROR.value()); - data.put("resp_msg", exception.getMessage()); - - return data; - } - - -} diff --git a/cloud/autho/src/main/java/com/sincere/autho/handler/OauthLogoutHandler.java b/cloud/autho/src/main/java/com/sincere/autho/handler/OauthLogoutHandler.java deleted file mode 100644 index 5403b47..0000000 --- a/cloud/autho/src/main/java/com/sincere/autho/handler/OauthLogoutHandler.java +++ /dev/null @@ -1,90 +0,0 @@ -package com.sincere.autho.handler; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.security.core.Authentication; -import org.springframework.security.oauth2.common.OAuth2AccessToken; -import org.springframework.security.oauth2.common.OAuth2RefreshToken; -import org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationDetails; -import org.springframework.security.oauth2.provider.token.TokenStore; -import org.springframework.security.web.authentication.logout.LogoutHandler; -import org.springframework.util.Assert; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import java.util.Enumeration; - -/** - * @author keets - * @date 2017/10/17 - */ -public class OauthLogoutHandler implements LogoutHandler { - - private static final Logger logger = LoggerFactory.getLogger(OauthLogoutHandler.class); - - @Autowired - private TokenStore tokenStore; - - @Override - public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) { - Assert.notNull(tokenStore, "tokenStore must be set"); - String token = extractToken(request); - if(token!=null || !"".equals(token)){ - OAuth2AccessToken existingAccessToken = tokenStore.readAccessToken(token); - OAuth2RefreshToken refreshToken; - if (existingAccessToken != null) { - if (existingAccessToken.getRefreshToken() != null) { - logger.info("remove refreshToken!", existingAccessToken.getRefreshToken()); - refreshToken = existingAccessToken.getRefreshToken(); - tokenStore.removeRefreshToken(refreshToken); - } - logger.info("remove existingAccessToken!", existingAccessToken); - tokenStore.removeAccessToken(existingAccessToken); - } - return; - } - - } - - protected String extractToken(HttpServletRequest request) { - // first check the header... - String token = extractHeaderToken(request); - - // bearer type allows a request parameter as well - if (token == null) { - logger.debug("Token not found in headers. Trying request parameters."); - token = request.getParameter(OAuth2AccessToken.ACCESS_TOKEN); - if (token == null) { - logger.debug("Token not found in request parameters. Not an OAuth2 request."); - } else { - request.setAttribute(OAuth2AuthenticationDetails.ACCESS_TOKEN_TYPE, OAuth2AccessToken.BEARER_TYPE); - } - } - - return token; - } - - protected String extractHeaderToken(HttpServletRequest request) { - Enumeration headers = request.getHeaders("Authorization"); - while (headers.hasMoreElements()) { // typically there is only one (most - // servers enforce that) - String value = headers.nextElement(); - if ((value.toLowerCase().startsWith(OAuth2AccessToken.BEARER_TYPE.toLowerCase()))) { - String authHeaderValue = value.substring(OAuth2AccessToken.BEARER_TYPE.length()).trim(); - // Add this here for the auth details later. Would be better to - // change the signature of this method. - request.setAttribute(OAuth2AuthenticationDetails.ACCESS_TOKEN_TYPE, - value.substring(0, OAuth2AccessToken.BEARER_TYPE.length()).trim()); - int commaIndex = authHeaderValue.indexOf(','); - if (commaIndex > 0) { - authHeaderValue = authHeaderValue.substring(0, commaIndex); - } - return authHeaderValue; - } - } - - return null; - } - -} diff --git a/cloud/autho/src/main/java/com/sincere/autho/log/dao/LogDao.java b/cloud/autho/src/main/java/com/sincere/autho/log/dao/LogDao.java deleted file mode 100644 index aaed6af..0000000 --- a/cloud/autho/src/main/java/com/sincere/autho/log/dao/LogDao.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.sincere.autho.log.dao; - -import com.sincere.common.model.log.SysLog; -import org.apache.ibatis.annotations.Insert; -import org.apache.ibatis.annotations.Mapper; - -@Mapper -public interface LogDao { - - @Insert("insert into sys_log(username, module, params, remark, flag, createTime) values(#{username}, #{module}, #{params}, #{remark}, #{flag}, #{createTime})") - int save(SysLog log); - -} diff --git a/cloud/autho/src/main/java/com/sincere/autho/log/service/LogService.java b/cloud/autho/src/main/java/com/sincere/autho/log/service/LogService.java deleted file mode 100644 index 7dc2673..0000000 --- a/cloud/autho/src/main/java/com/sincere/autho/log/service/LogService.java +++ /dev/null @@ -1,11 +0,0 @@ -package com.sincere.autho.log.service; - - -import com.sincere.common.model.log.SysLog; - -public interface LogService { - - void save(SysLog log); - - -} diff --git a/cloud/autho/src/main/java/com/sincere/autho/log/service/impl/LogServiceImpl.java b/cloud/autho/src/main/java/com/sincere/autho/log/service/impl/LogServiceImpl.java deleted file mode 100644 index 2a48e22..0000000 --- a/cloud/autho/src/main/java/com/sincere/autho/log/service/impl/LogServiceImpl.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.sincere.autho.log.service.impl; - -import com.sincere.autho.annotation.datasource.DataSource; -import com.sincere.autho.log.dao.LogDao; -import com.sincere.autho.log.service.LogService; -import com.sincere.common.model.log.SysLog; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.scheduling.annotation.Async; -import org.springframework.stereotype.Service; - -import java.util.Date; - -@Service -public class LogServiceImpl implements LogService { - - @Autowired - private LogDao logDao; - - @Async - @Override - @DataSource(name="log") - public void save(SysLog log) { - if (log.getCreateTime() == null) { - log.setCreateTime(new Date()); - } - if (log.getFlag() == null) { - log.setFlag(Boolean.TRUE); - } - - logDao.save(log); - } - - -} diff --git a/cloud/autho/src/main/java/com/sincere/autho/mapper/UserMapper.java b/cloud/autho/src/main/java/com/sincere/autho/mapper/UserMapper.java new file mode 100644 index 0000000..73a09a7 --- /dev/null +++ b/cloud/autho/src/main/java/com/sincere/autho/mapper/UserMapper.java @@ -0,0 +1,10 @@ +package com.sincere.autho.mapper; + +import com.sincere.autho.dto.req.LoginReqDto; + +public interface UserMapper { + + String loginTeacher(LoginReqDto loginReqDto) ; + + String loginStudent(LoginReqDto loginReqDto) ; +} diff --git a/cloud/autho/src/main/java/com/sincere/autho/service/LoginService.java b/cloud/autho/src/main/java/com/sincere/autho/service/LoginService.java new file mode 100644 index 0000000..5f695be --- /dev/null +++ b/cloud/autho/src/main/java/com/sincere/autho/service/LoginService.java @@ -0,0 +1,8 @@ +package com.sincere.autho.service; + +import com.sincere.autho.dto.req.LoginReqDto; + +public interface LoginService { + + String login(LoginReqDto loginReqDto); +} diff --git a/cloud/autho/src/main/java/com/sincere/autho/service/RedisAuthorizationCodeServices.java b/cloud/autho/src/main/java/com/sincere/autho/service/RedisAuthorizationCodeServices.java deleted file mode 100644 index a278926..0000000 --- a/cloud/autho/src/main/java/com/sincere/autho/service/RedisAuthorizationCodeServices.java +++ /dev/null @@ -1,58 +0,0 @@ -package com.sincere.autho.service; - -import org.springframework.data.redis.core.RedisTemplate; -import org.springframework.security.oauth2.provider.OAuth2Authentication; -import org.springframework.security.oauth2.provider.code.RandomValueAuthorizationCodeServices; - -import java.util.concurrent.TimeUnit; - -/** - * JdbcAuthorizationCodeServices替换 - */ -public class RedisAuthorizationCodeServices extends RandomValueAuthorizationCodeServices { - - private RedisTemplate redisTemplate ; - - - public RedisTemplate getRedisTemplate() { - return redisTemplate; - } - - public void setRedisTemplate(RedisTemplate redisTemplate) { - this.redisTemplate = redisTemplate; - } - - /** - * 替换JdbcAuthorizationCodeServices的存储策略 - * 将存储code到redis,并设置过期时间,10分钟
- */ - @Override - protected void store(String code, OAuth2Authentication authentication) { - - redisTemplate.opsForValue().set(redisKey(code), authentication, 10, TimeUnit.MINUTES); - - - } - - @Override - protected OAuth2Authentication remove(final String code) { - - String codeKey =redisKey(code) ; - - OAuth2Authentication token = (OAuth2Authentication) redisTemplate.opsForValue().get(codeKey) ; - - this.redisTemplate.delete(codeKey); - - return token; - } - - /** - * redis中 code key的前缀 - * - * @param code - * @return - */ - private String redisKey(String code) { - return "oauth:code:" + code; - } -} diff --git a/cloud/autho/src/main/java/com/sincere/autho/service/RedisClientDetailsService.java b/cloud/autho/src/main/java/com/sincere/autho/service/RedisClientDetailsService.java deleted file mode 100644 index 1455f68..0000000 --- a/cloud/autho/src/main/java/com/sincere/autho/service/RedisClientDetailsService.java +++ /dev/null @@ -1,153 +0,0 @@ -package com.sincere.autho.service; - -import com.alibaba.fastjson.JSONObject; -import org.apache.commons.lang.StringUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.data.redis.core.RedisTemplate; -import org.springframework.security.oauth2.common.exceptions.InvalidClientException; -import org.springframework.security.oauth2.provider.ClientDetails; -import org.springframework.security.oauth2.provider.NoSuchClientException; -import org.springframework.security.oauth2.provider.client.BaseClientDetails; -import org.springframework.security.oauth2.provider.client.JdbcClientDetailsService; -import org.springframework.util.CollectionUtils; - -import javax.sql.DataSource; -import java.util.List; - - -/** - * @author owen 624191343@qq.com - * @version 创建时间:2017年11月12日 上午22:57:51 - * 类说明 - * 将oauth_client_details表数据缓存到redis,这里做个缓存优化 - * layui模块中有对oauth_client_details的crud, 注意同步redis的数据 - * 注意对oauth_client_details清楚redis db部分数据的清空 - */ - -public class RedisClientDetailsService extends JdbcClientDetailsService { - - - // 扩展 默认的 ClientDetailsService, 增加逻辑删除判断( status = 1) - private static final String SELECT_CLIENT_DETAILS_SQL = "select client_id, client_secret, resource_ids, scope, authorized_grant_types, " + - "web_server_redirect_uri, authorities, access_token_validity, refresh_token_validity, additional_information, autoapprove " + - "from oauth_client_details where client_id = ? and `status` = 1 "; - - - private static final String SELECT_FIND_STATEMENT = "select client_id, client_secret,resource_ids, scope, " - + "authorized_grant_types, web_server_redirect_uri, authorities, access_token_validity, " - + "refresh_token_validity, additional_information, autoapprove from oauth_client_details where `status` = 1 order by client_id " ; - - /** - * 缓存client的redis key,这里是hash结构存储 - */ - private static final String CACHE_CLIENT_KEY = "oauth_client_details"; - - private Logger logger = LoggerFactory.getLogger(RedisClientDetailsService.class) ; - - private RedisTemplate redisTemplate ; - - public RedisTemplate getRedisTemplate() { - return redisTemplate; - } - - public void setRedisTemplate(RedisTemplate redisTemplate) { - this.redisTemplate = redisTemplate; - } - - public RedisClientDetailsService(DataSource dataSource) { - super(dataSource); - setSelectClientDetailsSql(SELECT_CLIENT_DETAILS_SQL) ; - setFindClientDetailsSql(SELECT_FIND_STATEMENT) ; - } - - - - @Override - public ClientDetails loadClientByClientId(String clientId) throws InvalidClientException { - ClientDetails clientDetails = null; - - // 先从redis获取 - String value = (String) redisTemplate.boundHashOps(CACHE_CLIENT_KEY).get(clientId); - if (StringUtils.isBlank(value)) { - clientDetails = cacheAndGetClient(clientId); - } else { - clientDetails = JSONObject.parseObject(value, BaseClientDetails.class); - } - - return clientDetails; - } - - /** - * 缓存client并返回client - * - * @param clientId - * @return - */ - private ClientDetails cacheAndGetClient(String clientId) { - // 从数据库读取 - ClientDetails clientDetails = null ; - try { - clientDetails = super.loadClientByClientId(clientId); - if (clientDetails != null) { - // 写入redis缓存 - redisTemplate.boundHashOps(CACHE_CLIENT_KEY).put(clientId, JSONObject.toJSONString(clientDetails)); - logger.info("缓存clientId:{},{}", clientId, clientDetails); - } - }catch (NoSuchClientException e){ - logger.info("clientId:{},{}", clientId, clientId ); - }catch (InvalidClientException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - return clientDetails; - } - - @Override - public void updateClientDetails(ClientDetails clientDetails) throws NoSuchClientException { - super.updateClientDetails(clientDetails); - cacheAndGetClient(clientDetails.getClientId()); - } - - @Override - public void updateClientSecret(String clientId, String secret) throws NoSuchClientException { - super.updateClientSecret(clientId, secret); - cacheAndGetClient(clientId); - } - - @Override - public void removeClientDetails(String clientId) throws NoSuchClientException { - super.removeClientDetails(clientId); - removeRedisCache(clientId); - } - - /** - * 删除redis缓存 - * - * @param clientId - */ - private void removeRedisCache(String clientId) { - redisTemplate.boundHashOps(CACHE_CLIENT_KEY).delete(clientId); - } - - /** - * 将oauth_client_details全表刷入redis - */ - public void loadAllClientToCache() { - if (redisTemplate.hasKey(CACHE_CLIENT_KEY)) { - return; - } - logger.info("将oauth_client_details全表刷入redis"); - - List list = super.listClientDetails(); - if (CollectionUtils.isEmpty(list)) { - logger.error("oauth_client_details表数据为空,请检查"); - return; - } - - list.parallelStream().forEach(client -> { - redisTemplate.boundHashOps(CACHE_CLIENT_KEY).put(client.getClientId(), JSONObject.toJSONString(client)); - }); - } -} diff --git a/cloud/autho/src/main/java/com/sincere/autho/service/impl/LoginServiceImpl.java b/cloud/autho/src/main/java/com/sincere/autho/service/impl/LoginServiceImpl.java new file mode 100644 index 0000000..b335637 --- /dev/null +++ b/cloud/autho/src/main/java/com/sincere/autho/service/impl/LoginServiceImpl.java @@ -0,0 +1,25 @@ +package com.sincere.autho.service.impl; + +import com.sincere.autho.dto.req.LoginReqDto; +import com.sincere.autho.mapper.UserMapper; +import com.sincere.autho.service.LoginService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +@Service +public class LoginServiceImpl implements LoginService { + + @Autowired + UserMapper userMapper ; + + @Override + public String login(LoginReqDto loginReqDto) { + String userId = "" ; + if(loginReqDto.getUserType() == 2){ + userId = userMapper.loginStudent(loginReqDto); + }else { + userId = userMapper.loginTeacher(loginReqDto); + } + return userId; + } +} diff --git a/cloud/autho/src/main/java/com/sincere/autho/token/RedisTemplateTokenStore.java b/cloud/autho/src/main/java/com/sincere/autho/token/RedisTemplateTokenStore.java deleted file mode 100644 index fb6d255..0000000 --- a/cloud/autho/src/main/java/com/sincere/autho/token/RedisTemplateTokenStore.java +++ /dev/null @@ -1,331 +0,0 @@ -package com.sincere.autho.token; - -import com.sincere.common.model.system.LoginAppUser; -import org.springframework.data.redis.core.RedisTemplate; -import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; -import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken; -import org.springframework.security.oauth2.common.ExpiringOAuth2RefreshToken; -import org.springframework.security.oauth2.common.OAuth2AccessToken; -import org.springframework.security.oauth2.common.OAuth2RefreshToken; -import org.springframework.security.oauth2.provider.OAuth2Authentication; -import org.springframework.security.oauth2.provider.token.AuthenticationKeyGenerator; -import org.springframework.security.oauth2.provider.token.DefaultAuthenticationKeyGenerator; -import org.springframework.security.oauth2.provider.token.TokenStore; - -import java.time.Instant; -import java.time.LocalDateTime; -import java.time.ZoneId; -import java.util.*; -import java.util.concurrent.TimeUnit; - -/** - * @version redis集群存储token - */ - -public class RedisTemplateTokenStore implements TokenStore { - - private static final String ACCESS = "access:"; - private static final String AUTH_TO_ACCESS = "auth_to_access:"; - private static final String AUTH = "auth:"; - private static final String REFRESH_AUTH = "refresh_auth:"; - private static final String ACCESS_TO_REFRESH = "access_to_refresh:"; - private static final String REFRESH = "refresh:"; - private static final String REFRESH_TO_ACCESS = "refresh_to_access:"; - private static final String CLIENT_ID_TO_ACCESS = "client_id_to_access:"; - private static final String UNAME_TO_ACCESS = "uname_to_access:"; - private static final String TOKEN = "token:"; - - private RedisTemplate redisTemplate; - - public RedisTemplate getRedisTemplate() { - return redisTemplate; - } - - public void setRedisTemplate(RedisTemplate redisTemplate) { - this.redisTemplate = redisTemplate; - } - - private AuthenticationKeyGenerator authenticationKeyGenerator = new DefaultAuthenticationKeyGenerator(); - - public void setAuthenticationKeyGenerator(AuthenticationKeyGenerator authenticationKeyGenerator) { - this.authenticationKeyGenerator = authenticationKeyGenerator; - } - - public OAuth2AccessToken getAccessToken(OAuth2Authentication authentication) { - String key = authenticationKeyGenerator.extractKey(authentication); - OAuth2AccessToken accessToken = (OAuth2AccessToken) redisTemplate.opsForValue().get(AUTH_TO_ACCESS + key); - if (accessToken != null - && !key.equals(authenticationKeyGenerator.extractKey(readAuthentication(accessToken.getValue())))) { - // Keep the stores consistent (maybe the same user is represented by - // this authentication but the details - // have changed) - storeAccessToken(accessToken, authentication); - } - return accessToken; - } - - public OAuth2Authentication readAuthentication(OAuth2AccessToken token) { - return readAuthentication(token.getValue()); - } - - public OAuth2Authentication readAuthentication(String token) { - return (OAuth2Authentication) this.redisTemplate.opsForValue().get(AUTH + token); - } - - public OAuth2Authentication readAuthenticationForRefreshToken(OAuth2RefreshToken token) { - return readAuthenticationForRefreshToken(token.getValue()); - } - - public OAuth2Authentication readAuthenticationForRefreshToken(String token) { - return (OAuth2Authentication) this.redisTemplate.opsForValue().get(REFRESH_AUTH + token); - } - - public void storeAccessToken(OAuth2AccessToken token, OAuth2Authentication authentication) { - - OAuth2AccessToken existingAccessToken = this.getAccessToken(authentication); - - this.redisTemplate.opsForValue().set(ACCESS + token.getValue(), token); - this.redisTemplate.opsForValue().set(AUTH + token.getValue(), authentication); - this.redisTemplate.opsForValue().set(AUTH_TO_ACCESS + authenticationKeyGenerator.extractKey(authentication), - token); - - Map params = new HashMap<>(); - - params.put("clientId", authentication.getOAuth2Request().getClientId()); - - if (authentication.getUserAuthentication() instanceof UsernamePasswordAuthenticationToken) { - UsernamePasswordAuthenticationToken authenticationToken = (UsernamePasswordAuthenticationToken) authentication - .getUserAuthentication(); - LoginAppUser appUser = (LoginAppUser) authenticationToken.getPrincipal(); - params.put("username", appUser.getUsername()); - params.put("authorities", appUser.getAuthorities()); - } - - if (!params.isEmpty()) { - this.redisTemplate.opsForValue().set(TOKEN + token.getValue(), params); - } - - if (!authentication.isClientOnly()) { - if (existingAccessToken != null) { - if (!existingAccessToken.isExpired()) { - int seconds = token.getExpiresIn(); - redisTemplate.expire(UNAME_TO_ACCESS + authentication.getOAuth2Request().getClientId(), seconds, - TimeUnit.SECONDS); - } else { - redisTemplate.opsForList().rightPush(UNAME_TO_ACCESS + getApprovalKey(authentication), token); - } - } else { - redisTemplate.opsForList().rightPush(UNAME_TO_ACCESS + getApprovalKey(authentication), token); - } - - } - - if (existingAccessToken != null) { - if (!existingAccessToken.isExpired()) { - int seconds = token.getExpiresIn(); - redisTemplate.expire(CLIENT_ID_TO_ACCESS + authentication.getOAuth2Request().getClientId(), seconds, - TimeUnit.SECONDS); - - } else { - redisTemplate.opsForList() - .rightPush(CLIENT_ID_TO_ACCESS + authentication.getOAuth2Request().getClientId(), token); - } - } else { - redisTemplate.opsForList().rightPush(CLIENT_ID_TO_ACCESS + authentication.getOAuth2Request().getClientId(), - token); - } - - if (token.getExpiration() != null) { - - int seconds = token.getExpiresIn(); - redisTemplate.expire(ACCESS + token.getValue(), seconds, TimeUnit.SECONDS); - redisTemplate.expire(AUTH + token.getValue(), seconds, TimeUnit.SECONDS); - redisTemplate.expire(TOKEN + token.getValue(), seconds, TimeUnit.SECONDS); - redisTemplate.expire(AUTH_TO_ACCESS + authenticationKeyGenerator.extractKey(authentication), seconds, - TimeUnit.SECONDS); - redisTemplate.expire(CLIENT_ID_TO_ACCESS + authentication.getOAuth2Request().getClientId(), seconds, - TimeUnit.SECONDS); - redisTemplate.expire(UNAME_TO_ACCESS + getApprovalKey(authentication), seconds, TimeUnit.SECONDS); - } - - OAuth2RefreshToken refreshToken = token.getRefreshToken(); - - if (token.getRefreshToken() != null && token.getRefreshToken().getValue() != null) { - this.redisTemplate.opsForValue().set(REFRESH_TO_ACCESS + token.getRefreshToken().getValue(), - token.getValue()); - this.redisTemplate.opsForValue().set(ACCESS_TO_REFRESH + token.getValue(), - token.getRefreshToken().getValue()); - - if (refreshToken instanceof ExpiringOAuth2RefreshToken) { - ExpiringOAuth2RefreshToken expiringRefreshToken = (ExpiringOAuth2RefreshToken) refreshToken; - Date expiration = expiringRefreshToken.getExpiration(); - if (expiration != null) { - int seconds = Long.valueOf((expiration.getTime() - System.currentTimeMillis()) / 1000L).intValue(); - - redisTemplate.expire(REFRESH_TO_ACCESS + token.getRefreshToken().getValue(), seconds, - TimeUnit.SECONDS); - redisTemplate.expire(ACCESS_TO_REFRESH + token.getValue(), seconds, TimeUnit.SECONDS); - - } - } - - } - } - - private String getApprovalKey(OAuth2Authentication authentication) { - String userName = authentication.getUserAuthentication() == null ? "" - : authentication.getUserAuthentication().getName(); - return getApprovalKey(authentication.getOAuth2Request().getClientId(), userName); - } - - private String getApprovalKey(String clientId, String userName) { - return clientId + (userName == null ? "" : ":" + userName); - } - - public void removeAccessToken(OAuth2AccessToken accessToken) { - removeAccessToken(accessToken.getValue()); - } - - public OAuth2AccessToken readAccessToken(String tokenValue) { - - OAuth2Authentication oauth2Authentication = (OAuth2Authentication) this.redisTemplate.opsForValue() - .get(AUTH + tokenValue); - OAuth2AccessToken oauth2AccessToken = (OAuth2AccessToken) this.redisTemplate.opsForValue() - .get(ACCESS + tokenValue); - if (oauth2Authentication != null) { - String auth_to_access = authenticationKeyGenerator.extractKey(oauth2Authentication); - if (oauth2AccessToken != null) { - if (oauth2AccessToken.getExpiresIn() < 180) { - - if (oauth2AccessToken instanceof DefaultOAuth2AccessToken) { - DefaultOAuth2AccessToken token = (DefaultOAuth2AccessToken) oauth2AccessToken; -// Calendar cal = Calendar.getInstance(); -// cal.add(Calendar.DATE, 30); -// Date date = cal.getTime(); - /** - * 自动续费 30分钟 - */ - LocalDateTime t1 = LocalDateTime.now().plusMinutes(30); - ZoneId zone = ZoneId.systemDefault(); - Instant instant = t1.atZone(zone).toInstant(); - Date date = Date.from(instant); - - token.setExpiration(date); - - int seconds = token.getExpiresIn(); - - this.redisTemplate.opsForValue().set(AUTH_TO_ACCESS + auth_to_access, token, seconds, - TimeUnit.SECONDS); - this.redisTemplate.opsForValue().set(ACCESS + token.getValue(), token, seconds, - TimeUnit.SECONDS); - - redisTemplate.expire(AUTH + token.getValue(), seconds, TimeUnit.SECONDS); - redisTemplate.expire(TOKEN + token.getValue(), seconds, TimeUnit.SECONDS); - - redisTemplate.expire( - CLIENT_ID_TO_ACCESS + oauth2Authentication.getOAuth2Request().getClientId(), seconds, - TimeUnit.SECONDS); - redisTemplate.expire(UNAME_TO_ACCESS + getApprovalKey(oauth2Authentication), seconds, - TimeUnit.SECONDS); - - } - - } - } - } - - return oauth2AccessToken; - } - - public void removeAccessToken(String tokenValue) { - OAuth2AccessToken removed = (OAuth2AccessToken) redisTemplate.opsForValue().get(ACCESS + tokenValue); - // Don't remove the refresh token - it's up to the caller to do that - OAuth2Authentication authentication = (OAuth2Authentication) this.redisTemplate.opsForValue() - .get(AUTH + tokenValue); - - this.redisTemplate.delete(AUTH + tokenValue); - redisTemplate.delete(ACCESS + tokenValue); - redisTemplate.delete(TOKEN + tokenValue); - this.redisTemplate.delete(ACCESS_TO_REFRESH + tokenValue); - - if (authentication != null) { - this.redisTemplate.delete(AUTH_TO_ACCESS + authenticationKeyGenerator.extractKey(authentication)); - - String clientId = authentication.getOAuth2Request().getClientId(); - - // redisTemplate.opsForList().rightPush("UNAME_TO_ACCESS:"+getApprovalKey(authentication), - // token) ; - redisTemplate.opsForList().leftPop(UNAME_TO_ACCESS + getApprovalKey(clientId, authentication.getName())); - - redisTemplate.opsForList().leftPop(CLIENT_ID_TO_ACCESS + clientId); - - this.redisTemplate.delete(AUTH_TO_ACCESS + authenticationKeyGenerator.extractKey(authentication)); - } - } - - public void storeRefreshToken(OAuth2RefreshToken refreshToken, OAuth2Authentication authentication) { - this.redisTemplate.opsForValue().set(REFRESH + refreshToken.getValue(), refreshToken); - this.redisTemplate.opsForValue().set(REFRESH_AUTH + refreshToken.getValue(), authentication); - } - - public OAuth2RefreshToken readRefreshToken(String tokenValue) { - return (OAuth2RefreshToken) this.redisTemplate.opsForValue().get(REFRESH + tokenValue); - } - - public void removeRefreshToken(OAuth2RefreshToken refreshToken) { - removeRefreshToken(refreshToken.getValue()); - } - - public void removeRefreshToken(String tokenValue) { - this.redisTemplate.delete(REFRESH + tokenValue); - this.redisTemplate.delete(REFRESH_AUTH + tokenValue); - this.redisTemplate.delete(REFRESH_TO_ACCESS + tokenValue); - } - - public void removeAccessTokenUsingRefreshToken(OAuth2RefreshToken refreshToken) { - removeAccessTokenUsingRefreshToken(refreshToken.getValue()); - } - - private void removeAccessTokenUsingRefreshToken(String refreshToken) { - - String token = (String) this.redisTemplate.opsForValue().get(REFRESH_TO_ACCESS + refreshToken); - - if (token != null) { - redisTemplate.delete(REFRESH_TO_ACCESS + refreshToken); - } - } - - public Collection findTokensByClientIdAndUserName(String clientId, String userName) { - List result = redisTemplate.opsForList().range(UNAME_TO_ACCESS + getApprovalKey(clientId, userName), 0, - -1); - - if (result == null || result.size() == 0) { - return Collections.emptySet(); - } - List accessTokens = new ArrayList(result.size()); - - for (Iterator it = result.iterator(); it.hasNext();) { - OAuth2AccessToken accessToken = (OAuth2AccessToken) it.next(); - accessTokens.add(accessToken); - } - - return Collections.unmodifiableCollection(accessTokens); - } - - public Collection findTokensByClientId(String clientId) { - List result = redisTemplate.opsForList().range((CLIENT_ID_TO_ACCESS + clientId), 0, -1); - - if (result == null || result.size() == 0) { - return Collections.emptySet(); - } - List accessTokens = new ArrayList(result.size()); - - for (Iterator it = result.iterator(); it.hasNext();) { - OAuth2AccessToken accessToken = (OAuth2AccessToken) it.next(); - accessTokens.add(accessToken); - } - - return Collections.unmodifiableCollection(accessTokens); - } - -} diff --git a/cloud/autho/src/main/java/com/sincere/autho/utils/SpringUtil.java b/cloud/autho/src/main/java/com/sincere/autho/utils/SpringUtil.java deleted file mode 100644 index 994db76..0000000 --- a/cloud/autho/src/main/java/com/sincere/autho/utils/SpringUtil.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.sincere.autho.utils; - -import org.springframework.beans.BeansException; -import org.springframework.context.ApplicationContext; -import org.springframework.context.ApplicationContextAware; -import org.springframework.core.env.Environment; -import org.springframework.stereotype.Component; - -/** - * spring获取bean工具类 - * - * - */ -@Component -public class SpringUtil implements ApplicationContextAware { - - private static ApplicationContext applicationContext = null; - - @Override - public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { - SpringUtil.applicationContext = applicationContext; - } - - public static T getBean(Class cla) { - return applicationContext.getBean(cla); - } - - public static T getBean(String name, Class cal) { - return applicationContext.getBean(name, cal); - } - - public static String getProperty(String key) { - return applicationContext.getBean(Environment.class).getProperty(key); - } -} diff --git a/cloud/autho/src/main/java/com/sincere/autho/utils/SysUserUtil.java b/cloud/autho/src/main/java/com/sincere/autho/utils/SysUserUtil.java deleted file mode 100644 index 6b38473..0000000 --- a/cloud/autho/src/main/java/com/sincere/autho/utils/SysUserUtil.java +++ /dev/null @@ -1,41 +0,0 @@ -package com.sincere.autho.utils; - -import com.sincere.common.model.system.LoginAppUser; -import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; -import org.springframework.security.core.Authentication; -import org.springframework.security.core.context.SecurityContextHolder; -import org.springframework.security.oauth2.provider.OAuth2Authentication; -import org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken; - -/** - * @author 作者 owen E-mail: 624191343@qq.com - * @version 创建时间:2017年11月12日 上午22:57:51 获取用户信息 - */ -public class SysUserUtil { - - /** - * 获取登陆的 LoginAppUser - * - * @return - */ - @SuppressWarnings("rawtypes") - public static LoginAppUser getLoginAppUser() { - Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); - if (authentication instanceof OAuth2Authentication) { - OAuth2Authentication oAuth2Auth = (OAuth2Authentication) authentication; - authentication = oAuth2Auth.getUserAuthentication(); - - if (authentication instanceof UsernamePasswordAuthenticationToken) { - UsernamePasswordAuthenticationToken authenticationToken = (UsernamePasswordAuthenticationToken) authentication; - return (LoginAppUser) authenticationToken.getPrincipal(); - } else if (authentication instanceof PreAuthenticatedAuthenticationToken) { - // 刷新token方式 - PreAuthenticatedAuthenticationToken authenticationToken = (PreAuthenticatedAuthenticationToken) authentication; - return (LoginAppUser) authenticationToken.getPrincipal(); - - } - } - - return null; - } -} diff --git a/cloud/autho/src/main/resources/application.yaml b/cloud/autho/src/main/resources/application.yaml index dac2081..fb5f629 100644 --- a/cloud/autho/src/main/resources/application.yaml +++ b/cloud/autho/src/main/resources/application.yaml @@ -1,76 +1,22 @@ server: - port: 8763 + port: 9005 spring: application: - name: auth-server -session: - store-type: redis + name: authserver datasource: - dynamic: - enable: true - druid: - # JDBC (Զurlmysqlʶ,ԴԶʶ) - core: - url: jdbc:mysql://localhost/oauth-center?useUnicode=true&characterEncoding=utf-8&allowMultiQueries=true&useSSL=false - username: root - password: root - driver-class-name: com.mysql.jdbc.Driver - log: - url: jdbc:mysql://59.110.164.254:3306/log-center?useUnicode=true&characterEncoding=utf-8&allowMultiQueries=true&useSSL=false - username: root - password: root - driver-class-name: com.mysql.jdbc.Driver - #ӳ(ͨ˵ֻҪ޸initialSizeminIdlemaxActive - initial-size: 1 - max-active: 20 - min-idle: 1 - # ûȡӵȴʱʱ - max-wait: 60000 - #PSCacheָÿPSCacheĴС - pool-prepared-statements: true - max-pool-prepared-statement-per-connection-size: 20 - validation-query: SELECT 'x' - test-on-borrow: false - test-on-return: false - test-while-idle: true - #üòŽһμ⣬ҪرյĿӣλǺ - time-between-eviction-runs-millis: 60000 - #һڳСʱ䣬λǺ - min-evictable-idle-time-millis: 300000 - filters: stat,wall - # WebStatFilterã˵οDruid Wiki_WebStatFilter - #ǷStatFilterĬֵtrue - web-stat-filter.enabled: true - web-stat-filter.url-pattern: /* - web-stat-filter.exclusions: "*.js , *.gif ,*.jpg ,*.png ,*.css ,*.ico , /druid/*" - web-stat-filter.session-stat-max-count: 1000 - web-stat-filter.profile-enable: true - # StatViewServlet - #չʾDruidͳϢ,StatViewServlet;1.ṩϢչʾhtmlҳ2.ṩϢJSON API - #ǷStatViewServletĬֵtrue - stat-view-servlet.enabled: true - #еurl-patternüҳ棬ãüҳҳ/druid/index.html磺 - #http://110.76.43.235:9000/druid/index.html - #http://110.76.43.235:8080/mini-web/druid/index.html - stat-view-servlet.url-pattern: /druid/* - #ͳ - stat-view-servlet.reset-enable: true - stat-view-servlet.login-username: admin - stat-view-servlet.login-password: admin - #StatViewSerlvetչʾļϢȽУϵͳеڲҪʿƣallowdeny - #denyallowdenyбУallowбУҲᱻܾallowûûΪգз - #õĸʽ - # - #/128.242.127.1/24 - #24ʾǰ24λ룬ȶԵʱǰ24λͬƥ,֧IPV6 - #stat-view-servlet.allow= - #stat-view-servlet.deny=128.242.127.1/24,128.242.128.1 - # Springã˵οDruid Github Wiki_DruidSpring - #aop-patterns= # SpringAOP㣬x.y.z.service.*,öӢĶŷָ -################### mysq end ########################## - - + username: szjxtuser + password: RQminVCJota3H1u8bBYH + url: jdbc:sqlserver://116.62.155.137:33419;database=SmartCampus + driver-class-name: com.microsoft.sqlserver.jdbc.SQLServerDriver +##mybatis +mybatis: + mapper-locations: classpath:mapper/*.xml + type-aliases-package: com.sincere.autho.mapper + check-config-location: true +ribbon: + ReadTimeout: 50000 + ConnectTimeout: 5000 eureka: instance: hostname: localhost @@ -78,19 +24,5 @@ eureka: lease-renewal-interval-in-seconds: 10 client: service-url: - defaultZone: http://121.40.109.21:8761/eureka/,http://121.40.109.21:8762/eureka/ - + defaultZone: http://localhost:8761/eureka/,http://localhost:8762/eureka/ - redis: - ################### redis start ########################## - host: localhost - port: 6379 - timeout: 6000 - database: 2 - lettuce: - pool: - max-active: 10 # ӳʹøֵʾûƣ,ֵΪ-1ʾƣpoolѾmaxActivejedisʵʱpool״̬Ϊexhausted(ľ) - max-idle: 8 # ӳе ĬֵҲ8 - max-wait: 100 # # ȴӵʱ䣬λ룬ĬֵΪ-1ʾʱȴʱ䣬ֱ׳JedisConnectionException - min-idle: 2 # ӳеС ĬֵҲ0 - shutdown-timeout: 100ms \ No newline at end of file diff --git a/cloud/autho/src/main/resources/mapper/UserMapper.xml b/cloud/autho/src/main/resources/mapper/UserMapper.xml new file mode 100644 index 0000000..fbb748a --- /dev/null +++ b/cloud/autho/src/main/resources/mapper/UserMapper.xml @@ -0,0 +1,14 @@ + + + + + + + + + + diff --git a/cloud/common/src/main/java/com/sincere/common/util/TokenUtils.java b/cloud/common/src/main/java/com/sincere/common/util/TokenUtils.java index 86e6b90..98c4b74 100644 --- a/cloud/common/src/main/java/com/sincere/common/util/TokenUtils.java +++ b/cloud/common/src/main/java/com/sincere/common/util/TokenUtils.java @@ -20,7 +20,7 @@ public class TokenUtils { /** * 过期时间5秒 */ - private static final long EXPIRE_TIME = 1000 * 60 * 60 * 24; + private static final long EXPIRE_TIME = 1000 * 60 * 60 * 24 * 3; /** diff --git a/cloud/getaway/src/main/java/com/sincere/getaway/client/filter/AccessFilter.java b/cloud/getaway/src/main/java/com/sincere/getaway/client/filter/AccessFilter.java index 34e97c9..4919a65 100644 --- a/cloud/getaway/src/main/java/com/sincere/getaway/client/filter/AccessFilter.java +++ b/cloud/getaway/src/main/java/com/sincere/getaway/client/filter/AccessFilter.java @@ -63,8 +63,8 @@ public class AccessFilter implements GlobalFilter, Ordered { exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED); ServerHttpResponse response = exchange.getResponse(); JSONObject message = new JSONObject(); - message.put("resp_code", result.getCode()); - message.put("resp_msg", result.getMessage()); + message.put("code", result.getCode()); + message.put("message", result.getMessage()); byte[] bits = message.toJSONString().getBytes(StandardCharsets.UTF_8); DataBuffer buffer = response.bufferFactory().wrap(bits); response.setStatusCode(HttpStatus.UNAUTHORIZED); @@ -86,7 +86,7 @@ public class AccessFilter implements GlobalFilter, Ordered { return ResultEnums.getByCode(e.getCode()); } } - return ResultEnums.error ; + return ResultEnums.success ; } public String extractToken(ServerHttpRequest request) { diff --git a/cloud/getaway/src/main/resources/application.yml b/cloud/getaway/src/main/resources/application.yml index 387e262..2a3da5f 100644 --- a/cloud/getaway/src/main/resources/application.yml +++ b/cloud/getaway/src/main/resources/application.yml @@ -27,5 +27,11 @@ spring: - Path=/haikangserver/** filters: - StripPrefix=1 + - id: authserver + uri: lb://authserver + predicates: + - Path=/authserver/** + filters: + - StripPrefix=1 url: - ignored: /user/** \ No newline at end of file + ignored: /authserver/** \ No newline at end of file diff --git a/cloud/user_search/src/main/java/com/sincere/userSearch/controller/UserController.java b/cloud/user_search/src/main/java/com/sincere/userSearch/controller/UserController.java index 3ff937e..d133d8c 100644 --- a/cloud/user_search/src/main/java/com/sincere/userSearch/controller/UserController.java +++ b/cloud/user_search/src/main/java/com/sincere/userSearch/controller/UserController.java @@ -40,8 +40,8 @@ public class UserController { */ @ApiOperation("根据userId 获取用户信息") @RequestMapping(value = "getUserInfo" , method = RequestMethod.GET) - public String getUserInfo(){ - return "aa" ; + public String getUserInfo(UserInfo userInfo){ + return userInfo.getUserId() ; } public void getUserId(){ diff --git a/cloud/user_search/src/main/resources/application.yaml b/cloud/user_search/src/main/resources/application.yaml index c8e13b9..3520bbc 100644 --- a/cloud/user_search/src/main/resources/application.yaml +++ b/cloud/user_search/src/main/resources/application.yaml @@ -12,7 +12,7 @@ spring: ##mybatis mybatis: mapper-locations: classpath:mapper/*.xml - type-aliases-package: com.sincere.quartz.mapper + type-aliases-package: com.sincere.userSearch.mapper check-config-location: true ribbon: ReadTimeout: 50000 -- libgit2 0.21.0