Commit e5d1fbedcfdd63f9e6883ef5d2fb23782bae520d
1 parent
5b7afb68
Exists in
master
认证中心 登录接口
Showing
37 changed files
with
352 additions
and
2128 deletions
Show diff stats
cloud/autho/pom.xml
| ... | ... | @@ -13,63 +13,142 @@ |
| 13 | 13 | <name>autho</name> |
| 14 | 14 | <description>Demo project for Spring Boot</description> |
| 15 | 15 | |
| 16 | - <properties> | |
| 17 | - <java.version>1.8</java.version> | |
| 18 | - <spring-cloud.version>Greenwich.SR2</spring-cloud.version> | |
| 19 | - </properties> | |
| 20 | - | |
| 21 | 16 | <dependencies> |
| 22 | 17 | <dependency> |
| 23 | 18 | <groupId>com.sincere</groupId> |
| 24 | 19 | <artifactId>common</artifactId> |
| 25 | - <version>0.0.1-SNAPSHOT</version> | |
| 20 | + <version>1.0.0</version> | |
| 26 | 21 | </dependency> |
| 27 | 22 | <dependency> |
| 28 | - <groupId>org.springframework.cloud</groupId> | |
| 29 | - <artifactId>spring-cloud-starter-oauth2</artifactId> | |
| 23 | + <groupId>org.springframework.boot</groupId> | |
| 24 | + <artifactId>spring-boot-starter-test</artifactId> | |
| 25 | + <scope>test</scope> | |
| 30 | 26 | </dependency> |
| 31 | - | |
| 32 | 27 | <dependency> |
| 33 | 28 | <groupId>org.springframework.cloud</groupId> |
| 34 | - <artifactId>spring-cloud-starter-security</artifactId> | |
| 35 | - <version>2.1.3.RELEASE</version> | |
| 29 | + <artifactId>spring-cloud-starter-feign</artifactId> | |
| 30 | + <version>1.3.6.RELEASE</version> | |
| 36 | 31 | </dependency> |
| 37 | 32 | <dependency> |
| 38 | 33 | <groupId>org.springframework.cloud</groupId> |
| 39 | - <artifactId>spring-cloud-starter-openfeign</artifactId> | |
| 34 | + <artifactId>spring-cloud-openfeign-core</artifactId> | |
| 35 | + <version>2.1.2.RELEASE</version> | |
| 40 | 36 | </dependency> |
| 41 | - | |
| 42 | 37 | <dependency> |
| 43 | - <groupId>org.springframework.boot</groupId> | |
| 44 | - <artifactId>spring-boot-starter-data-redis</artifactId> | |
| 38 | + <groupId>org.apache.commons</groupId> | |
| 39 | + <artifactId>commons-lang3</artifactId> | |
| 40 | + <version>3.3.2</version> | |
| 45 | 41 | </dependency> |
| 46 | 42 | <dependency> |
| 47 | - <groupId>io.grpc</groupId> | |
| 48 | - <artifactId>grpc-core</artifactId> | |
| 49 | - <version>1.18.0</version> | |
| 43 | + <groupId>org.mybatis.spring.boot</groupId> | |
| 44 | + <artifactId>mybatis-spring-boot-starter</artifactId> | |
| 45 | + <version>1.3.0</version> | |
| 50 | 46 | </dependency> |
| 51 | - | |
| 52 | 47 | <dependency> |
| 53 | - <groupId>io.springfox</groupId> | |
| 54 | - <artifactId>springfox-swagger2</artifactId> | |
| 55 | - <version>2.9.2</version> | |
| 48 | + <groupId>com.microsoft.sqlserver</groupId> | |
| 49 | + <artifactId>mssql-jdbc</artifactId> | |
| 50 | + <version>6.4.0.jre8</version> | |
| 56 | 51 | </dependency> |
| 57 | - | |
| 58 | 52 | <dependency> |
| 59 | - <groupId>io.springfox</groupId> | |
| 60 | - <artifactId>springfox-swagger-ui</artifactId> | |
| 61 | - <version>2.9.2</version> | |
| 53 | + <groupId>org.springframework.boot</groupId> | |
| 54 | + <artifactId>spring-boot-starter-web</artifactId> | |
| 62 | 55 | </dependency> |
| 63 | - | |
| 64 | 56 | </dependencies> |
| 65 | 57 | |
| 58 | + <dependencyManagement> | |
| 59 | + <dependencies> | |
| 60 | + <dependency> | |
| 61 | + <groupId>org.springframework.cloud</groupId> | |
| 62 | + <artifactId>spring-cloud-dependencies</artifactId> | |
| 63 | + <version>${spring-cloud.version}</version> | |
| 64 | + <type>pom</type> | |
| 65 | + <scope>import</scope> | |
| 66 | + </dependency> | |
| 67 | + </dependencies> | |
| 68 | + </dependencyManagement> | |
| 69 | + | |
| 66 | 70 | <build> |
| 71 | + <!--打包文件名--> | |
| 72 | + <finalName>quartz_server</finalName> | |
| 73 | + <!--打包方式--> | |
| 67 | 74 | <plugins> |
| 75 | + <!-- 设置编译版本 --> | |
| 76 | + <plugin> | |
| 77 | + <groupId>org.apache.maven.plugins</groupId> | |
| 78 | + <artifactId>maven-compiler-plugin</artifactId> | |
| 79 | + <version>3.1</version> | |
| 80 | + <configuration> | |
| 81 | + <source>1.8</source> | |
| 82 | + <target>1.8</target> | |
| 83 | + <encoding>UTF-8</encoding> | |
| 84 | + </configuration> | |
| 85 | + </plugin> | |
| 86 | + <!-- 打包jar文件时,配置manifest文件,加入lib包的jar依赖 --> | |
| 87 | + <!-- 本地启动需要注释--> | |
| 88 | + <plugin> | |
| 89 | + <groupId>org.apache.maven.plugins</groupId> | |
| 90 | + <artifactId>maven-jar-plugin</artifactId> | |
| 91 | + <configuration> | |
| 92 | + <archive> | |
| 93 | + <manifest> | |
| 94 | + <mainClass>com.sincere.userSearch.UserApplication</mainClass> | |
| 95 | + <addClasspath>true</addClasspath> | |
| 96 | + <classpathPrefix>lib/</classpathPrefix> | |
| 97 | + </manifest> | |
| 98 | + <manifestEntries> | |
| 99 | + <Class-Path>./config/</Class-Path> | |
| 100 | + </manifestEntries> | |
| 101 | + </archive> | |
| 102 | + <excludes> | |
| 103 | + <exclude>config/**</exclude> | |
| 104 | + </excludes> | |
| 105 | + <classesDirectory></classesDirectory> | |
| 106 | + </configuration> | |
| 107 | + </plugin> | |
| 108 | + <!-- 拷贝依赖的jar包到lib目录 --> | |
| 68 | 109 | <plugin> |
| 69 | - <groupId>org.springframework.boot</groupId> | |
| 70 | - <artifactId>spring-boot-maven-plugin</artifactId> | |
| 110 | + <groupId>org.apache.maven.plugins</groupId> | |
| 111 | + <artifactId>maven-dependency-plugin</artifactId> | |
| 112 | + <executions> | |
| 113 | + <execution> | |
| 114 | + <id>copy</id> | |
| 115 | + <phase>package</phase> | |
| 116 | + <goals> | |
| 117 | + <goal>copy-dependencies</goal> | |
| 118 | + </goals> | |
| 119 | + <configuration> | |
| 120 | + <outputDirectory> | |
| 121 | + ${project.build.directory}/lib | |
| 122 | + </outputDirectory> | |
| 123 | + </configuration> | |
| 124 | + </execution> | |
| 125 | + </executions> | |
| 126 | + </plugin> | |
| 127 | + <!-- 解决资源文件的编码问题 --> | |
| 128 | + <plugin> | |
| 129 | + <groupId>org.apache.maven.plugins</groupId> | |
| 130 | + <artifactId>maven-resources-plugin</artifactId> | |
| 131 | + <version>2.5</version> | |
| 132 | + <configuration> | |
| 133 | + <encoding>UTF-8</encoding> | |
| 134 | + </configuration> | |
| 135 | + </plugin> | |
| 136 | + <!-- 打包source文件为jar文件 --> | |
| 137 | + <plugin> | |
| 138 | + <artifactId>maven-source-plugin</artifactId> | |
| 139 | + <version>2.2</version> | |
| 140 | + <configuration> | |
| 141 | + <attach>true</attach> | |
| 142 | + </configuration> | |
| 143 | + <executions> | |
| 144 | + <execution> | |
| 145 | + <phase>compile</phase> | |
| 146 | + <goals> | |
| 147 | + <goal>jar</goal> | |
| 148 | + </goals> | |
| 149 | + </execution> | |
| 150 | + </executions> | |
| 71 | 151 | </plugin> |
| 72 | 152 | </plugins> |
| 73 | 153 | </build> |
| 74 | - | |
| 75 | 154 | </project> | ... | ... |
cloud/autho/src/main/java/com/sincere/autho/AuthoApplication.java
| 1 | 1 | package com.sincere.autho; |
| 2 | 2 | |
| 3 | +import org.mybatis.spring.annotation.MapperScan; | |
| 3 | 4 | import org.springframework.boot.SpringApplication; |
| 4 | 5 | import org.springframework.boot.autoconfigure.SpringBootApplication; |
| 5 | 6 | import org.springframework.cloud.client.discovery.EnableDiscoveryClient; |
| 6 | 7 | |
| 7 | 8 | @EnableDiscoveryClient |
| 8 | 9 | @SpringBootApplication |
| 10 | +@MapperScan("com.sincere.autho.mapper") | |
| 9 | 11 | public class AuthoApplication { |
| 10 | 12 | |
| 11 | 13 | public static void main(String[] args) { | ... | ... |
cloud/autho/src/main/java/com/sincere/autho/Swagger2.java
0 → 100644
| ... | ... | @@ -0,0 +1,52 @@ |
| 1 | +package com.sincere.autho; | |
| 2 | + | |
| 3 | +import io.swagger.annotations.ApiOperation; | |
| 4 | +import org.springframework.context.annotation.Bean; | |
| 5 | +import org.springframework.context.annotation.Configuration; | |
| 6 | +import springfox.documentation.builders.ApiInfoBuilder; | |
| 7 | +import springfox.documentation.builders.ParameterBuilder; | |
| 8 | +import springfox.documentation.builders.PathSelectors; | |
| 9 | +import springfox.documentation.builders.RequestHandlerSelectors; | |
| 10 | +import springfox.documentation.schema.ModelRef; | |
| 11 | +import springfox.documentation.service.ApiInfo; | |
| 12 | +import springfox.documentation.service.Parameter; | |
| 13 | +import springfox.documentation.spi.DocumentationType; | |
| 14 | +import springfox.documentation.spring.web.plugins.Docket; | |
| 15 | +import springfox.documentation.swagger2.annotations.EnableSwagger2; | |
| 16 | + | |
| 17 | +import java.util.ArrayList; | |
| 18 | +import java.util.List; | |
| 19 | + | |
| 20 | +@EnableSwagger2 | |
| 21 | +@Configuration //让Spring来加载该类配置 | |
| 22 | +public class Swagger2 { | |
| 23 | + | |
| 24 | + @Bean | |
| 25 | + public Docket createRestApi() { | |
| 26 | + ParameterBuilder ticketPar = new ParameterBuilder(); | |
| 27 | + List<Parameter> pars = new ArrayList<Parameter>(); | |
| 28 | + ticketPar.name("X-Authorization").description("user token") | |
| 29 | + .modelRef(new ModelRef("string")).parameterType("header") | |
| 30 | + .required(false).build(); //header中的ticket参数非必填,传空也可以 | |
| 31 | + pars.add(ticketPar.build()); | |
| 32 | + | |
| 33 | + | |
| 34 | + return new Docket(DocumentationType.SWAGGER_2) | |
| 35 | + .apiInfo(apiInfo()) | |
| 36 | + .enableUrlTemplating(true) | |
| 37 | + .select() | |
| 38 | + // 扫描所有有注解的api,用这种方式更灵活 | |
| 39 | + .apis(RequestHandlerSelectors.basePackage("com.sincere.autho.control")) | |
| 40 | + .paths(PathSelectors.any()) | |
| 41 | + .build().globalOperationParameters(pars); | |
| 42 | + | |
| 43 | + } | |
| 44 | + private ApiInfo apiInfo() { | |
| 45 | + return new ApiInfoBuilder() | |
| 46 | + .title("Spring Boot中使用Swagger2构建RESTful APIs") | |
| 47 | + .description("接口文档") | |
| 48 | + .termsOfServiceUrl("") | |
| 49 | + .version("1.0") | |
| 50 | + .build(); | |
| 51 | + } | |
| 52 | +} | ... | ... |
cloud/autho/src/main/java/com/sincere/autho/annotation/EnableLogging.java
| ... | ... | @@ -1,22 +0,0 @@ |
| 1 | -package com.sincere.autho.annotation; | |
| 2 | - | |
| 3 | -import com.sincere.autho.autoconfigure.LoggingConfigurationSelector; | |
| 4 | -import org.springframework.context.annotation.Import; | |
| 5 | - | |
| 6 | -import java.lang.annotation.*; | |
| 7 | - | |
| 8 | - | |
| 9 | -/** | |
| 10 | - * 启动日志框架支持 | |
| 11 | - * @author owen | |
| 12 | - * @create 2017年7月2日 | |
| 13 | - */ | |
| 14 | - | |
| 15 | -@Target(ElementType.TYPE) | |
| 16 | -@Retention(RetentionPolicy.RUNTIME) | |
| 17 | -@Documented | |
| 18 | -//自动装配starter | |
| 19 | -@Import(LoggingConfigurationSelector.class) | |
| 20 | -public @interface EnableLogging{ | |
| 21 | -// String name() ; | |
| 22 | -} | |
| 23 | 0 | \ No newline at end of file |
cloud/autho/src/main/java/com/sincere/autho/annotation/datasource/DataSource.java
| ... | ... | @@ -1,16 +0,0 @@ |
| 1 | -package com.sincere.autho.annotation.datasource; | |
| 2 | - | |
| 3 | -import java.lang.annotation.*; | |
| 4 | - | |
| 5 | - | |
| 6 | -/** | |
| 7 | - * 数据源选择 | |
| 8 | - * @author owen | |
| 9 | - * @create 2017年7月2日 | |
| 10 | - */ | |
| 11 | -@Target({ElementType.METHOD, ElementType.TYPE}) | |
| 12 | -@Retention(RetentionPolicy.RUNTIME) | |
| 13 | -@Documented | |
| 14 | -public @interface DataSource { | |
| 15 | - String name(); | |
| 16 | -} | |
| 17 | 0 | \ No newline at end of file |
cloud/autho/src/main/java/com/sincere/autho/annotation/log/LogAnnotation.java
| ... | ... | @@ -1,26 +0,0 @@ |
| 1 | -package com.sincere.autho.annotation.log; | |
| 2 | - | |
| 3 | -import java.lang.annotation.*; | |
| 4 | - | |
| 5 | -/** | |
| 6 | - * 日志注解 | |
| 7 | - * @author owen | |
| 8 | - * @create 2017年7月2日 | |
| 9 | - */ | |
| 10 | -@Target({ElementType.METHOD, ElementType.TYPE}) | |
| 11 | -@Retention(RetentionPolicy.RUNTIME) | |
| 12 | -@Documented | |
| 13 | -public @interface LogAnnotation { | |
| 14 | - | |
| 15 | - /** | |
| 16 | - * 模块 | |
| 17 | - * @return | |
| 18 | - */ | |
| 19 | - String module(); | |
| 20 | - | |
| 21 | - /** | |
| 22 | - * 记录执行参数 | |
| 23 | - * @return | |
| 24 | - */ | |
| 25 | - boolean recordRequestParam() default true; | |
| 26 | -} |
cloud/autho/src/main/java/com/sincere/autho/autoconfigure/LoggingConfigurationSelector.java
| ... | ... | @@ -1,23 +0,0 @@ |
| 1 | -package com.sincere.autho.autoconfigure; | |
| 2 | - | |
| 3 | -import org.springframework.context.annotation.ImportSelector; | |
| 4 | -import org.springframework.core.type.AnnotationMetadata; | |
| 5 | - | |
| 6 | -/** | |
| 7 | - * @author owen | |
| 8 | - * @create 2017年7月2日 | |
| 9 | - * 装配bean | |
| 10 | - */ | |
| 11 | -public class LoggingConfigurationSelector implements ImportSelector { | |
| 12 | - | |
| 13 | - @Override | |
| 14 | - public String[] selectImports(AnnotationMetadata importingClassMetadata) { | |
| 15 | - // TODO Auto-generated method stub | |
| 16 | -// importingClassMetadata.getAllAnnotationAttributes(EnableEcho.class.getName()); | |
| 17 | - return new String[] { | |
| 18 | - "com.sincere.autho.autoconfigure.datasource.DataSourceAspect", | |
| 19 | - "com.sincere.autho.autoconfigure.log.LogAnnotationAspect" | |
| 20 | - }; | |
| 21 | - } | |
| 22 | - | |
| 23 | -} |
cloud/autho/src/main/java/com/sincere/autho/autoconfigure/datasource/DataSourceAspect.java
| ... | ... | @@ -1,42 +0,0 @@ |
| 1 | -package com.sincere.autho.autoconfigure.datasource; | |
| 2 | - | |
| 3 | -import com.sincere.autho.annotation.datasource.DataSource; | |
| 4 | -import com.sincere.common.config.DataSourceHolder; | |
| 5 | -import com.sincere.common.config.DataSourceKey; | |
| 6 | -import org.aspectj.lang.JoinPoint; | |
| 7 | -import org.aspectj.lang.annotation.After; | |
| 8 | -import org.aspectj.lang.annotation.Aspect; | |
| 9 | -import org.aspectj.lang.annotation.Before; | |
| 10 | -import org.slf4j.Logger; | |
| 11 | -import org.slf4j.LoggerFactory; | |
| 12 | -import org.springframework.core.annotation.Order; | |
| 13 | - | |
| 14 | -/** | |
| 15 | - * 切换数据源Advice | |
| 16 | - */ | |
| 17 | -@Aspect | |
| 18 | -@Order(-1) // 保证该AOP在@Transactional之前执行 | |
| 19 | -public class DataSourceAspect { | |
| 20 | - | |
| 21 | - private static final Logger logger = LoggerFactory.getLogger(DataSourceAspect.class); | |
| 22 | - | |
| 23 | - @Before("@annotation(ds)") | |
| 24 | - public void changeDataSource(JoinPoint point, DataSource ds) throws Throwable { | |
| 25 | - String dsId = ds.name(); | |
| 26 | - try { | |
| 27 | - DataSourceKey dataSourceKey = DataSourceKey.valueOf(dsId); | |
| 28 | - DataSourceHolder.setDataSourceKey(dataSourceKey); | |
| 29 | - } catch (Exception e) { | |
| 30 | - logger.error("数据源[{}]不存在,使用默认数据源 > {}", ds.name(), point.getSignature()); | |
| 31 | - } | |
| 32 | - | |
| 33 | - | |
| 34 | - } | |
| 35 | - | |
| 36 | - @After("@annotation(ds)") | |
| 37 | - public void restoreDataSource(JoinPoint point, DataSource ds) { | |
| 38 | - logger.debug("Revert DataSource : {transIdo} > {}", ds.name(), point.getSignature()); | |
| 39 | - DataSourceHolder.clearDataSourceKey(); | |
| 40 | - } | |
| 41 | - | |
| 42 | -} | |
| 43 | 0 | \ No newline at end of file |
cloud/autho/src/main/java/com/sincere/autho/autoconfigure/log/LogAnnotationAspect.java
| ... | ... | @@ -1,133 +0,0 @@ |
| 1 | -package com.sincere.autho.autoconfigure.log; | |
| 2 | - | |
| 3 | -import com.alibaba.fastjson.JSON; | |
| 4 | -import com.alibaba.fastjson.JSONObject; | |
| 5 | -import com.sincere.autho.annotation.log.LogAnnotation; | |
| 6 | -import com.sincere.autho.log.service.LogService; | |
| 7 | -import com.sincere.autho.log.service.impl.LogServiceImpl; | |
| 8 | -import com.sincere.autho.utils.SysUserUtil; | |
| 9 | -import com.sincere.common.model.log.SysLog; | |
| 10 | -import com.sincere.common.model.system.LoginAppUser; | |
| 11 | -import com.sincere.common.util.SpringUtils; | |
| 12 | -import org.aspectj.lang.ProceedingJoinPoint; | |
| 13 | -import org.aspectj.lang.annotation.Around; | |
| 14 | -import org.aspectj.lang.annotation.Aspect; | |
| 15 | -import org.aspectj.lang.reflect.MethodSignature; | |
| 16 | -import org.slf4j.Logger; | |
| 17 | -import org.slf4j.LoggerFactory; | |
| 18 | -import org.springframework.core.annotation.Order; | |
| 19 | - | |
| 20 | -import javax.servlet.http.HttpServletRequest; | |
| 21 | -import javax.servlet.http.HttpServletResponse; | |
| 22 | -import java.util.ArrayList; | |
| 23 | -import java.util.Date; | |
| 24 | -import java.util.List; | |
| 25 | -import java.util.concurrent.CompletableFuture; | |
| 26 | -import java.util.concurrent.ThreadLocalRandom; | |
| 27 | - | |
| 28 | -/** | |
| 29 | - * 保存日志 | |
| 30 | - * | |
| 31 | - * @author owen | |
| 32 | - * @create 2017年7月2日 | |
| 33 | - */ | |
| 34 | -@Aspect | |
| 35 | -@Order(-1) // 保证该AOP在@Transactional之前执行 | |
| 36 | -public class LogAnnotationAspect { | |
| 37 | - | |
| 38 | - private static final Logger logger = LoggerFactory.getLogger(LogAnnotationAspect.class); | |
| 39 | - | |
| 40 | - @Around("@annotation(ds)") | |
| 41 | - public Object logSave(ProceedingJoinPoint joinPoint, LogAnnotation ds) throws Throwable { | |
| 42 | - | |
| 43 | - // 请求流水号 | |
| 44 | - String transid = getRandom(); | |
| 45 | - // 记录开始时间 | |
| 46 | - long start = System.currentTimeMillis(); | |
| 47 | - // 获取方法参数 | |
| 48 | - String url = null; | |
| 49 | - String httpMethod = null; | |
| 50 | - Object result = null; | |
| 51 | - List<Object> httpReqArgs = new ArrayList<Object>(); | |
| 52 | - SysLog log = new SysLog(); | |
| 53 | - log.setCreateTime(new Date()); | |
| 54 | - LoginAppUser loginAppUser = SysUserUtil.getLoginAppUser(); | |
| 55 | - if (loginAppUser != null) { | |
| 56 | - log.setUsername(loginAppUser.getUsername()); | |
| 57 | - } | |
| 58 | - | |
| 59 | - MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature(); | |
| 60 | - | |
| 61 | - LogAnnotation logAnnotation = methodSignature.getMethod().getDeclaredAnnotation(LogAnnotation.class); | |
| 62 | - log.setModule(logAnnotation.module() + ":" + methodSignature.getDeclaringTypeName() + "/" | |
| 63 | - + methodSignature.getName()); | |
| 64 | - | |
| 65 | - Object[] args = joinPoint.getArgs();// 参数值 | |
| 66 | - url = methodSignature.getDeclaringTypeName() + "/"+ methodSignature.getName(); | |
| 67 | - for (Object object : args) { | |
| 68 | - if (object instanceof HttpServletRequest) { | |
| 69 | - HttpServletRequest request = (HttpServletRequest) object; | |
| 70 | - url = request.getRequestURI(); | |
| 71 | - httpMethod = request.getMethod(); | |
| 72 | - } else if (object instanceof HttpServletResponse) { | |
| 73 | - } else { | |
| 74 | - | |
| 75 | - httpReqArgs.add(object); | |
| 76 | - } | |
| 77 | - } | |
| 78 | - | |
| 79 | - try { | |
| 80 | - String params = JSONObject.toJSONString(httpReqArgs); | |
| 81 | - log.setParams(params); | |
| 82 | - // 打印请求参数参数 | |
| 83 | - logger.info("开始请求,transid={}, url={} , httpMethod={}, reqData={} ", transid, url, httpMethod, params); | |
| 84 | - } catch (Exception e) { | |
| 85 | - logger.error("记录参数失败:{}", e.getMessage()); | |
| 86 | - } | |
| 87 | - | |
| 88 | - try { | |
| 89 | - // 调用原来的方法 | |
| 90 | - result = joinPoint.proceed(); | |
| 91 | - log.setFlag(Boolean.TRUE); | |
| 92 | - } catch (Exception e) { | |
| 93 | - log.setFlag(Boolean.FALSE); | |
| 94 | - log.setRemark(e.getMessage()); | |
| 95 | - | |
| 96 | - throw e; | |
| 97 | - } finally { | |
| 98 | - | |
| 99 | - CompletableFuture.runAsync(() -> { | |
| 100 | - try { | |
| 101 | - if (logAnnotation.recordRequestParam()) { | |
| 102 | - LogService logService = SpringUtils.getBean(LogServiceImpl.class); | |
| 103 | - logService.save(log); | |
| 104 | - } | |
| 105 | - } catch (Exception e) { | |
| 106 | - logger.error("记录参数失败:{}", e.getMessage()); | |
| 107 | - } | |
| 108 | - | |
| 109 | - }); | |
| 110 | - // 获取回执报文及耗时 | |
| 111 | - logger.info("请求完成, transid={}, 耗时={}, resp={}:", transid, (System.currentTimeMillis() - start), | |
| 112 | - result == null ? null : JSON.toJSONString(result)); | |
| 113 | - | |
| 114 | - } | |
| 115 | - return result; | |
| 116 | - } | |
| 117 | - | |
| 118 | - /** | |
| 119 | - * 生成日志随机数 | |
| 120 | - * | |
| 121 | - * @return | |
| 122 | - */ | |
| 123 | - public String getRandom() { | |
| 124 | - int i = 0; | |
| 125 | - StringBuilder st = new StringBuilder(); | |
| 126 | - while (i < 5) { | |
| 127 | - i++; | |
| 128 | - st.append(ThreadLocalRandom.current().nextInt(10)); | |
| 129 | - } | |
| 130 | - return st.toString() + System.currentTimeMillis(); | |
| 131 | - } | |
| 132 | - | |
| 133 | -} | |
| 134 | 0 | \ No newline at end of file |
cloud/autho/src/main/java/com/sincere/autho/config/OAuth2ServerConfig.java
| ... | ... | @@ -1,260 +0,0 @@ |
| 1 | - | |
| 2 | -package com.sincere.autho.config; | |
| 3 | - | |
| 4 | -import com.sincere.autho.service.RedisAuthorizationCodeServices; | |
| 5 | -import com.sincere.autho.service.RedisClientDetailsService; | |
| 6 | -import com.sincere.autho.token.RedisTemplateTokenStore; | |
| 7 | -import com.sincere.common.props.PermitUrlProperties; | |
| 8 | -import org.springframework.beans.factory.annotation.Autowired; | |
| 9 | -import org.springframework.boot.autoconfigure.AutoConfigureAfter; | |
| 10 | -import org.springframework.boot.context.properties.EnableConfigurationProperties; | |
| 11 | -import org.springframework.context.annotation.Bean; | |
| 12 | -import org.springframework.context.annotation.Configuration; | |
| 13 | -import org.springframework.data.redis.core.RedisTemplate; | |
| 14 | -import org.springframework.security.authentication.AuthenticationManager; | |
| 15 | -import org.springframework.security.config.annotation.web.builders.HttpSecurity; | |
| 16 | -import org.springframework.security.config.annotation.web.builders.WebSecurity; | |
| 17 | -import org.springframework.security.core.userdetails.UserDetailsService; | |
| 18 | -import org.springframework.security.oauth2.common.OAuth2AccessToken; | |
| 19 | -import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer; | |
| 20 | -import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter; | |
| 21 | -import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer; | |
| 22 | -import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer; | |
| 23 | -import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter; | |
| 24 | -import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer; | |
| 25 | -import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer; | |
| 26 | -import org.springframework.security.oauth2.provider.code.RandomValueAuthorizationCodeServices; | |
| 27 | -import org.springframework.security.oauth2.provider.error.WebResponseExceptionTranslator; | |
| 28 | -import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter; | |
| 29 | -import org.springframework.security.oauth2.provider.token.store.JwtTokenStore; | |
| 30 | -import org.springframework.security.web.util.matcher.RequestMatcher; | |
| 31 | -import org.springframework.stereotype.Component; | |
| 32 | -import org.springframework.util.AntPathMatcher; | |
| 33 | - | |
| 34 | -import javax.annotation.Resource; | |
| 35 | -import javax.servlet.http.HttpServletRequest; | |
| 36 | -import javax.sql.DataSource; | |
| 37 | - | |
| 38 | -/** | |
| 39 | - * @author owen 624191343@qq.com | |
| 40 | - * @version 创建时间:2017年11月12日 上午22:57:51 | |
| 41 | - */ | |
| 42 | -@Configuration | |
| 43 | -public class OAuth2ServerConfig { | |
| 44 | - | |
| 45 | - @Resource | |
| 46 | - private DataSource dataSource; | |
| 47 | - @Resource | |
| 48 | - private RedisTemplate<String, Object> redisTemplate; | |
| 49 | - | |
| 50 | - /** | |
| 51 | - * 声明 ClientDetails实现 | |
| 52 | - */ | |
| 53 | - @Bean | |
| 54 | - public RedisClientDetailsService redisClientDetailsService() { | |
| 55 | - RedisClientDetailsService clientDetailsService = new RedisClientDetailsService(dataSource); | |
| 56 | - clientDetailsService.setRedisTemplate(redisTemplate); | |
| 57 | - return clientDetailsService; | |
| 58 | - } | |
| 59 | - | |
| 60 | - | |
| 61 | - @Bean | |
| 62 | - public RandomValueAuthorizationCodeServices authorizationCodeServices() { | |
| 63 | - RedisAuthorizationCodeServices redisAuthorizationCodeServices = new RedisAuthorizationCodeServices(); | |
| 64 | - redisAuthorizationCodeServices.setRedisTemplate(redisTemplate); | |
| 65 | - return redisAuthorizationCodeServices; | |
| 66 | - } | |
| 67 | - | |
| 68 | - /** | |
| 69 | - * @author owen 624191343@qq.com | |
| 70 | - * @version 创建时间:2017年11月12日 上午22:57:51 默认token存储在内存中 | |
| 71 | - * DefaultTokenServices默认处理 | |
| 72 | - */ | |
| 73 | - @Component | |
| 74 | - @Configuration | |
| 75 | - @EnableAuthorizationServer | |
| 76 | - @AutoConfigureAfter(AuthorizationServerEndpointsConfigurer.class) | |
| 77 | - public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter { | |
| 78 | - /** | |
| 79 | - * 注入authenticationManager 来支持 password grant type | |
| 80 | - */ | |
| 81 | - @Autowired | |
| 82 | - private AuthenticationManager authenticationManager; | |
| 83 | - | |
| 84 | - @Autowired | |
| 85 | - private UserDetailsService userDetailsService; | |
| 86 | - | |
| 87 | - @Autowired(required = false) | |
| 88 | - private RedisTemplateTokenStore redisTokenStore; | |
| 89 | - | |
| 90 | - @Autowired(required = false) | |
| 91 | - private JwtTokenStore jwtTokenStore; | |
| 92 | - @Autowired(required = false) | |
| 93 | - private JwtAccessTokenConverter jwtAccessTokenConverter; | |
| 94 | - | |
| 95 | - @Autowired | |
| 96 | - private WebResponseExceptionTranslator webResponseExceptionTranslator; | |
| 97 | - | |
| 98 | - @Autowired | |
| 99 | - private RedisClientDetailsService redisClientDetailsService; | |
| 100 | - | |
| 101 | - @Autowired(required = false) | |
| 102 | - private RandomValueAuthorizationCodeServices authorizationCodeServices; | |
| 103 | - | |
| 104 | - /** | |
| 105 | - * 配置身份认证器,配置认证方式,TokenStore,TokenGranter,OAuth2RequestFactory | |
| 106 | - */ | |
| 107 | - public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception { | |
| 108 | - | |
| 109 | - if (jwtTokenStore != null) { | |
| 110 | - endpoints.tokenStore(jwtTokenStore).authenticationManager(authenticationManager) | |
| 111 | - // 支持 | |
| 112 | - .userDetailsService(userDetailsService); | |
| 113 | - // password | |
| 114 | - // grant | |
| 115 | - // type; | |
| 116 | - } else if (redisTokenStore != null) { | |
| 117 | - endpoints.tokenStore(redisTokenStore).authenticationManager(authenticationManager) | |
| 118 | - // 支持 | |
| 119 | - .userDetailsService(userDetailsService); | |
| 120 | - // password | |
| 121 | - // grant | |
| 122 | - // type; | |
| 123 | - } | |
| 124 | - | |
| 125 | - if (jwtAccessTokenConverter != null) { | |
| 126 | - endpoints.accessTokenConverter(jwtAccessTokenConverter); | |
| 127 | - } | |
| 128 | - | |
| 129 | - endpoints.authorizationCodeServices(authorizationCodeServices); | |
| 130 | - | |
| 131 | - endpoints.exceptionTranslator(webResponseExceptionTranslator); | |
| 132 | - | |
| 133 | - } | |
| 134 | - | |
| 135 | - /** | |
| 136 | - * 配置应用名称 应用id | |
| 137 | - * 配置OAuth2的客户端相关信息 | |
| 138 | - */ | |
| 139 | - @Override | |
| 140 | - public void configure(ClientDetailsServiceConfigurer clients) throws Exception { | |
| 141 | - | |
| 142 | - // if(clientDetailsService!=null){ | |
| 143 | - // clients.withClientDetails(clientDetailsService); | |
| 144 | - // }else{ | |
| 145 | - // clients.inMemory().withClient("neusoft1").secret("neusoft1") | |
| 146 | - // .authorizedGrantTypes("authorization_code", "password", | |
| 147 | - // "refresh_token").scopes("all") | |
| 148 | - // .resourceIds(SERVER_RESOURCE_ID).accessTokenValiditySeconds(1200) | |
| 149 | - // .refreshTokenValiditySeconds(50000) | |
| 150 | - // .and().withClient("neusoft2").secret("neusoft2") | |
| 151 | - // .authorizedGrantTypes("authorization_code", "password", | |
| 152 | - // "refresh_token").scopes("all") | |
| 153 | - // .resourceIds(SERVER_RESOURCE_ID).accessTokenValiditySeconds(1200) | |
| 154 | - // .refreshTokenValiditySeconds(50000) | |
| 155 | - // ; | |
| 156 | - // } | |
| 157 | - clients.withClientDetails(redisClientDetailsService); | |
| 158 | - redisClientDetailsService.loadAllClientToCache(); | |
| 159 | - } | |
| 160 | - | |
| 161 | - /** | |
| 162 | - * 对应于配置AuthorizationServer安全认证的相关信息,创建ClientCredentialsTokenEndpointFilter核心过滤器 | |
| 163 | - */ | |
| 164 | - @Override | |
| 165 | - public void configure(AuthorizationServerSecurityConfigurer security) throws Exception { | |
| 166 | - // url:/oauth/token_key,exposes | |
| 167 | - security.tokenKeyAccess("permitAll()") | |
| 168 | - /// public key for token | |
| 169 | - /// verification if using | |
| 170 | - /// JWT tokens | |
| 171 | - // url:/oauth/check_token | |
| 172 | - .checkTokenAccess("isAuthenticated()") | |
| 173 | - // allow check token | |
| 174 | - .allowFormAuthenticationForClients(); | |
| 175 | - | |
| 176 | - // security.allowFormAuthenticationForClients(); | |
| 177 | - //// security.tokenKeyAccess("permitAll()"); | |
| 178 | - // security.tokenKeyAccess("isAuthenticated()"); | |
| 179 | - } | |
| 180 | - | |
| 181 | - } | |
| 182 | - | |
| 183 | - /** | |
| 184 | - * 资源服务 | |
| 185 | - */ | |
| 186 | - @Configuration | |
| 187 | - @EnableResourceServer | |
| 188 | - @EnableConfigurationProperties(PermitUrlProperties.class) | |
| 189 | - public class ResourceServerConfig extends ResourceServerConfigurerAdapter { | |
| 190 | - | |
| 191 | - @Autowired | |
| 192 | - private PermitUrlProperties permitUrlProperties; | |
| 193 | - | |
| 194 | - public void configure(WebSecurity web) throws Exception { | |
| 195 | - web.ignoring().antMatchers("/health"); | |
| 196 | - web.ignoring().antMatchers("/oauth/user/token"); | |
| 197 | - web.ignoring().antMatchers("/oauth/client/token"); | |
| 198 | - } | |
| 199 | - | |
| 200 | - @Override | |
| 201 | - public void configure(HttpSecurity http) throws Exception { | |
| 202 | - http.requestMatcher( | |
| 203 | - /** | |
| 204 | - * 判断来源请求是否包含oauth2授权信息 | |
| 205 | - */ | |
| 206 | - new RequestMatcher() { | |
| 207 | - private AntPathMatcher antPathMatcher = new AntPathMatcher(); | |
| 208 | - | |
| 209 | - @Override | |
| 210 | - public boolean matches(HttpServletRequest request) { | |
| 211 | - // 请求参数中包含access_token参数 | |
| 212 | - if (request.getParameter(OAuth2AccessToken.ACCESS_TOKEN) != null) { | |
| 213 | - return true; | |
| 214 | - } | |
| 215 | - | |
| 216 | - // 头部的Authorization值以Bearer开头 | |
| 217 | - String auth = request.getHeader("Authorization"); | |
| 218 | - if (auth != null) { | |
| 219 | - if (auth.startsWith(OAuth2AccessToken.BEARER_TYPE)) { | |
| 220 | - return true; | |
| 221 | - } | |
| 222 | - } | |
| 223 | - if (antPathMatcher.match(request.getRequestURI(), "/oauth/userinfo")) { | |
| 224 | - return true; | |
| 225 | - } | |
| 226 | - if (antPathMatcher.match(request.getRequestURI(), "/oauth/remove/token")) { | |
| 227 | - return true; | |
| 228 | - } | |
| 229 | - if (antPathMatcher.match(request.getRequestURI(), "/oauth/get/token")) { | |
| 230 | - return true; | |
| 231 | - } | |
| 232 | - if (antPathMatcher.match(request.getRequestURI(), "/oauth/refresh/token")) { | |
| 233 | - return true; | |
| 234 | - } | |
| 235 | - | |
| 236 | - if (antPathMatcher.match(request.getRequestURI(), "/oauth/token/list")) { | |
| 237 | - return true; | |
| 238 | - } | |
| 239 | - | |
| 240 | - if (antPathMatcher.match("/clients/**", request.getRequestURI())) { | |
| 241 | - return true; | |
| 242 | - } | |
| 243 | - | |
| 244 | - if (antPathMatcher.match("/services/**", request.getRequestURI())) { | |
| 245 | - return true; | |
| 246 | - } | |
| 247 | - if (antPathMatcher.match("/redis/**", request.getRequestURI())) { | |
| 248 | - return true; | |
| 249 | - } | |
| 250 | - return false; | |
| 251 | - } | |
| 252 | - } | |
| 253 | - | |
| 254 | - ).authorizeRequests().antMatchers(permitUrlProperties.getIgnored()).permitAll().anyRequest() | |
| 255 | - .authenticated(); | |
| 256 | - } | |
| 257 | - | |
| 258 | - } | |
| 259 | - | |
| 260 | -} |
cloud/autho/src/main/java/com/sincere/autho/config/SecurityConfig.java
| ... | ... | @@ -1,129 +0,0 @@ |
| 1 | -package com.sincere.autho.config; | |
| 2 | - | |
| 3 | -import com.sincere.autho.handler.OauthLogoutHandler; | |
| 4 | -import com.sincere.common.props.PermitUrlProperties; | |
| 5 | -import org.springframework.beans.factory.annotation.Autowired; | |
| 6 | -import org.springframework.boot.context.properties.EnableConfigurationProperties; | |
| 7 | -import org.springframework.context.annotation.Bean; | |
| 8 | -import org.springframework.context.annotation.Configuration; | |
| 9 | -import org.springframework.security.authentication.AuthenticationManager; | |
| 10 | -import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; | |
| 11 | -import org.springframework.security.config.annotation.web.builders.HttpSecurity; | |
| 12 | -import org.springframework.security.config.annotation.web.builders.WebSecurity; | |
| 13 | -import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; | |
| 14 | -import org.springframework.security.config.http.SessionCreationPolicy; | |
| 15 | -import org.springframework.security.core.userdetails.UserDetailsService; | |
| 16 | -import org.springframework.security.crypto.password.PasswordEncoder; | |
| 17 | -import org.springframework.security.web.AuthenticationEntryPoint; | |
| 18 | -import org.springframework.security.web.authentication.AuthenticationFailureHandler; | |
| 19 | -import org.springframework.security.web.authentication.AuthenticationSuccessHandler; | |
| 20 | -import org.springframework.security.web.authentication.logout.HttpStatusReturningLogoutSuccessHandler; | |
| 21 | - | |
| 22 | -/** | |
| 23 | - * spring security配置 | |
| 24 | - * 在WebSecurityConfigurerAdapter不拦截oauth要开放的资源 | |
| 25 | - */ | |
| 26 | -@Configuration | |
| 27 | -//@EnableWebSecurity | |
| 28 | -//@EnableGlobalMethodSecurity(prePostEnabled = true) | |
| 29 | -@EnableConfigurationProperties(PermitUrlProperties.class) | |
| 30 | -public class SecurityConfig extends WebSecurityConfigurerAdapter { | |
| 31 | - | |
| 32 | - @Autowired | |
| 33 | - private AuthenticationSuccessHandler authenticationSuccessHandler; | |
| 34 | - @Autowired | |
| 35 | - private AuthenticationFailureHandler authenticationFailureHandler; | |
| 36 | - // @Autowired | |
| 37 | - // private LogoutSuccessHandler logoutSuccessHandler; | |
| 38 | - @Autowired(required = false) | |
| 39 | - private AuthenticationEntryPoint authenticationEntryPoint; | |
| 40 | - @Autowired | |
| 41 | - private UserDetailsService userDetailsService; | |
| 42 | - | |
| 43 | - @Autowired | |
| 44 | - private PasswordEncoder passwordEncoder; | |
| 45 | - | |
| 46 | - @Autowired | |
| 47 | - private OauthLogoutHandler oauthLogoutHandler; | |
| 48 | - @Autowired | |
| 49 | - private PermitUrlProperties permitUrlProperties ; | |
| 50 | - | |
| 51 | - @Autowired | |
| 52 | - private ValidateCodeSecurityConfig validateCodeSecurityConfig ; | |
| 53 | - | |
| 54 | - @Override | |
| 55 | - public void configure(WebSecurity web) throws Exception { | |
| 56 | - web.ignoring().antMatchers("/v2/api-docs", "/configuration/ui", "/swagger-resources", "/configuration/security", | |
| 57 | - "/swagger-ui.html", "/webjars/**", "/doc.html", "/login.html"); | |
| 58 | - web.ignoring().antMatchers("/js/**"); | |
| 59 | - web.ignoring().antMatchers("/css/**"); | |
| 60 | - web.ignoring().antMatchers("/health"); | |
| 61 | - // 忽略登录界面 | |
| 62 | - web.ignoring().antMatchers("/login.html"); | |
| 63 | - web.ignoring().antMatchers("/index.html"); | |
| 64 | - web.ignoring().antMatchers("/oauth/user/token"); | |
| 65 | - web.ignoring().antMatchers("/oauth/client/token"); | |
| 66 | - web.ignoring().antMatchers("/validata/code/**"); | |
| 67 | - web.ignoring().antMatchers(permitUrlProperties.getIgnored()); | |
| 68 | - | |
| 69 | - } | |
| 70 | - /** | |
| 71 | - * 认证管理 | |
| 72 | - * | |
| 73 | - * @return 认证管理对象 | |
| 74 | - * @throws Exception | |
| 75 | - * 认证异常信息 | |
| 76 | - */ | |
| 77 | - @Override | |
| 78 | - @Bean | |
| 79 | - public AuthenticationManager authenticationManagerBean() throws Exception { | |
| 80 | - return super.authenticationManagerBean(); | |
| 81 | - } | |
| 82 | - | |
| 83 | - @Override | |
| 84 | - protected void configure(HttpSecurity http) throws Exception { | |
| 85 | - http.csrf().disable(); | |
| 86 | - | |
| 87 | - http.authorizeRequests() | |
| 88 | - .anyRequest().authenticated(); | |
| 89 | - http.formLogin().loginPage("/login.html").loginProcessingUrl("/user/login") | |
| 90 | - .successHandler(authenticationSuccessHandler).failureHandler(authenticationFailureHandler); | |
| 91 | - | |
| 92 | - // 基于密码 等模式可以无session,不支持授权码模式 | |
| 93 | - if (authenticationEntryPoint != null) { | |
| 94 | - http.exceptionHandling().authenticationEntryPoint(authenticationEntryPoint); | |
| 95 | - http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS); | |
| 96 | - | |
| 97 | - } else { | |
| 98 | - // 授权码模式单独处理,需要session的支持,此模式可以支持所有oauth2的认证 | |
| 99 | - http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED); | |
| 100 | - } | |
| 101 | - | |
| 102 | - http.logout().logoutSuccessUrl("/login.html") | |
| 103 | - .logoutSuccessHandler(new HttpStatusReturningLogoutSuccessHandler()) | |
| 104 | - .addLogoutHandler(oauthLogoutHandler).clearAuthentication(true); | |
| 105 | - | |
| 106 | - //增加验证码处理 | |
| 107 | - http.apply(validateCodeSecurityConfig) ; | |
| 108 | - // http.logout().logoutUrl("/logout").logoutSuccessHandler(logoutSuccessHandler); | |
| 109 | - // 解决不允许显示在iframe的问题 | |
| 110 | - http.headers().frameOptions().disable(); | |
| 111 | - http.headers().cacheControl(); | |
| 112 | - | |
| 113 | - } | |
| 114 | - | |
| 115 | - /** | |
| 116 | - * 全局用户信息 | |
| 117 | - * | |
| 118 | - * @param auth | |
| 119 | - * 认证管理 | |
| 120 | - * @throws Exception | |
| 121 | - * 用户认证异常信息 | |
| 122 | - */ | |
| 123 | - @Autowired | |
| 124 | - public void globalUserDetails(AuthenticationManagerBuilder auth) throws Exception { | |
| 125 | - auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder); | |
| 126 | - } | |
| 127 | - | |
| 128 | - | |
| 129 | -} |
cloud/autho/src/main/java/com/sincere/autho/config/ValidateCodeSecurityConfig.java
| ... | ... | @@ -1,29 +0,0 @@ |
| 1 | -/** | |
| 2 | - * | |
| 3 | - */ | |
| 4 | -package com.sincere.autho.config; | |
| 5 | - | |
| 6 | -import org.springframework.security.config.annotation.SecurityConfigurerAdapter; | |
| 7 | -import org.springframework.security.config.annotation.web.builders.HttpSecurity; | |
| 8 | -import org.springframework.security.web.DefaultSecurityFilterChain; | |
| 9 | -import org.springframework.security.web.authentication.preauth.AbstractPreAuthenticatedProcessingFilter; | |
| 10 | -import org.springframework.stereotype.Component; | |
| 11 | - | |
| 12 | -import javax.annotation.Resource; | |
| 13 | -import javax.servlet.Filter; | |
| 14 | - | |
| 15 | -/** | |
| 16 | - * 校验码相关安全配置 | |
| 17 | - * | |
| 18 | - * @author zlt | |
| 19 | - */ | |
| 20 | -@Component("validateCodeSecurityConfig") | |
| 21 | -public class ValidateCodeSecurityConfig extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity> { | |
| 22 | - @Resource | |
| 23 | - private Filter validateCodeFilter; | |
| 24 | - | |
| 25 | - @Override | |
| 26 | - public void configure(HttpSecurity http) { | |
| 27 | - http.addFilterBefore(validateCodeFilter, AbstractPreAuthenticatedProcessingFilter.class); | |
| 28 | - } | |
| 29 | -} |
cloud/autho/src/main/java/com/sincere/autho/control/LoginController.java
0 → 100644
| ... | ... | @@ -0,0 +1,35 @@ |
| 1 | +package com.sincere.autho.control; | |
| 2 | + | |
| 3 | +import com.sincere.autho.dto.BaseDto; | |
| 4 | +import com.sincere.autho.dto.req.LoginReqDto; | |
| 5 | +import com.sincere.autho.service.LoginService; | |
| 6 | +import com.sincere.common.util.TokenUtils; | |
| 7 | +import io.swagger.annotations.Api; | |
| 8 | +import org.apache.commons.lang3.StringUtils; | |
| 9 | +import org.springframework.beans.factory.annotation.Autowired; | |
| 10 | +import org.springframework.web.bind.annotation.RequestBody; | |
| 11 | +import org.springframework.web.bind.annotation.RequestMapping; | |
| 12 | +import org.springframework.web.bind.annotation.RequestMethod; | |
| 13 | +import org.springframework.web.bind.annotation.RestController; | |
| 14 | + | |
| 15 | +@RestController | |
| 16 | +public class LoginController { | |
| 17 | + | |
| 18 | + @Autowired | |
| 19 | + LoginService loginService ; | |
| 20 | + | |
| 21 | + | |
| 22 | + @RequestMapping(value = "/login" , method = RequestMethod.POST) | |
| 23 | + public BaseDto<String> login(@RequestBody LoginReqDto loginReqDto){ | |
| 24 | + BaseDto<String> result = new BaseDto<>() ; | |
| 25 | + String userId = loginService.login(loginReqDto); | |
| 26 | + if(StringUtils.isNotBlank(userId)){ | |
| 27 | + result.setMessage("登录成功"); | |
| 28 | + result.setData(TokenUtils.buildToken(userId)); | |
| 29 | + }else { | |
| 30 | + result.setStatus(false); | |
| 31 | + result.setMessage("账号密码错误"); | |
| 32 | + } | |
| 33 | + return result ; | |
| 34 | + } | |
| 35 | +} | ... | ... |
cloud/autho/src/main/java/com/sincere/autho/control/OAuth2Controller.java
| ... | ... | @@ -1,482 +0,0 @@ |
| 1 | -package com.sincere.autho.control; | |
| 2 | - | |
| 3 | -import com.fasterxml.jackson.core.JsonProcessingException; | |
| 4 | -import com.fasterxml.jackson.databind.ObjectMapper; | |
| 5 | -import com.sincere.autho.annotation.log.LogAnnotation; | |
| 6 | -import com.sincere.autho.service.RedisClientDetailsService; | |
| 7 | -import com.sincere.autho.utils.SpringUtil; | |
| 8 | -import com.sincere.common.commons.PageResult; | |
| 9 | -import com.sincere.common.model.system.LoginAppUser; | |
| 10 | -import com.sincere.common.model.system.SysPermission; | |
| 11 | -import io.swagger.annotations.Api; | |
| 12 | -import io.swagger.annotations.ApiOperation; | |
| 13 | -import io.swagger.annotations.ApiParam; | |
| 14 | -import org.apache.commons.collections.MapUtils; | |
| 15 | -import org.slf4j.Logger; | |
| 16 | -import org.slf4j.LoggerFactory; | |
| 17 | -import org.springframework.beans.factory.annotation.Autowired; | |
| 18 | -import org.springframework.dao.DataAccessException; | |
| 19 | -import org.springframework.data.redis.connection.RedisConnection; | |
| 20 | -import org.springframework.data.redis.core.Cursor; | |
| 21 | -import org.springframework.data.redis.core.RedisCallback; | |
| 22 | -import org.springframework.data.redis.core.RedisTemplate; | |
| 23 | -import org.springframework.data.redis.core.ScanOptions; | |
| 24 | -import org.springframework.http.HttpStatus; | |
| 25 | -import org.springframework.security.authentication.AuthenticationManager; | |
| 26 | -import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; | |
| 27 | -import org.springframework.security.core.Authentication; | |
| 28 | -import org.springframework.security.core.context.SecurityContextHolder; | |
| 29 | -import org.springframework.security.crypto.password.PasswordEncoder; | |
| 30 | -import org.springframework.security.oauth2.common.OAuth2AccessToken; | |
| 31 | -import org.springframework.security.oauth2.common.exceptions.UnapprovedClientAuthenticationException; | |
| 32 | -import org.springframework.security.oauth2.provider.*; | |
| 33 | -import org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationDetails; | |
| 34 | -import org.springframework.security.oauth2.provider.client.ClientCredentialsTokenGranter; | |
| 35 | -import org.springframework.security.oauth2.provider.refresh.RefreshTokenGranter; | |
| 36 | -import org.springframework.security.oauth2.provider.request.DefaultOAuth2RequestFactory; | |
| 37 | -import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices; | |
| 38 | -import org.springframework.security.oauth2.provider.token.TokenStore; | |
| 39 | -import org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken; | |
| 40 | -import org.springframework.web.bind.annotation.PostMapping; | |
| 41 | -import org.springframework.web.bind.annotation.RequestMapping; | |
| 42 | -import org.springframework.web.bind.annotation.RequestParam; | |
| 43 | -import org.springframework.web.bind.annotation.RestController; | |
| 44 | - | |
| 45 | -import javax.annotation.Resource; | |
| 46 | -import javax.servlet.http.HttpServletRequest; | |
| 47 | -import javax.servlet.http.HttpServletResponse; | |
| 48 | -import java.io.IOException; | |
| 49 | -import java.util.*; | |
| 50 | - | |
| 51 | -/** | |
| 52 | - * @author 作者 owen E-mail: 624191343@qq.com | |
| 53 | - * @version 创建时间:2018年4月28日 下午2:18:54 类说明 | |
| 54 | - */ | |
| 55 | - | |
| 56 | -@Api(tags = "OAuth2相关操作") | |
| 57 | -@RestController | |
| 58 | -public class OAuth2Controller { | |
| 59 | - | |
| 60 | - private static final Logger logger = LoggerFactory.getLogger(OAuth2Controller.class); | |
| 61 | - @Resource | |
| 62 | - private ObjectMapper objectMapper; // springmvc启动时自动装配json处理类 | |
| 63 | - @Autowired | |
| 64 | - private PasswordEncoder passwordEncoder; | |
| 65 | - | |
| 66 | - @Autowired | |
| 67 | - private TokenStore tokenStore; | |
| 68 | - | |
| 69 | - @Autowired | |
| 70 | - private RedisTemplate<String, Object> redisTemplate; | |
| 71 | - | |
| 72 | - @ApiOperation(value = "用户名密码获取token") | |
| 73 | - @PostMapping("/oauth/user/token") | |
| 74 | - public void getUserTokenInfo( | |
| 75 | - @ApiParam(required = true, name = "username", value = "账号") @RequestParam(value = "username") String username, | |
| 76 | - @ApiParam(required = true, name = "password", value = "密码") @RequestParam(value = "password") String password, | |
| 77 | - HttpServletRequest request, HttpServletResponse response) { | |
| 78 | - String clientId = request.getHeader("client_id"); | |
| 79 | - String clientSecret = request.getHeader("client_secret"); | |
| 80 | - | |
| 81 | - try { | |
| 82 | - | |
| 83 | - if (clientId == null || "".equals(clientId)) { | |
| 84 | - throw new UnapprovedClientAuthenticationException("请求头中无client_id信息"); | |
| 85 | - } | |
| 86 | - | |
| 87 | - if (clientSecret == null || "".equals(clientSecret)) { | |
| 88 | - throw new UnapprovedClientAuthenticationException("请求头中无client_secret信息"); | |
| 89 | - } | |
| 90 | - | |
| 91 | - RedisClientDetailsService clientDetailsService = SpringUtil.getBean(RedisClientDetailsService.class); | |
| 92 | - | |
| 93 | - ClientDetails clientDetails = clientDetailsService.loadClientByClientId(clientId); | |
| 94 | - | |
| 95 | - if (clientDetails == null) { | |
| 96 | - throw new UnapprovedClientAuthenticationException("clientId对应的信息不存在"); | |
| 97 | - } else if (!passwordEncoder.matches(clientSecret, clientDetails.getClientSecret())) { | |
| 98 | - throw new UnapprovedClientAuthenticationException("clientSecret不匹配"); | |
| 99 | - } | |
| 100 | - | |
| 101 | - TokenRequest tokenRequest = new TokenRequest(MapUtils.EMPTY_MAP, clientId, clientDetails.getScope(), | |
| 102 | - "customer"); | |
| 103 | - | |
| 104 | - OAuth2Request oAuth2Request = tokenRequest.createOAuth2Request(clientDetails); | |
| 105 | - | |
| 106 | - UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(username, password); | |
| 107 | - | |
| 108 | - AuthenticationManager authenticationManager = SpringUtil.getBean(AuthenticationManager.class); | |
| 109 | - | |
| 110 | - Authentication authentication = authenticationManager.authenticate(token); | |
| 111 | - SecurityContextHolder.getContext().setAuthentication(authentication); | |
| 112 | - | |
| 113 | - OAuth2Authentication oAuth2Authentication = new OAuth2Authentication(oAuth2Request, authentication); | |
| 114 | - | |
| 115 | - AuthorizationServerTokenServices authorizationServerTokenServices = SpringUtil | |
| 116 | - .getBean("defaultAuthorizationServerTokenServices", AuthorizationServerTokenServices.class); | |
| 117 | - | |
| 118 | - OAuth2AccessToken oAuth2AccessToken = authorizationServerTokenServices | |
| 119 | - .createAccessToken(oAuth2Authentication); | |
| 120 | - | |
| 121 | - oAuth2Authentication.setAuthenticated(true); | |
| 122 | - | |
| 123 | - response.setContentType("application/json;charset=UTF-8"); | |
| 124 | - response.getWriter().write(objectMapper.writeValueAsString(oAuth2AccessToken)); | |
| 125 | - response.getWriter().flush(); | |
| 126 | - response.getWriter().close(); | |
| 127 | - | |
| 128 | - } catch (Exception e) { | |
| 129 | - | |
| 130 | - response.setStatus(HttpStatus.UNAUTHORIZED.value()); | |
| 131 | - | |
| 132 | - response.setContentType("application/json;charset=UTF-8"); | |
| 133 | - | |
| 134 | - Map<String, String> rsp = new HashMap<>(); | |
| 135 | - rsp.put("resp_code", HttpStatus.UNAUTHORIZED.value() + ""); | |
| 136 | - rsp.put("rsp_msg", e.getMessage()); | |
| 137 | - | |
| 138 | - try { | |
| 139 | - response.getWriter().write(objectMapper.writeValueAsString(rsp)); | |
| 140 | - response.getWriter().flush(); | |
| 141 | - response.getWriter().close(); | |
| 142 | - } catch (JsonProcessingException e1) { | |
| 143 | - // TODO Auto-generated catch block | |
| 144 | - e1.printStackTrace(); | |
| 145 | - } catch (IOException e1) { | |
| 146 | - // TODO Auto-generated catch block | |
| 147 | - e1.printStackTrace(); | |
| 148 | - } | |
| 149 | - | |
| 150 | - } | |
| 151 | - } | |
| 152 | - | |
| 153 | - | |
| 154 | - @ApiOperation(value = "clientId获取token") | |
| 155 | - @PostMapping("/oauth/client/token") | |
| 156 | - @LogAnnotation(module = "autho", recordRequestParam = false) | |
| 157 | - public void getClientTokenInfo(HttpServletRequest request, HttpServletResponse response) { | |
| 158 | - | |
| 159 | - String clientId = request.getHeader("client_id"); | |
| 160 | - String clientSecret = request.getHeader("client_secret"); | |
| 161 | - try { | |
| 162 | - | |
| 163 | - if (clientId == null || "".equals(clientId)) { | |
| 164 | - throw new UnapprovedClientAuthenticationException("请求参数中无clientId信息"); | |
| 165 | - } | |
| 166 | - | |
| 167 | - if (clientSecret == null || "".equals(clientSecret)) { | |
| 168 | - throw new UnapprovedClientAuthenticationException("请求参数中无clientSecret信息"); | |
| 169 | - } | |
| 170 | - | |
| 171 | - RedisClientDetailsService clientDetailsService = SpringUtil.getBean(RedisClientDetailsService.class); | |
| 172 | - | |
| 173 | - ClientDetails clientDetails = clientDetailsService.loadClientByClientId(clientId); | |
| 174 | - | |
| 175 | - if (clientDetails == null) { | |
| 176 | - throw new UnapprovedClientAuthenticationException("clientId对应的信息不存在"); | |
| 177 | - } else if (!passwordEncoder.matches(clientSecret, clientDetails.getClientSecret())) { | |
| 178 | - throw new UnapprovedClientAuthenticationException("clientSecret不匹配"); | |
| 179 | - } | |
| 180 | - | |
| 181 | - Map<String, String> map = new HashMap<>(); | |
| 182 | - map.put("client_secret", clientSecret); | |
| 183 | - map.put("client_id", clientId); | |
| 184 | - map.put("grant_type", "client_credentials"); | |
| 185 | - TokenRequest tokenRequest = new TokenRequest(map, clientId, clientDetails.getScope(), "client_credentials"); | |
| 186 | - | |
| 187 | - OAuth2Request oAuth2Request = tokenRequest.createOAuth2Request(clientDetails); | |
| 188 | - | |
| 189 | - AuthorizationServerTokenServices authorizationServerTokenServices = SpringUtil | |
| 190 | - .getBean("defaultAuthorizationServerTokenServices", AuthorizationServerTokenServices.class); | |
| 191 | - OAuth2RequestFactory requestFactory = new DefaultOAuth2RequestFactory(clientDetailsService); | |
| 192 | - ClientCredentialsTokenGranter clientCredentialsTokenGranter = new ClientCredentialsTokenGranter( | |
| 193 | - authorizationServerTokenServices, clientDetailsService, requestFactory); | |
| 194 | - | |
| 195 | - clientCredentialsTokenGranter.setAllowRefresh(true); | |
| 196 | - OAuth2AccessToken oAuth2AccessToken = clientCredentialsTokenGranter.grant("client_credentials", | |
| 197 | - tokenRequest); | |
| 198 | - | |
| 199 | - response.setContentType("application/json;charset=UTF-8"); | |
| 200 | - response.getWriter().write(objectMapper.writeValueAsString(oAuth2AccessToken)); | |
| 201 | - response.getWriter().flush(); | |
| 202 | - response.getWriter().close(); | |
| 203 | - | |
| 204 | - } catch (Exception e) { | |
| 205 | - | |
| 206 | - response.setStatus(HttpStatus.UNAUTHORIZED.value()); | |
| 207 | - response.setContentType("application/json;charset=UTF-8"); | |
| 208 | - Map<String, String> rsp = new HashMap<>(); | |
| 209 | - rsp.put("resp_code", HttpStatus.UNAUTHORIZED.value() + ""); | |
| 210 | - rsp.put("rsp_msg", e.getMessage()); | |
| 211 | - | |
| 212 | - try { | |
| 213 | - response.getWriter().write(objectMapper.writeValueAsString(rsp)); | |
| 214 | - response.getWriter().flush(); | |
| 215 | - response.getWriter().close(); | |
| 216 | - } catch (JsonProcessingException e1) { | |
| 217 | - // TODO Auto-generated catch block | |
| 218 | - e1.printStackTrace(); | |
| 219 | - } catch (IOException e1) { | |
| 220 | - // TODO Auto-generated catch block | |
| 221 | - e1.printStackTrace(); | |
| 222 | - } | |
| 223 | - | |
| 224 | - } | |
| 225 | - } | |
| 226 | - | |
| 227 | - @ApiOperation(value = "access_token刷新token") | |
| 228 | - @PostMapping(value = "/oauth/refresh/token", params = "access_token") | |
| 229 | - public void refreshTokenInfo(String access_token, HttpServletRequest request, HttpServletResponse response) { | |
| 230 | - | |
| 231 | - // 拿到当前用户信息 | |
| 232 | - try { | |
| 233 | - Authentication user = SecurityContextHolder.getContext().getAuthentication(); | |
| 234 | - | |
| 235 | - if (user != null) { | |
| 236 | - if (user instanceof OAuth2Authentication) { | |
| 237 | - Authentication athentication = (Authentication) user; | |
| 238 | - OAuth2AuthenticationDetails details = (OAuth2AuthenticationDetails) athentication.getDetails(); | |
| 239 | - } | |
| 240 | - | |
| 241 | - } | |
| 242 | - OAuth2AccessToken accessToken = tokenStore.readAccessToken(access_token); | |
| 243 | - OAuth2Authentication auth = (OAuth2Authentication) user; | |
| 244 | - RedisClientDetailsService clientDetailsService = SpringUtil.getBean(RedisClientDetailsService.class); | |
| 245 | - | |
| 246 | - ClientDetails clientDetails = clientDetailsService | |
| 247 | - .loadClientByClientId(auth.getOAuth2Request().getClientId()); | |
| 248 | - | |
| 249 | - AuthorizationServerTokenServices authorizationServerTokenServices = SpringUtil | |
| 250 | - .getBean("defaultAuthorizationServerTokenServices", AuthorizationServerTokenServices.class); | |
| 251 | - OAuth2RequestFactory requestFactory = new DefaultOAuth2RequestFactory(clientDetailsService); | |
| 252 | - | |
| 253 | - RefreshTokenGranter refreshTokenGranter = new RefreshTokenGranter(authorizationServerTokenServices, | |
| 254 | - clientDetailsService, requestFactory); | |
| 255 | - | |
| 256 | - Map<String, String> map = new HashMap<>(); | |
| 257 | - map.put("grant_type", "refresh_token"); | |
| 258 | - map.put("refresh_token", accessToken.getRefreshToken().getValue()); | |
| 259 | - TokenRequest tokenRequest = new TokenRequest(map, auth.getOAuth2Request().getClientId(), | |
| 260 | - auth.getOAuth2Request().getScope(), "refresh_token"); | |
| 261 | - | |
| 262 | - OAuth2AccessToken oAuth2AccessToken = refreshTokenGranter.grant("refresh_token", tokenRequest); | |
| 263 | - | |
| 264 | - tokenStore.removeAccessToken(accessToken); | |
| 265 | - | |
| 266 | - response.setContentType("application/json;charset=UTF-8"); | |
| 267 | - response.getWriter().write(objectMapper.writeValueAsString(oAuth2AccessToken)); | |
| 268 | - response.getWriter().flush(); | |
| 269 | - response.getWriter().close(); | |
| 270 | - } catch (Exception e) { | |
| 271 | - response.setStatus(HttpStatus.UNAUTHORIZED.value()); | |
| 272 | - response.setContentType("application/json;charset=UTF-8"); | |
| 273 | - Map<String, String> rsp = new HashMap<>(); | |
| 274 | - rsp.put("resp_code", HttpStatus.UNAUTHORIZED.value() + ""); | |
| 275 | - rsp.put("rsp_msg", e.getMessage()); | |
| 276 | - | |
| 277 | - try { | |
| 278 | - response.getWriter().write(objectMapper.writeValueAsString(rsp)); | |
| 279 | - response.getWriter().flush(); | |
| 280 | - response.getWriter().close(); | |
| 281 | - } catch (JsonProcessingException e1) { | |
| 282 | - // TODO Auto-generated catch block | |
| 283 | - e1.printStackTrace(); | |
| 284 | - } catch (IOException e1) { | |
| 285 | - // TODO Auto-generated catch block | |
| 286 | - e1.printStackTrace(); | |
| 287 | - } | |
| 288 | - } | |
| 289 | - | |
| 290 | - } | |
| 291 | - | |
| 292 | - /** | |
| 293 | - * 移除access_token和refresh_token | |
| 294 | - * | |
| 295 | - * @param access_token | |
| 296 | - */ | |
| 297 | - @ApiOperation(value = "移除token") | |
| 298 | - @PostMapping(value = "/oauth/remove/token", params = "access_token") | |
| 299 | - public void removeToken(String access_token) { | |
| 300 | - | |
| 301 | - // 拿到当前用户信息 | |
| 302 | - Authentication user = SecurityContextHolder.getContext().getAuthentication(); | |
| 303 | - | |
| 304 | - if (user != null) { | |
| 305 | - if (user instanceof OAuth2Authentication) { | |
| 306 | - Authentication athentication = (Authentication) user; | |
| 307 | - OAuth2AuthenticationDetails details = (OAuth2AuthenticationDetails) athentication.getDetails(); | |
| 308 | - } | |
| 309 | - | |
| 310 | - } | |
| 311 | - OAuth2AccessToken accessToken = tokenStore.readAccessToken(access_token); | |
| 312 | - if (accessToken != null) { | |
| 313 | - // 移除access_token | |
| 314 | - tokenStore.removeAccessToken(accessToken); | |
| 315 | - | |
| 316 | - // 移除refresh_token | |
| 317 | - if (accessToken.getRefreshToken() != null) { | |
| 318 | - tokenStore.removeRefreshToken(accessToken.getRefreshToken()); | |
| 319 | - } | |
| 320 | - | |
| 321 | - } | |
| 322 | - } | |
| 323 | - | |
| 324 | - @ApiOperation(value = "获取token信息") | |
| 325 | - @PostMapping(value = "/oauth/get/token", params = "access_token") | |
| 326 | - public OAuth2AccessToken getTokenInfo(String access_token) { | |
| 327 | - | |
| 328 | - // 拿到当前用户信息 | |
| 329 | - Authentication user = SecurityContextHolder.getContext().getAuthentication(); | |
| 330 | - | |
| 331 | - if (user != null) { | |
| 332 | - if (user instanceof OAuth2Authentication) { | |
| 333 | - Authentication athentication = (Authentication) user; | |
| 334 | - OAuth2AuthenticationDetails details = (OAuth2AuthenticationDetails) athentication.getDetails(); | |
| 335 | - } | |
| 336 | - | |
| 337 | - } | |
| 338 | - OAuth2AccessToken accessToken = tokenStore.readAccessToken(access_token); | |
| 339 | - | |
| 340 | - return accessToken; | |
| 341 | - | |
| 342 | - } | |
| 343 | - | |
| 344 | - /** | |
| 345 | - * 当前登陆用户信息 | |
| 346 | - * security获取当前登录用户的方法是SecurityContextHolder.getContext().getAuthentication() | |
| 347 | - * 这里的实现类是org.springframework.security.oauth2.provider.OAuth2Authentication | |
| 348 | - * | |
| 349 | - * @return | |
| 350 | - */ | |
| 351 | - @ApiOperation(value = "当前登陆用户信息") | |
| 352 | - @RequestMapping(value = { "/oauth/userinfo" }, produces = "application/json") // 获取用户信息。/auth/user | |
| 353 | - public Map<String, Object> getCurrentUserDetail() { | |
| 354 | - Map<String, Object> userInfo = new HashMap<>(); | |
| 355 | - userInfo.put("user", SecurityContextHolder.getContext().getAuthentication().getPrincipal()); | |
| 356 | - logger.debug("认证详细信息:" + SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString()); | |
| 357 | - | |
| 358 | - List<SysPermission> permissions = new ArrayList<>(); | |
| 359 | - | |
| 360 | - new ArrayList(SecurityContextHolder.getContext().getAuthentication().getAuthorities()).forEach(o -> { | |
| 361 | - SysPermission sysPermission = new SysPermission(); | |
| 362 | - sysPermission.setPermission(o.toString()); | |
| 363 | - permissions.add(sysPermission); | |
| 364 | - }); | |
| 365 | - // userInfo.put("authorities", | |
| 366 | - // AuthorityUtils.authorityListToSet(SecurityContextHolder.getContext().getAuthentication().getAuthorities()) | |
| 367 | - // ); | |
| 368 | - userInfo.put("permissions", permissions); | |
| 369 | - | |
| 370 | - userInfo.put("resp_code", "200"); | |
| 371 | - | |
| 372 | - logger.info("返回信息:{}", userInfo); | |
| 373 | - | |
| 374 | - return userInfo; | |
| 375 | - } | |
| 376 | - | |
| 377 | - @ApiOperation(value = "token列表") | |
| 378 | - @PostMapping("/oauth/token/list") | |
| 379 | - public PageResult<HashMap<String, String>> getUserTokenInfo(@RequestParam Map<String, Object> params) | |
| 380 | - throws Exception { | |
| 381 | - List<HashMap<String, String>> list = new ArrayList<>(); | |
| 382 | - | |
| 383 | - Set<String> keys = redisTemplate.keys("access:" + "*") ; | |
| 384 | -// Object key1 = keys.toArray()[0]; | |
| 385 | -// Object token1 = redisTemplate.opsForValue().get(key1); | |
| 386 | - //根据分页参数获取对应数据 | |
| 387 | - // List<String> pages = findKeysForPage("access:" + "*", MapUtils.getInteger(params, "page"),MapUtils.getInteger(params, "limit")); | |
| 388 | - | |
| 389 | - for (Object key: keys.toArray()) { | |
| 390 | -// String key = page; | |
| 391 | -// String accessToken = StringUtils.substringAfter(key, "access:"); | |
| 392 | -// OAuth2AccessToken token = tokenStore.readAccessToken(accessToken); | |
| 393 | - OAuth2AccessToken token = (OAuth2AccessToken)redisTemplate.opsForValue().get(key); | |
| 394 | - HashMap<String, String> map = new HashMap<String, String>(); | |
| 395 | - | |
| 396 | - try { | |
| 397 | - map.put("token_type", token.getTokenType()); | |
| 398 | - map.put("token_value", token.getValue()); | |
| 399 | - map.put("expires_in", token.getExpiresIn()+""); | |
| 400 | - } catch (Exception e) { | |
| 401 | - | |
| 402 | - } | |
| 403 | - | |
| 404 | - | |
| 405 | - OAuth2Authentication oAuth2Auth = tokenStore.readAuthentication(token); | |
| 406 | - Authentication authentication = oAuth2Auth.getUserAuthentication(); | |
| 407 | - | |
| 408 | - map.put("client_id", oAuth2Auth.getOAuth2Request().getClientId()); | |
| 409 | - map.put("grant_type", oAuth2Auth.getOAuth2Request().getGrantType()); | |
| 410 | - | |
| 411 | - if (authentication instanceof UsernamePasswordAuthenticationToken) { | |
| 412 | - UsernamePasswordAuthenticationToken authenticationToken = (UsernamePasswordAuthenticationToken) authentication; | |
| 413 | - | |
| 414 | - if(authenticationToken.getPrincipal() instanceof LoginAppUser ){ | |
| 415 | - LoginAppUser user = (LoginAppUser) authenticationToken.getPrincipal(); | |
| 416 | - map.put("user_id", user.getId()+""); | |
| 417 | - map.put("user_name", user.getUsername()+""); | |
| 418 | - map.put("user_head_imgurl", user.getHeadImgUrl()+""); | |
| 419 | - } | |
| 420 | - | |
| 421 | - | |
| 422 | - }else if (authentication instanceof PreAuthenticatedAuthenticationToken){ | |
| 423 | - //刷新token方式 | |
| 424 | - PreAuthenticatedAuthenticationToken authenticationToken = (PreAuthenticatedAuthenticationToken) authentication; | |
| 425 | - if(authenticationToken.getPrincipal() instanceof LoginAppUser ){ | |
| 426 | - LoginAppUser user = (LoginAppUser) authenticationToken.getPrincipal(); | |
| 427 | - map.put("user_id", user.getId()+""); | |
| 428 | - map.put("user_name", user.getUsername()+""); | |
| 429 | - map.put("user_head_imgurl", user.getHeadImgUrl()+""); | |
| 430 | - } | |
| 431 | - | |
| 432 | - } | |
| 433 | - list.add(map); | |
| 434 | - | |
| 435 | - } | |
| 436 | - | |
| 437 | - | |
| 438 | - | |
| 439 | - return PageResult.<HashMap<String, String>>builder().data(list).code(0).count((long) keys.size()).build(); | |
| 440 | - | |
| 441 | - } | |
| 442 | - | |
| 443 | - public List<String> findKeysForPage(String patternKey, int pageNum, int pageSize) { | |
| 444 | - | |
| 445 | - Set<String> execute = redisTemplate.execute(new RedisCallback<Set<String>>() { | |
| 446 | - | |
| 447 | - @Override | |
| 448 | - public Set<String> doInRedis(RedisConnection connection) throws DataAccessException { | |
| 449 | - | |
| 450 | - Set<String> binaryKeys = new HashSet<>(); | |
| 451 | - | |
| 452 | - Cursor<byte[]> cursor = connection | |
| 453 | - .scan(new ScanOptions.ScanOptionsBuilder().match(patternKey).count(1000).build()); | |
| 454 | - int tmpIndex = 0; | |
| 455 | - int startIndex = (pageNum - 1) * pageSize; | |
| 456 | - int end = pageNum * pageSize; | |
| 457 | - while (cursor.hasNext()) { | |
| 458 | - if (tmpIndex >= startIndex && tmpIndex < end) { | |
| 459 | - binaryKeys.add(new String(cursor.next())); | |
| 460 | - tmpIndex++; | |
| 461 | - continue; | |
| 462 | - } | |
| 463 | - | |
| 464 | - // 获取到满足条件的数据后,就可以退出了 | |
| 465 | - if (tmpIndex >= end) { | |
| 466 | - break; | |
| 467 | - } | |
| 468 | - | |
| 469 | - tmpIndex++; | |
| 470 | - cursor.next(); | |
| 471 | - } | |
| 472 | - connection.close(); | |
| 473 | - return binaryKeys; | |
| 474 | - } | |
| 475 | - }); | |
| 476 | - | |
| 477 | - List<String> result = new ArrayList<String>(pageSize); | |
| 478 | - result.addAll(execute); | |
| 479 | - return result; | |
| 480 | - } | |
| 481 | - | |
| 482 | -} |
cloud/autho/src/main/java/com/sincere/autho/control/UserController.java
| ... | ... | @@ -1,16 +0,0 @@ |
| 1 | -package com.sincere.autho.control; | |
| 2 | - | |
| 3 | -import org.springframework.web.bind.annotation.GetMapping; | |
| 4 | -import org.springframework.web.bind.annotation.RestController; | |
| 5 | - | |
| 6 | -import java.security.Principal; | |
| 7 | - | |
| 8 | -@RestController | |
| 9 | -public class UserController { | |
| 10 | - | |
| 11 | - @GetMapping("/user") | |
| 12 | - public Principal user(Principal user){ | |
| 13 | - return user; | |
| 14 | - } | |
| 15 | - | |
| 16 | -} |
cloud/autho/src/main/java/com/sincere/autho/dto/BaseDto.java
0 → 100644
| ... | ... | @@ -0,0 +1,36 @@ |
| 1 | +package com.sincere.autho.dto; | |
| 2 | + | |
| 3 | +public class BaseDto<T> { | |
| 4 | + | |
| 5 | + private String message ; | |
| 6 | + private boolean status ; | |
| 7 | + private T data ; | |
| 8 | + | |
| 9 | + public String getMessage() { | |
| 10 | + return message; | |
| 11 | + } | |
| 12 | + | |
| 13 | + public void setMessage(String message) { | |
| 14 | + this.message = message; | |
| 15 | + } | |
| 16 | + | |
| 17 | + public boolean isStatus() { | |
| 18 | + return status; | |
| 19 | + } | |
| 20 | + | |
| 21 | + public void setStatus(boolean status) { | |
| 22 | + this.status = status; | |
| 23 | + } | |
| 24 | + | |
| 25 | + public T getData() { | |
| 26 | + return data; | |
| 27 | + } | |
| 28 | + | |
| 29 | + public void setData(T data) { | |
| 30 | + this.data = data; | |
| 31 | + } | |
| 32 | + | |
| 33 | + public BaseDto() { | |
| 34 | + this.status = true ; | |
| 35 | + } | |
| 36 | +} | ... | ... |
cloud/autho/src/main/java/com/sincere/autho/dto/req/LoginReqDto.java
0 → 100644
| ... | ... | @@ -0,0 +1,32 @@ |
| 1 | +package com.sincere.autho.dto.req; | |
| 2 | + | |
| 3 | +public class LoginReqDto { | |
| 4 | + | |
| 5 | + private String account ; | |
| 6 | + private String password ; | |
| 7 | + private int userType ; // 2:学生;3:家长;其他都是老师 | |
| 8 | + | |
| 9 | + public String getAccount() { | |
| 10 | + return account; | |
| 11 | + } | |
| 12 | + | |
| 13 | + public void setAccount(String account) { | |
| 14 | + this.account = account; | |
| 15 | + } | |
| 16 | + | |
| 17 | + public String getPassword() { | |
| 18 | + return password; | |
| 19 | + } | |
| 20 | + | |
| 21 | + public void setPassword(String password) { | |
| 22 | + this.password = password; | |
| 23 | + } | |
| 24 | + | |
| 25 | + public int getUserType() { | |
| 26 | + return userType; | |
| 27 | + } | |
| 28 | + | |
| 29 | + public void setUserType(int userType) { | |
| 30 | + this.userType = userType; | |
| 31 | + } | |
| 32 | +} | ... | ... |
cloud/autho/src/main/java/com/sincere/autho/handler/ExceptionHandlerAdvice.java
| ... | ... | @@ -1,63 +0,0 @@ |
| 1 | -package com.sincere.autho.handler; | |
| 2 | - | |
| 3 | -import io.grpc.StatusRuntimeException; | |
| 4 | -import org.springframework.http.HttpStatus; | |
| 5 | -import org.springframework.security.access.AccessDeniedException; | |
| 6 | -import org.springframework.web.bind.annotation.ExceptionHandler; | |
| 7 | -import org.springframework.web.bind.annotation.ResponseStatus; | |
| 8 | -import org.springframework.web.bind.annotation.RestControllerAdvice; | |
| 9 | - | |
| 10 | -import java.util.HashMap; | |
| 11 | -import java.util.Map; | |
| 12 | - | |
| 13 | - | |
| 14 | -/** | |
| 15 | - * @author 作者 owen E-mail: 624191343@qq.com | |
| 16 | - * @version 创建时间:2017年11月12日 上午22:57:51 | |
| 17 | - * 异常通用处理 | |
| 18 | -*/ | |
| 19 | -@RestControllerAdvice | |
| 20 | -public class ExceptionHandlerAdvice { | |
| 21 | - | |
| 22 | - /** | |
| 23 | - * IllegalArgumentException异常处理返回json | |
| 24 | - * 状态码:400 | |
| 25 | - * @param exception | |
| 26 | - * @return | |
| 27 | - */ | |
| 28 | - @ExceptionHandler({ IllegalArgumentException.class }) | |
| 29 | - @ResponseStatus(HttpStatus.BAD_REQUEST) | |
| 30 | - public Map<String, Object> badRequestException(IllegalArgumentException exception) { | |
| 31 | - Map<String, Object> data = new HashMap<>(); | |
| 32 | - data.put("resp_code", HttpStatus.BAD_REQUEST.value()); | |
| 33 | - data.put("resp_msg", exception.getMessage()); | |
| 34 | - | |
| 35 | - return data; | |
| 36 | - } | |
| 37 | - /** | |
| 38 | - * AccessDeniedException异常处理返回json | |
| 39 | - * 状态码:403 | |
| 40 | - * @param exception | |
| 41 | - * @return | |
| 42 | - */ | |
| 43 | - @ExceptionHandler({ AccessDeniedException.class }) | |
| 44 | - @ResponseStatus(HttpStatus.FORBIDDEN) | |
| 45 | - public Map<String, Object> badMethodExpressException(AccessDeniedException exception) { | |
| 46 | - Map<String, Object> data = new HashMap<>(); | |
| 47 | - data.put("resp_code", HttpStatus.FORBIDDEN.value()); | |
| 48 | - data.put("resp_msg", exception.getMessage()); | |
| 49 | - | |
| 50 | - return data; | |
| 51 | - } | |
| 52 | - @ExceptionHandler({ StatusRuntimeException.class }) | |
| 53 | - @ResponseStatus(HttpStatus.BAD_REQUEST) | |
| 54 | - public Map<String, Object> badRequestException(StatusRuntimeException exception) { | |
| 55 | - Map<String, Object> data = new HashMap<>(); | |
| 56 | - data.put("resp_code", HttpStatus.INTERNAL_SERVER_ERROR.value()); | |
| 57 | - data.put("resp_msg", exception.getMessage()); | |
| 58 | - | |
| 59 | - return data; | |
| 60 | - } | |
| 61 | - | |
| 62 | - | |
| 63 | -} |
cloud/autho/src/main/java/com/sincere/autho/handler/OauthLogoutHandler.java
| ... | ... | @@ -1,90 +0,0 @@ |
| 1 | -package com.sincere.autho.handler; | |
| 2 | - | |
| 3 | -import org.slf4j.Logger; | |
| 4 | -import org.slf4j.LoggerFactory; | |
| 5 | -import org.springframework.beans.factory.annotation.Autowired; | |
| 6 | -import org.springframework.security.core.Authentication; | |
| 7 | -import org.springframework.security.oauth2.common.OAuth2AccessToken; | |
| 8 | -import org.springframework.security.oauth2.common.OAuth2RefreshToken; | |
| 9 | -import org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationDetails; | |
| 10 | -import org.springframework.security.oauth2.provider.token.TokenStore; | |
| 11 | -import org.springframework.security.web.authentication.logout.LogoutHandler; | |
| 12 | -import org.springframework.util.Assert; | |
| 13 | - | |
| 14 | -import javax.servlet.http.HttpServletRequest; | |
| 15 | -import javax.servlet.http.HttpServletResponse; | |
| 16 | -import java.util.Enumeration; | |
| 17 | - | |
| 18 | -/** | |
| 19 | - * @author keets | |
| 20 | - * @date 2017/10/17 | |
| 21 | - */ | |
| 22 | -public class OauthLogoutHandler implements LogoutHandler { | |
| 23 | - | |
| 24 | - private static final Logger logger = LoggerFactory.getLogger(OauthLogoutHandler.class); | |
| 25 | - | |
| 26 | - @Autowired | |
| 27 | - private TokenStore tokenStore; | |
| 28 | - | |
| 29 | - @Override | |
| 30 | - public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) { | |
| 31 | - Assert.notNull(tokenStore, "tokenStore must be set"); | |
| 32 | - String token = extractToken(request); | |
| 33 | - if(token!=null || !"".equals(token)){ | |
| 34 | - OAuth2AccessToken existingAccessToken = tokenStore.readAccessToken(token); | |
| 35 | - OAuth2RefreshToken refreshToken; | |
| 36 | - if (existingAccessToken != null) { | |
| 37 | - if (existingAccessToken.getRefreshToken() != null) { | |
| 38 | - logger.info("remove refreshToken!", existingAccessToken.getRefreshToken()); | |
| 39 | - refreshToken = existingAccessToken.getRefreshToken(); | |
| 40 | - tokenStore.removeRefreshToken(refreshToken); | |
| 41 | - } | |
| 42 | - logger.info("remove existingAccessToken!", existingAccessToken); | |
| 43 | - tokenStore.removeAccessToken(existingAccessToken); | |
| 44 | - } | |
| 45 | - return; | |
| 46 | - } | |
| 47 | - | |
| 48 | - } | |
| 49 | - | |
| 50 | - protected String extractToken(HttpServletRequest request) { | |
| 51 | - // first check the header... | |
| 52 | - String token = extractHeaderToken(request); | |
| 53 | - | |
| 54 | - // bearer type allows a request parameter as well | |
| 55 | - if (token == null) { | |
| 56 | - logger.debug("Token not found in headers. Trying request parameters."); | |
| 57 | - token = request.getParameter(OAuth2AccessToken.ACCESS_TOKEN); | |
| 58 | - if (token == null) { | |
| 59 | - logger.debug("Token not found in request parameters. Not an OAuth2 request."); | |
| 60 | - } else { | |
| 61 | - request.setAttribute(OAuth2AuthenticationDetails.ACCESS_TOKEN_TYPE, OAuth2AccessToken.BEARER_TYPE); | |
| 62 | - } | |
| 63 | - } | |
| 64 | - | |
| 65 | - return token; | |
| 66 | - } | |
| 67 | - | |
| 68 | - protected String extractHeaderToken(HttpServletRequest request) { | |
| 69 | - Enumeration<String> headers = request.getHeaders("Authorization"); | |
| 70 | - while (headers.hasMoreElements()) { // typically there is only one (most | |
| 71 | - // servers enforce that) | |
| 72 | - String value = headers.nextElement(); | |
| 73 | - if ((value.toLowerCase().startsWith(OAuth2AccessToken.BEARER_TYPE.toLowerCase()))) { | |
| 74 | - String authHeaderValue = value.substring(OAuth2AccessToken.BEARER_TYPE.length()).trim(); | |
| 75 | - // Add this here for the auth details later. Would be better to | |
| 76 | - // change the signature of this method. | |
| 77 | - request.setAttribute(OAuth2AuthenticationDetails.ACCESS_TOKEN_TYPE, | |
| 78 | - value.substring(0, OAuth2AccessToken.BEARER_TYPE.length()).trim()); | |
| 79 | - int commaIndex = authHeaderValue.indexOf(','); | |
| 80 | - if (commaIndex > 0) { | |
| 81 | - authHeaderValue = authHeaderValue.substring(0, commaIndex); | |
| 82 | - } | |
| 83 | - return authHeaderValue; | |
| 84 | - } | |
| 85 | - } | |
| 86 | - | |
| 87 | - return null; | |
| 88 | - } | |
| 89 | - | |
| 90 | -} |
cloud/autho/src/main/java/com/sincere/autho/log/dao/LogDao.java
| ... | ... | @@ -1,13 +0,0 @@ |
| 1 | -package com.sincere.autho.log.dao; | |
| 2 | - | |
| 3 | -import com.sincere.common.model.log.SysLog; | |
| 4 | -import org.apache.ibatis.annotations.Insert; | |
| 5 | -import org.apache.ibatis.annotations.Mapper; | |
| 6 | - | |
| 7 | -@Mapper | |
| 8 | -public interface LogDao { | |
| 9 | - | |
| 10 | - @Insert("insert into sys_log(username, module, params, remark, flag, createTime) values(#{username}, #{module}, #{params}, #{remark}, #{flag}, #{createTime})") | |
| 11 | - int save(SysLog log); | |
| 12 | - | |
| 13 | -} |
cloud/autho/src/main/java/com/sincere/autho/log/service/LogService.java
cloud/autho/src/main/java/com/sincere/autho/log/service/impl/LogServiceImpl.java
| ... | ... | @@ -1,34 +0,0 @@ |
| 1 | -package com.sincere.autho.log.service.impl; | |
| 2 | - | |
| 3 | -import com.sincere.autho.annotation.datasource.DataSource; | |
| 4 | -import com.sincere.autho.log.dao.LogDao; | |
| 5 | -import com.sincere.autho.log.service.LogService; | |
| 6 | -import com.sincere.common.model.log.SysLog; | |
| 7 | -import org.springframework.beans.factory.annotation.Autowired; | |
| 8 | -import org.springframework.scheduling.annotation.Async; | |
| 9 | -import org.springframework.stereotype.Service; | |
| 10 | - | |
| 11 | -import java.util.Date; | |
| 12 | - | |
| 13 | -@Service | |
| 14 | -public class LogServiceImpl implements LogService { | |
| 15 | - | |
| 16 | - @Autowired | |
| 17 | - private LogDao logDao; | |
| 18 | - | |
| 19 | - @Async | |
| 20 | - @Override | |
| 21 | - @DataSource(name="log") | |
| 22 | - public void save(SysLog log) { | |
| 23 | - if (log.getCreateTime() == null) { | |
| 24 | - log.setCreateTime(new Date()); | |
| 25 | - } | |
| 26 | - if (log.getFlag() == null) { | |
| 27 | - log.setFlag(Boolean.TRUE); | |
| 28 | - } | |
| 29 | - | |
| 30 | - logDao.save(log); | |
| 31 | - } | |
| 32 | - | |
| 33 | - | |
| 34 | -} |
cloud/autho/src/main/java/com/sincere/autho/mapper/UserMapper.java
0 → 100644
cloud/autho/src/main/java/com/sincere/autho/service/LoginService.java
0 → 100644
cloud/autho/src/main/java/com/sincere/autho/service/RedisAuthorizationCodeServices.java
| ... | ... | @@ -1,58 +0,0 @@ |
| 1 | -package com.sincere.autho.service; | |
| 2 | - | |
| 3 | -import org.springframework.data.redis.core.RedisTemplate; | |
| 4 | -import org.springframework.security.oauth2.provider.OAuth2Authentication; | |
| 5 | -import org.springframework.security.oauth2.provider.code.RandomValueAuthorizationCodeServices; | |
| 6 | - | |
| 7 | -import java.util.concurrent.TimeUnit; | |
| 8 | - | |
| 9 | -/** | |
| 10 | - * JdbcAuthorizationCodeServices替换 | |
| 11 | - */ | |
| 12 | -public class RedisAuthorizationCodeServices extends RandomValueAuthorizationCodeServices { | |
| 13 | - | |
| 14 | - private RedisTemplate<String,Object> redisTemplate ; | |
| 15 | - | |
| 16 | - | |
| 17 | - public RedisTemplate<String, Object> getRedisTemplate() { | |
| 18 | - return redisTemplate; | |
| 19 | - } | |
| 20 | - | |
| 21 | - public void setRedisTemplate(RedisTemplate<String, Object> redisTemplate) { | |
| 22 | - this.redisTemplate = redisTemplate; | |
| 23 | - } | |
| 24 | - | |
| 25 | - /** | |
| 26 | - * 替换JdbcAuthorizationCodeServices的存储策略 | |
| 27 | - * 将存储code到redis,并设置过期时间,10分钟<br> | |
| 28 | - */ | |
| 29 | - @Override | |
| 30 | - protected void store(String code, OAuth2Authentication authentication) { | |
| 31 | - | |
| 32 | - redisTemplate.opsForValue().set(redisKey(code), authentication, 10, TimeUnit.MINUTES); | |
| 33 | - | |
| 34 | - | |
| 35 | - } | |
| 36 | - | |
| 37 | - @Override | |
| 38 | - protected OAuth2Authentication remove(final String code) { | |
| 39 | - | |
| 40 | - String codeKey =redisKey(code) ; | |
| 41 | - | |
| 42 | - OAuth2Authentication token = (OAuth2Authentication) redisTemplate.opsForValue().get(codeKey) ; | |
| 43 | - | |
| 44 | - this.redisTemplate.delete(codeKey); | |
| 45 | - | |
| 46 | - return token; | |
| 47 | - } | |
| 48 | - | |
| 49 | - /** | |
| 50 | - * redis中 code key的前缀 | |
| 51 | - * | |
| 52 | - * @param code | |
| 53 | - * @return | |
| 54 | - */ | |
| 55 | - private String redisKey(String code) { | |
| 56 | - return "oauth:code:" + code; | |
| 57 | - } | |
| 58 | -} |
cloud/autho/src/main/java/com/sincere/autho/service/RedisClientDetailsService.java
| ... | ... | @@ -1,153 +0,0 @@ |
| 1 | -package com.sincere.autho.service; | |
| 2 | - | |
| 3 | -import com.alibaba.fastjson.JSONObject; | |
| 4 | -import org.apache.commons.lang.StringUtils; | |
| 5 | -import org.slf4j.Logger; | |
| 6 | -import org.slf4j.LoggerFactory; | |
| 7 | -import org.springframework.data.redis.core.RedisTemplate; | |
| 8 | -import org.springframework.security.oauth2.common.exceptions.InvalidClientException; | |
| 9 | -import org.springframework.security.oauth2.provider.ClientDetails; | |
| 10 | -import org.springframework.security.oauth2.provider.NoSuchClientException; | |
| 11 | -import org.springframework.security.oauth2.provider.client.BaseClientDetails; | |
| 12 | -import org.springframework.security.oauth2.provider.client.JdbcClientDetailsService; | |
| 13 | -import org.springframework.util.CollectionUtils; | |
| 14 | - | |
| 15 | -import javax.sql.DataSource; | |
| 16 | -import java.util.List; | |
| 17 | - | |
| 18 | - | |
| 19 | -/** | |
| 20 | - * @author owen 624191343@qq.com | |
| 21 | - * @version 创建时间:2017年11月12日 上午22:57:51 | |
| 22 | - * 类说明 | |
| 23 | - * 将oauth_client_details表数据缓存到redis,这里做个缓存优化 | |
| 24 | - * layui模块中有对oauth_client_details的crud, 注意同步redis的数据 | |
| 25 | - * 注意对oauth_client_details清楚redis db部分数据的清空 | |
| 26 | - */ | |
| 27 | - | |
| 28 | -public class RedisClientDetailsService extends JdbcClientDetailsService { | |
| 29 | - | |
| 30 | - | |
| 31 | - // 扩展 默认的 ClientDetailsService, 增加逻辑删除判断( status = 1) | |
| 32 | - private static final String SELECT_CLIENT_DETAILS_SQL = "select client_id, client_secret, resource_ids, scope, authorized_grant_types, " + | |
| 33 | - "web_server_redirect_uri, authorities, access_token_validity, refresh_token_validity, additional_information, autoapprove " + | |
| 34 | - "from oauth_client_details where client_id = ? and `status` = 1 "; | |
| 35 | - | |
| 36 | - | |
| 37 | - private static final String SELECT_FIND_STATEMENT = "select client_id, client_secret,resource_ids, scope, " | |
| 38 | - + "authorized_grant_types, web_server_redirect_uri, authorities, access_token_validity, " | |
| 39 | - + "refresh_token_validity, additional_information, autoapprove from oauth_client_details where `status` = 1 order by client_id " ; | |
| 40 | - | |
| 41 | - /** | |
| 42 | - * 缓存client的redis key,这里是hash结构存储 | |
| 43 | - */ | |
| 44 | - private static final String CACHE_CLIENT_KEY = "oauth_client_details"; | |
| 45 | - | |
| 46 | - private Logger logger = LoggerFactory.getLogger(RedisClientDetailsService.class) ; | |
| 47 | - | |
| 48 | - private RedisTemplate<String,Object> redisTemplate ; | |
| 49 | - | |
| 50 | - public RedisTemplate<String, Object> getRedisTemplate() { | |
| 51 | - return redisTemplate; | |
| 52 | - } | |
| 53 | - | |
| 54 | - public void setRedisTemplate(RedisTemplate<String, Object> redisTemplate) { | |
| 55 | - this.redisTemplate = redisTemplate; | |
| 56 | - } | |
| 57 | - | |
| 58 | - public RedisClientDetailsService(DataSource dataSource) { | |
| 59 | - super(dataSource); | |
| 60 | - setSelectClientDetailsSql(SELECT_CLIENT_DETAILS_SQL) ; | |
| 61 | - setFindClientDetailsSql(SELECT_FIND_STATEMENT) ; | |
| 62 | - } | |
| 63 | - | |
| 64 | - | |
| 65 | - | |
| 66 | - @Override | |
| 67 | - public ClientDetails loadClientByClientId(String clientId) throws InvalidClientException { | |
| 68 | - ClientDetails clientDetails = null; | |
| 69 | - | |
| 70 | - // 先从redis获取 | |
| 71 | - String value = (String) redisTemplate.boundHashOps(CACHE_CLIENT_KEY).get(clientId); | |
| 72 | - if (StringUtils.isBlank(value)) { | |
| 73 | - clientDetails = cacheAndGetClient(clientId); | |
| 74 | - } else { | |
| 75 | - clientDetails = JSONObject.parseObject(value, BaseClientDetails.class); | |
| 76 | - } | |
| 77 | - | |
| 78 | - return clientDetails; | |
| 79 | - } | |
| 80 | - | |
| 81 | - /** | |
| 82 | - * 缓存client并返回client | |
| 83 | - * | |
| 84 | - * @param clientId | |
| 85 | - * @return | |
| 86 | - */ | |
| 87 | - private ClientDetails cacheAndGetClient(String clientId) { | |
| 88 | - // 从数据库读取 | |
| 89 | - ClientDetails clientDetails = null ; | |
| 90 | - try { | |
| 91 | - clientDetails = super.loadClientByClientId(clientId); | |
| 92 | - if (clientDetails != null) { | |
| 93 | - // 写入redis缓存 | |
| 94 | - redisTemplate.boundHashOps(CACHE_CLIENT_KEY).put(clientId, JSONObject.toJSONString(clientDetails)); | |
| 95 | - logger.info("缓存clientId:{},{}", clientId, clientDetails); | |
| 96 | - } | |
| 97 | - }catch (NoSuchClientException e){ | |
| 98 | - logger.info("clientId:{},{}", clientId, clientId ); | |
| 99 | - }catch (InvalidClientException e) { | |
| 100 | - // TODO Auto-generated catch block | |
| 101 | - e.printStackTrace(); | |
| 102 | - } | |
| 103 | - | |
| 104 | - return clientDetails; | |
| 105 | - } | |
| 106 | - | |
| 107 | - @Override | |
| 108 | - public void updateClientDetails(ClientDetails clientDetails) throws NoSuchClientException { | |
| 109 | - super.updateClientDetails(clientDetails); | |
| 110 | - cacheAndGetClient(clientDetails.getClientId()); | |
| 111 | - } | |
| 112 | - | |
| 113 | - @Override | |
| 114 | - public void updateClientSecret(String clientId, String secret) throws NoSuchClientException { | |
| 115 | - super.updateClientSecret(clientId, secret); | |
| 116 | - cacheAndGetClient(clientId); | |
| 117 | - } | |
| 118 | - | |
| 119 | - @Override | |
| 120 | - public void removeClientDetails(String clientId) throws NoSuchClientException { | |
| 121 | - super.removeClientDetails(clientId); | |
| 122 | - removeRedisCache(clientId); | |
| 123 | - } | |
| 124 | - | |
| 125 | - /** | |
| 126 | - * 删除redis缓存 | |
| 127 | - * | |
| 128 | - * @param clientId | |
| 129 | - */ | |
| 130 | - private void removeRedisCache(String clientId) { | |
| 131 | - redisTemplate.boundHashOps(CACHE_CLIENT_KEY).delete(clientId); | |
| 132 | - } | |
| 133 | - | |
| 134 | - /** | |
| 135 | - * 将oauth_client_details全表刷入redis | |
| 136 | - */ | |
| 137 | - public void loadAllClientToCache() { | |
| 138 | - if (redisTemplate.hasKey(CACHE_CLIENT_KEY)) { | |
| 139 | - return; | |
| 140 | - } | |
| 141 | - logger.info("将oauth_client_details全表刷入redis"); | |
| 142 | - | |
| 143 | - List<ClientDetails> list = super.listClientDetails(); | |
| 144 | - if (CollectionUtils.isEmpty(list)) { | |
| 145 | - logger.error("oauth_client_details表数据为空,请检查"); | |
| 146 | - return; | |
| 147 | - } | |
| 148 | - | |
| 149 | - list.parallelStream().forEach(client -> { | |
| 150 | - redisTemplate.boundHashOps(CACHE_CLIENT_KEY).put(client.getClientId(), JSONObject.toJSONString(client)); | |
| 151 | - }); | |
| 152 | - } | |
| 153 | -} |
cloud/autho/src/main/java/com/sincere/autho/service/impl/LoginServiceImpl.java
0 → 100644
| ... | ... | @@ -0,0 +1,25 @@ |
| 1 | +package com.sincere.autho.service.impl; | |
| 2 | + | |
| 3 | +import com.sincere.autho.dto.req.LoginReqDto; | |
| 4 | +import com.sincere.autho.mapper.UserMapper; | |
| 5 | +import com.sincere.autho.service.LoginService; | |
| 6 | +import org.springframework.beans.factory.annotation.Autowired; | |
| 7 | +import org.springframework.stereotype.Service; | |
| 8 | + | |
| 9 | +@Service | |
| 10 | +public class LoginServiceImpl implements LoginService { | |
| 11 | + | |
| 12 | + @Autowired | |
| 13 | + UserMapper userMapper ; | |
| 14 | + | |
| 15 | + @Override | |
| 16 | + public String login(LoginReqDto loginReqDto) { | |
| 17 | + String userId = "" ; | |
| 18 | + if(loginReqDto.getUserType() == 2){ | |
| 19 | + userId = userMapper.loginStudent(loginReqDto); | |
| 20 | + }else { | |
| 21 | + userId = userMapper.loginTeacher(loginReqDto); | |
| 22 | + } | |
| 23 | + return userId; | |
| 24 | + } | |
| 25 | +} | ... | ... |
cloud/autho/src/main/java/com/sincere/autho/token/RedisTemplateTokenStore.java
| ... | ... | @@ -1,331 +0,0 @@ |
| 1 | -package com.sincere.autho.token; | |
| 2 | - | |
| 3 | -import com.sincere.common.model.system.LoginAppUser; | |
| 4 | -import org.springframework.data.redis.core.RedisTemplate; | |
| 5 | -import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; | |
| 6 | -import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken; | |
| 7 | -import org.springframework.security.oauth2.common.ExpiringOAuth2RefreshToken; | |
| 8 | -import org.springframework.security.oauth2.common.OAuth2AccessToken; | |
| 9 | -import org.springframework.security.oauth2.common.OAuth2RefreshToken; | |
| 10 | -import org.springframework.security.oauth2.provider.OAuth2Authentication; | |
| 11 | -import org.springframework.security.oauth2.provider.token.AuthenticationKeyGenerator; | |
| 12 | -import org.springframework.security.oauth2.provider.token.DefaultAuthenticationKeyGenerator; | |
| 13 | -import org.springframework.security.oauth2.provider.token.TokenStore; | |
| 14 | - | |
| 15 | -import java.time.Instant; | |
| 16 | -import java.time.LocalDateTime; | |
| 17 | -import java.time.ZoneId; | |
| 18 | -import java.util.*; | |
| 19 | -import java.util.concurrent.TimeUnit; | |
| 20 | - | |
| 21 | -/** | |
| 22 | - * @version redis集群存储token | |
| 23 | - */ | |
| 24 | - | |
| 25 | -public class RedisTemplateTokenStore implements TokenStore { | |
| 26 | - | |
| 27 | - private static final String ACCESS = "access:"; | |
| 28 | - private static final String AUTH_TO_ACCESS = "auth_to_access:"; | |
| 29 | - private static final String AUTH = "auth:"; | |
| 30 | - private static final String REFRESH_AUTH = "refresh_auth:"; | |
| 31 | - private static final String ACCESS_TO_REFRESH = "access_to_refresh:"; | |
| 32 | - private static final String REFRESH = "refresh:"; | |
| 33 | - private static final String REFRESH_TO_ACCESS = "refresh_to_access:"; | |
| 34 | - private static final String CLIENT_ID_TO_ACCESS = "client_id_to_access:"; | |
| 35 | - private static final String UNAME_TO_ACCESS = "uname_to_access:"; | |
| 36 | - private static final String TOKEN = "token:"; | |
| 37 | - | |
| 38 | - private RedisTemplate<String, Object> redisTemplate; | |
| 39 | - | |
| 40 | - public RedisTemplate<String, Object> getRedisTemplate() { | |
| 41 | - return redisTemplate; | |
| 42 | - } | |
| 43 | - | |
| 44 | - public void setRedisTemplate(RedisTemplate<String, Object> redisTemplate) { | |
| 45 | - this.redisTemplate = redisTemplate; | |
| 46 | - } | |
| 47 | - | |
| 48 | - private AuthenticationKeyGenerator authenticationKeyGenerator = new DefaultAuthenticationKeyGenerator(); | |
| 49 | - | |
| 50 | - public void setAuthenticationKeyGenerator(AuthenticationKeyGenerator authenticationKeyGenerator) { | |
| 51 | - this.authenticationKeyGenerator = authenticationKeyGenerator; | |
| 52 | - } | |
| 53 | - | |
| 54 | - public OAuth2AccessToken getAccessToken(OAuth2Authentication authentication) { | |
| 55 | - String key = authenticationKeyGenerator.extractKey(authentication); | |
| 56 | - OAuth2AccessToken accessToken = (OAuth2AccessToken) redisTemplate.opsForValue().get(AUTH_TO_ACCESS + key); | |
| 57 | - if (accessToken != null | |
| 58 | - && !key.equals(authenticationKeyGenerator.extractKey(readAuthentication(accessToken.getValue())))) { | |
| 59 | - // Keep the stores consistent (maybe the same user is represented by | |
| 60 | - // this authentication but the details | |
| 61 | - // have changed) | |
| 62 | - storeAccessToken(accessToken, authentication); | |
| 63 | - } | |
| 64 | - return accessToken; | |
| 65 | - } | |
| 66 | - | |
| 67 | - public OAuth2Authentication readAuthentication(OAuth2AccessToken token) { | |
| 68 | - return readAuthentication(token.getValue()); | |
| 69 | - } | |
| 70 | - | |
| 71 | - public OAuth2Authentication readAuthentication(String token) { | |
| 72 | - return (OAuth2Authentication) this.redisTemplate.opsForValue().get(AUTH + token); | |
| 73 | - } | |
| 74 | - | |
| 75 | - public OAuth2Authentication readAuthenticationForRefreshToken(OAuth2RefreshToken token) { | |
| 76 | - return readAuthenticationForRefreshToken(token.getValue()); | |
| 77 | - } | |
| 78 | - | |
| 79 | - public OAuth2Authentication readAuthenticationForRefreshToken(String token) { | |
| 80 | - return (OAuth2Authentication) this.redisTemplate.opsForValue().get(REFRESH_AUTH + token); | |
| 81 | - } | |
| 82 | - | |
| 83 | - public void storeAccessToken(OAuth2AccessToken token, OAuth2Authentication authentication) { | |
| 84 | - | |
| 85 | - OAuth2AccessToken existingAccessToken = this.getAccessToken(authentication); | |
| 86 | - | |
| 87 | - this.redisTemplate.opsForValue().set(ACCESS + token.getValue(), token); | |
| 88 | - this.redisTemplate.opsForValue().set(AUTH + token.getValue(), authentication); | |
| 89 | - this.redisTemplate.opsForValue().set(AUTH_TO_ACCESS + authenticationKeyGenerator.extractKey(authentication), | |
| 90 | - token); | |
| 91 | - | |
| 92 | - Map<String, Object> params = new HashMap<>(); | |
| 93 | - | |
| 94 | - params.put("clientId", authentication.getOAuth2Request().getClientId()); | |
| 95 | - | |
| 96 | - if (authentication.getUserAuthentication() instanceof UsernamePasswordAuthenticationToken) { | |
| 97 | - UsernamePasswordAuthenticationToken authenticationToken = (UsernamePasswordAuthenticationToken) authentication | |
| 98 | - .getUserAuthentication(); | |
| 99 | - LoginAppUser appUser = (LoginAppUser) authenticationToken.getPrincipal(); | |
| 100 | - params.put("username", appUser.getUsername()); | |
| 101 | - params.put("authorities", appUser.getAuthorities()); | |
| 102 | - } | |
| 103 | - | |
| 104 | - if (!params.isEmpty()) { | |
| 105 | - this.redisTemplate.opsForValue().set(TOKEN + token.getValue(), params); | |
| 106 | - } | |
| 107 | - | |
| 108 | - if (!authentication.isClientOnly()) { | |
| 109 | - if (existingAccessToken != null) { | |
| 110 | - if (!existingAccessToken.isExpired()) { | |
| 111 | - int seconds = token.getExpiresIn(); | |
| 112 | - redisTemplate.expire(UNAME_TO_ACCESS + authentication.getOAuth2Request().getClientId(), seconds, | |
| 113 | - TimeUnit.SECONDS); | |
| 114 | - } else { | |
| 115 | - redisTemplate.opsForList().rightPush(UNAME_TO_ACCESS + getApprovalKey(authentication), token); | |
| 116 | - } | |
| 117 | - } else { | |
| 118 | - redisTemplate.opsForList().rightPush(UNAME_TO_ACCESS + getApprovalKey(authentication), token); | |
| 119 | - } | |
| 120 | - | |
| 121 | - } | |
| 122 | - | |
| 123 | - if (existingAccessToken != null) { | |
| 124 | - if (!existingAccessToken.isExpired()) { | |
| 125 | - int seconds = token.getExpiresIn(); | |
| 126 | - redisTemplate.expire(CLIENT_ID_TO_ACCESS + authentication.getOAuth2Request().getClientId(), seconds, | |
| 127 | - TimeUnit.SECONDS); | |
| 128 | - | |
| 129 | - } else { | |
| 130 | - redisTemplate.opsForList() | |
| 131 | - .rightPush(CLIENT_ID_TO_ACCESS + authentication.getOAuth2Request().getClientId(), token); | |
| 132 | - } | |
| 133 | - } else { | |
| 134 | - redisTemplate.opsForList().rightPush(CLIENT_ID_TO_ACCESS + authentication.getOAuth2Request().getClientId(), | |
| 135 | - token); | |
| 136 | - } | |
| 137 | - | |
| 138 | - if (token.getExpiration() != null) { | |
| 139 | - | |
| 140 | - int seconds = token.getExpiresIn(); | |
| 141 | - redisTemplate.expire(ACCESS + token.getValue(), seconds, TimeUnit.SECONDS); | |
| 142 | - redisTemplate.expire(AUTH + token.getValue(), seconds, TimeUnit.SECONDS); | |
| 143 | - redisTemplate.expire(TOKEN + token.getValue(), seconds, TimeUnit.SECONDS); | |
| 144 | - redisTemplate.expire(AUTH_TO_ACCESS + authenticationKeyGenerator.extractKey(authentication), seconds, | |
| 145 | - TimeUnit.SECONDS); | |
| 146 | - redisTemplate.expire(CLIENT_ID_TO_ACCESS + authentication.getOAuth2Request().getClientId(), seconds, | |
| 147 | - TimeUnit.SECONDS); | |
| 148 | - redisTemplate.expire(UNAME_TO_ACCESS + getApprovalKey(authentication), seconds, TimeUnit.SECONDS); | |
| 149 | - } | |
| 150 | - | |
| 151 | - OAuth2RefreshToken refreshToken = token.getRefreshToken(); | |
| 152 | - | |
| 153 | - if (token.getRefreshToken() != null && token.getRefreshToken().getValue() != null) { | |
| 154 | - this.redisTemplate.opsForValue().set(REFRESH_TO_ACCESS + token.getRefreshToken().getValue(), | |
| 155 | - token.getValue()); | |
| 156 | - this.redisTemplate.opsForValue().set(ACCESS_TO_REFRESH + token.getValue(), | |
| 157 | - token.getRefreshToken().getValue()); | |
| 158 | - | |
| 159 | - if (refreshToken instanceof ExpiringOAuth2RefreshToken) { | |
| 160 | - ExpiringOAuth2RefreshToken expiringRefreshToken = (ExpiringOAuth2RefreshToken) refreshToken; | |
| 161 | - Date expiration = expiringRefreshToken.getExpiration(); | |
| 162 | - if (expiration != null) { | |
| 163 | - int seconds = Long.valueOf((expiration.getTime() - System.currentTimeMillis()) / 1000L).intValue(); | |
| 164 | - | |
| 165 | - redisTemplate.expire(REFRESH_TO_ACCESS + token.getRefreshToken().getValue(), seconds, | |
| 166 | - TimeUnit.SECONDS); | |
| 167 | - redisTemplate.expire(ACCESS_TO_REFRESH + token.getValue(), seconds, TimeUnit.SECONDS); | |
| 168 | - | |
| 169 | - } | |
| 170 | - } | |
| 171 | - | |
| 172 | - } | |
| 173 | - } | |
| 174 | - | |
| 175 | - private String getApprovalKey(OAuth2Authentication authentication) { | |
| 176 | - String userName = authentication.getUserAuthentication() == null ? "" | |
| 177 | - : authentication.getUserAuthentication().getName(); | |
| 178 | - return getApprovalKey(authentication.getOAuth2Request().getClientId(), userName); | |
| 179 | - } | |
| 180 | - | |
| 181 | - private String getApprovalKey(String clientId, String userName) { | |
| 182 | - return clientId + (userName == null ? "" : ":" + userName); | |
| 183 | - } | |
| 184 | - | |
| 185 | - public void removeAccessToken(OAuth2AccessToken accessToken) { | |
| 186 | - removeAccessToken(accessToken.getValue()); | |
| 187 | - } | |
| 188 | - | |
| 189 | - public OAuth2AccessToken readAccessToken(String tokenValue) { | |
| 190 | - | |
| 191 | - OAuth2Authentication oauth2Authentication = (OAuth2Authentication) this.redisTemplate.opsForValue() | |
| 192 | - .get(AUTH + tokenValue); | |
| 193 | - OAuth2AccessToken oauth2AccessToken = (OAuth2AccessToken) this.redisTemplate.opsForValue() | |
| 194 | - .get(ACCESS + tokenValue); | |
| 195 | - if (oauth2Authentication != null) { | |
| 196 | - String auth_to_access = authenticationKeyGenerator.extractKey(oauth2Authentication); | |
| 197 | - if (oauth2AccessToken != null) { | |
| 198 | - if (oauth2AccessToken.getExpiresIn() < 180) { | |
| 199 | - | |
| 200 | - if (oauth2AccessToken instanceof DefaultOAuth2AccessToken) { | |
| 201 | - DefaultOAuth2AccessToken token = (DefaultOAuth2AccessToken) oauth2AccessToken; | |
| 202 | -// Calendar cal = Calendar.getInstance(); | |
| 203 | -// cal.add(Calendar.DATE, 30); | |
| 204 | -// Date date = cal.getTime(); | |
| 205 | - /** | |
| 206 | - * 自动续费 30分钟 | |
| 207 | - */ | |
| 208 | - LocalDateTime t1 = LocalDateTime.now().plusMinutes(30); | |
| 209 | - ZoneId zone = ZoneId.systemDefault(); | |
| 210 | - Instant instant = t1.atZone(zone).toInstant(); | |
| 211 | - Date date = Date.from(instant); | |
| 212 | - | |
| 213 | - token.setExpiration(date); | |
| 214 | - | |
| 215 | - int seconds = token.getExpiresIn(); | |
| 216 | - | |
| 217 | - this.redisTemplate.opsForValue().set(AUTH_TO_ACCESS + auth_to_access, token, seconds, | |
| 218 | - TimeUnit.SECONDS); | |
| 219 | - this.redisTemplate.opsForValue().set(ACCESS + token.getValue(), token, seconds, | |
| 220 | - TimeUnit.SECONDS); | |
| 221 | - | |
| 222 | - redisTemplate.expire(AUTH + token.getValue(), seconds, TimeUnit.SECONDS); | |
| 223 | - redisTemplate.expire(TOKEN + token.getValue(), seconds, TimeUnit.SECONDS); | |
| 224 | - | |
| 225 | - redisTemplate.expire( | |
| 226 | - CLIENT_ID_TO_ACCESS + oauth2Authentication.getOAuth2Request().getClientId(), seconds, | |
| 227 | - TimeUnit.SECONDS); | |
| 228 | - redisTemplate.expire(UNAME_TO_ACCESS + getApprovalKey(oauth2Authentication), seconds, | |
| 229 | - TimeUnit.SECONDS); | |
| 230 | - | |
| 231 | - } | |
| 232 | - | |
| 233 | - } | |
| 234 | - } | |
| 235 | - } | |
| 236 | - | |
| 237 | - return oauth2AccessToken; | |
| 238 | - } | |
| 239 | - | |
| 240 | - public void removeAccessToken(String tokenValue) { | |
| 241 | - OAuth2AccessToken removed = (OAuth2AccessToken) redisTemplate.opsForValue().get(ACCESS + tokenValue); | |
| 242 | - // Don't remove the refresh token - it's up to the caller to do that | |
| 243 | - OAuth2Authentication authentication = (OAuth2Authentication) this.redisTemplate.opsForValue() | |
| 244 | - .get(AUTH + tokenValue); | |
| 245 | - | |
| 246 | - this.redisTemplate.delete(AUTH + tokenValue); | |
| 247 | - redisTemplate.delete(ACCESS + tokenValue); | |
| 248 | - redisTemplate.delete(TOKEN + tokenValue); | |
| 249 | - this.redisTemplate.delete(ACCESS_TO_REFRESH + tokenValue); | |
| 250 | - | |
| 251 | - if (authentication != null) { | |
| 252 | - this.redisTemplate.delete(AUTH_TO_ACCESS + authenticationKeyGenerator.extractKey(authentication)); | |
| 253 | - | |
| 254 | - String clientId = authentication.getOAuth2Request().getClientId(); | |
| 255 | - | |
| 256 | - // redisTemplate.opsForList().rightPush("UNAME_TO_ACCESS:"+getApprovalKey(authentication), | |
| 257 | - // token) ; | |
| 258 | - redisTemplate.opsForList().leftPop(UNAME_TO_ACCESS + getApprovalKey(clientId, authentication.getName())); | |
| 259 | - | |
| 260 | - redisTemplate.opsForList().leftPop(CLIENT_ID_TO_ACCESS + clientId); | |
| 261 | - | |
| 262 | - this.redisTemplate.delete(AUTH_TO_ACCESS + authenticationKeyGenerator.extractKey(authentication)); | |
| 263 | - } | |
| 264 | - } | |
| 265 | - | |
| 266 | - public void storeRefreshToken(OAuth2RefreshToken refreshToken, OAuth2Authentication authentication) { | |
| 267 | - this.redisTemplate.opsForValue().set(REFRESH + refreshToken.getValue(), refreshToken); | |
| 268 | - this.redisTemplate.opsForValue().set(REFRESH_AUTH + refreshToken.getValue(), authentication); | |
| 269 | - } | |
| 270 | - | |
| 271 | - public OAuth2RefreshToken readRefreshToken(String tokenValue) { | |
| 272 | - return (OAuth2RefreshToken) this.redisTemplate.opsForValue().get(REFRESH + tokenValue); | |
| 273 | - } | |
| 274 | - | |
| 275 | - public void removeRefreshToken(OAuth2RefreshToken refreshToken) { | |
| 276 | - removeRefreshToken(refreshToken.getValue()); | |
| 277 | - } | |
| 278 | - | |
| 279 | - public void removeRefreshToken(String tokenValue) { | |
| 280 | - this.redisTemplate.delete(REFRESH + tokenValue); | |
| 281 | - this.redisTemplate.delete(REFRESH_AUTH + tokenValue); | |
| 282 | - this.redisTemplate.delete(REFRESH_TO_ACCESS + tokenValue); | |
| 283 | - } | |
| 284 | - | |
| 285 | - public void removeAccessTokenUsingRefreshToken(OAuth2RefreshToken refreshToken) { | |
| 286 | - removeAccessTokenUsingRefreshToken(refreshToken.getValue()); | |
| 287 | - } | |
| 288 | - | |
| 289 | - private void removeAccessTokenUsingRefreshToken(String refreshToken) { | |
| 290 | - | |
| 291 | - String token = (String) this.redisTemplate.opsForValue().get(REFRESH_TO_ACCESS + refreshToken); | |
| 292 | - | |
| 293 | - if (token != null) { | |
| 294 | - redisTemplate.delete(REFRESH_TO_ACCESS + refreshToken); | |
| 295 | - } | |
| 296 | - } | |
| 297 | - | |
| 298 | - public Collection<OAuth2AccessToken> findTokensByClientIdAndUserName(String clientId, String userName) { | |
| 299 | - List<Object> result = redisTemplate.opsForList().range(UNAME_TO_ACCESS + getApprovalKey(clientId, userName), 0, | |
| 300 | - -1); | |
| 301 | - | |
| 302 | - if (result == null || result.size() == 0) { | |
| 303 | - return Collections.<OAuth2AccessToken>emptySet(); | |
| 304 | - } | |
| 305 | - List<OAuth2AccessToken> accessTokens = new ArrayList<OAuth2AccessToken>(result.size()); | |
| 306 | - | |
| 307 | - for (Iterator<Object> it = result.iterator(); it.hasNext();) { | |
| 308 | - OAuth2AccessToken accessToken = (OAuth2AccessToken) it.next(); | |
| 309 | - accessTokens.add(accessToken); | |
| 310 | - } | |
| 311 | - | |
| 312 | - return Collections.<OAuth2AccessToken>unmodifiableCollection(accessTokens); | |
| 313 | - } | |
| 314 | - | |
| 315 | - public Collection<OAuth2AccessToken> findTokensByClientId(String clientId) { | |
| 316 | - List<Object> result = redisTemplate.opsForList().range((CLIENT_ID_TO_ACCESS + clientId), 0, -1); | |
| 317 | - | |
| 318 | - if (result == null || result.size() == 0) { | |
| 319 | - return Collections.<OAuth2AccessToken>emptySet(); | |
| 320 | - } | |
| 321 | - List<OAuth2AccessToken> accessTokens = new ArrayList<OAuth2AccessToken>(result.size()); | |
| 322 | - | |
| 323 | - for (Iterator<Object> it = result.iterator(); it.hasNext();) { | |
| 324 | - OAuth2AccessToken accessToken = (OAuth2AccessToken) it.next(); | |
| 325 | - accessTokens.add(accessToken); | |
| 326 | - } | |
| 327 | - | |
| 328 | - return Collections.<OAuth2AccessToken>unmodifiableCollection(accessTokens); | |
| 329 | - } | |
| 330 | - | |
| 331 | -} |
cloud/autho/src/main/java/com/sincere/autho/utils/SpringUtil.java
| ... | ... | @@ -1,35 +0,0 @@ |
| 1 | -package com.sincere.autho.utils; | |
| 2 | - | |
| 3 | -import org.springframework.beans.BeansException; | |
| 4 | -import org.springframework.context.ApplicationContext; | |
| 5 | -import org.springframework.context.ApplicationContextAware; | |
| 6 | -import org.springframework.core.env.Environment; | |
| 7 | -import org.springframework.stereotype.Component; | |
| 8 | - | |
| 9 | -/** | |
| 10 | - * spring获取bean工具类 | |
| 11 | - * | |
| 12 | - * | |
| 13 | - */ | |
| 14 | -@Component | |
| 15 | -public class SpringUtil implements ApplicationContextAware { | |
| 16 | - | |
| 17 | - private static ApplicationContext applicationContext = null; | |
| 18 | - | |
| 19 | - @Override | |
| 20 | - public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { | |
| 21 | - SpringUtil.applicationContext = applicationContext; | |
| 22 | - } | |
| 23 | - | |
| 24 | - public static <T> T getBean(Class<T> cla) { | |
| 25 | - return applicationContext.getBean(cla); | |
| 26 | - } | |
| 27 | - | |
| 28 | - public static <T> T getBean(String name, Class<T> cal) { | |
| 29 | - return applicationContext.getBean(name, cal); | |
| 30 | - } | |
| 31 | - | |
| 32 | - public static String getProperty(String key) { | |
| 33 | - return applicationContext.getBean(Environment.class).getProperty(key); | |
| 34 | - } | |
| 35 | -} |
cloud/autho/src/main/java/com/sincere/autho/utils/SysUserUtil.java
| ... | ... | @@ -1,41 +0,0 @@ |
| 1 | -package com.sincere.autho.utils; | |
| 2 | - | |
| 3 | -import com.sincere.common.model.system.LoginAppUser; | |
| 4 | -import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; | |
| 5 | -import org.springframework.security.core.Authentication; | |
| 6 | -import org.springframework.security.core.context.SecurityContextHolder; | |
| 7 | -import org.springframework.security.oauth2.provider.OAuth2Authentication; | |
| 8 | -import org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken; | |
| 9 | - | |
| 10 | -/** | |
| 11 | - * @author 作者 owen E-mail: 624191343@qq.com | |
| 12 | - * @version 创建时间:2017年11月12日 上午22:57:51 获取用户信息 | |
| 13 | - */ | |
| 14 | -public class SysUserUtil { | |
| 15 | - | |
| 16 | - /** | |
| 17 | - * 获取登陆的 LoginAppUser | |
| 18 | - * | |
| 19 | - * @return | |
| 20 | - */ | |
| 21 | - @SuppressWarnings("rawtypes") | |
| 22 | - public static LoginAppUser getLoginAppUser() { | |
| 23 | - Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); | |
| 24 | - if (authentication instanceof OAuth2Authentication) { | |
| 25 | - OAuth2Authentication oAuth2Auth = (OAuth2Authentication) authentication; | |
| 26 | - authentication = oAuth2Auth.getUserAuthentication(); | |
| 27 | - | |
| 28 | - if (authentication instanceof UsernamePasswordAuthenticationToken) { | |
| 29 | - UsernamePasswordAuthenticationToken authenticationToken = (UsernamePasswordAuthenticationToken) authentication; | |
| 30 | - return (LoginAppUser) authenticationToken.getPrincipal(); | |
| 31 | - } else if (authentication instanceof PreAuthenticatedAuthenticationToken) { | |
| 32 | - // 刷新token方式 | |
| 33 | - PreAuthenticatedAuthenticationToken authenticationToken = (PreAuthenticatedAuthenticationToken) authentication; | |
| 34 | - return (LoginAppUser) authenticationToken.getPrincipal(); | |
| 35 | - | |
| 36 | - } | |
| 37 | - } | |
| 38 | - | |
| 39 | - return null; | |
| 40 | - } | |
| 41 | -} |
cloud/autho/src/main/resources/application.yaml
| 1 | 1 | server: |
| 2 | - port: 8763 | |
| 2 | + port: 9005 | |
| 3 | 3 | |
| 4 | 4 | spring: |
| 5 | 5 | application: |
| 6 | - name: auth-server | |
| 7 | -session: | |
| 8 | - store-type: redis | |
| 6 | + name: authserver | |
| 9 | 7 | datasource: |
| 10 | - dynamic: | |
| 11 | - enable: true | |
| 12 | - druid: | |
| 13 | - # JDBC 配置(驱动类自动从url的mysql识别,数据源类型自动识别) | |
| 14 | - core: | |
| 15 | - url: jdbc:mysql://localhost/oauth-center?useUnicode=true&characterEncoding=utf-8&allowMultiQueries=true&useSSL=false | |
| 16 | - username: root | |
| 17 | - password: root | |
| 18 | - driver-class-name: com.mysql.jdbc.Driver | |
| 19 | - log: | |
| 20 | - url: jdbc:mysql://59.110.164.254:3306/log-center?useUnicode=true&characterEncoding=utf-8&allowMultiQueries=true&useSSL=false | |
| 21 | - username: root | |
| 22 | - password: root | |
| 23 | - driver-class-name: com.mysql.jdbc.Driver | |
| 24 | - #连接池配置(通常来说,只需要修改initialSize、minIdle、maxActive | |
| 25 | - initial-size: 1 | |
| 26 | - max-active: 20 | |
| 27 | - min-idle: 1 | |
| 28 | - # 配置获取连接等待超时的时间 | |
| 29 | - max-wait: 60000 | |
| 30 | - #打开PSCache,并且指定每个连接上PSCache的大小 | |
| 31 | - pool-prepared-statements: true | |
| 32 | - max-pool-prepared-statement-per-connection-size: 20 | |
| 33 | - validation-query: SELECT 'x' | |
| 34 | - test-on-borrow: false | |
| 35 | - test-on-return: false | |
| 36 | - test-while-idle: true | |
| 37 | - #配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 | |
| 38 | - time-between-eviction-runs-millis: 60000 | |
| 39 | - #配置一个连接在池中最小生存的时间,单位是毫秒 | |
| 40 | - min-evictable-idle-time-millis: 300000 | |
| 41 | - filters: stat,wall | |
| 42 | - # WebStatFilter配置,说明请参考Druid Wiki,配置_配置WebStatFilter | |
| 43 | - #是否启用StatFilter默认值true | |
| 44 | - web-stat-filter.enabled: true | |
| 45 | - web-stat-filter.url-pattern: /* | |
| 46 | - web-stat-filter.exclusions: "*.js , *.gif ,*.jpg ,*.png ,*.css ,*.ico , /druid/*" | |
| 47 | - web-stat-filter.session-stat-max-count: 1000 | |
| 48 | - web-stat-filter.profile-enable: true | |
| 49 | - # StatViewServlet配置 | |
| 50 | - #展示Druid的统计信息,StatViewServlet的用途包括:1.提供监控信息展示的html页面2.提供监控信息的JSON API | |
| 51 | - #是否启用StatViewServlet默认值true | |
| 52 | - stat-view-servlet.enabled: true | |
| 53 | - #根据配置中的url-pattern来访问内置监控页面,如果是上面的配置,内置监控页面的首页是/druid/index.html例如: | |
| 54 | - #http://110.76.43.235:9000/druid/index.html | |
| 55 | - #http://110.76.43.235:8080/mini-web/druid/index.html | |
| 56 | - stat-view-servlet.url-pattern: /druid/* | |
| 57 | - #允许清空统计数据 | |
| 58 | - stat-view-servlet.reset-enable: true | |
| 59 | - stat-view-servlet.login-username: admin | |
| 60 | - stat-view-servlet.login-password: admin | |
| 61 | - #StatViewSerlvet展示出来的监控信息比较敏感,是系统运行的内部情况,如果你需要做访问控制,可以配置allow和deny这两个参数 | |
| 62 | - #deny优先于allow,如果在deny列表中,就算在allow列表中,也会被拒绝。如果allow没有配置或者为空,则允许所有访问 | |
| 63 | - #配置的格式 | |
| 64 | - #<IP> | |
| 65 | - #或者<IP>/<SUB_NET_MASK_size>其中128.242.127.1/24 | |
| 66 | - #24表示,前面24位是子网掩码,比对的时候,前面24位相同就匹配,不支持IPV6。 | |
| 67 | - #stat-view-servlet.allow= | |
| 68 | - #stat-view-servlet.deny=128.242.127.1/24,128.242.128.1 | |
| 69 | - # Spring监控配置,说明请参考Druid Github Wiki,配置_Druid和Spring关联监控配置 | |
| 70 | - #aop-patterns= # Spring监控AOP切入点,如x.y.z.service.*,配置多个英文逗号分隔 | |
| 71 | -################### mysq end ########################## | |
| 72 | - | |
| 73 | - | |
| 8 | + username: szjxtuser | |
| 9 | + password: RQminVCJota3H1u8bBYH | |
| 10 | + url: jdbc:sqlserver://116.62.155.137:33419;database=SmartCampus | |
| 11 | + driver-class-name: com.microsoft.sqlserver.jdbc.SQLServerDriver | |
| 12 | +##mybatis | |
| 13 | +mybatis: | |
| 14 | + mapper-locations: classpath:mapper/*.xml | |
| 15 | + type-aliases-package: com.sincere.autho.mapper | |
| 16 | + check-config-location: true | |
| 17 | +ribbon: | |
| 18 | + ReadTimeout: 50000 | |
| 19 | + ConnectTimeout: 5000 | |
| 74 | 20 | eureka: |
| 75 | 21 | instance: |
| 76 | 22 | hostname: localhost |
| ... | ... | @@ -78,19 +24,5 @@ eureka: |
| 78 | 24 | lease-renewal-interval-in-seconds: 10 |
| 79 | 25 | client: |
| 80 | 26 | service-url: |
| 81 | - defaultZone: http://121.40.109.21:8761/eureka/,http://121.40.109.21:8762/eureka/ | |
| 82 | - | |
| 27 | + defaultZone: http://localhost:8761/eureka/,http://localhost:8762/eureka/ | |
| 83 | 28 | |
| 84 | - redis: | |
| 85 | - ################### redis 单机版 start ########################## | |
| 86 | - host: localhost | |
| 87 | - port: 6379 | |
| 88 | - timeout: 6000 | |
| 89 | - database: 2 | |
| 90 | - lettuce: | |
| 91 | - pool: | |
| 92 | - max-active: 10 # 连接池最大连接数(使用负值表示没有限制),如果赋值为-1,则表示不限制;如果pool已经分配了maxActive个jedis实例,则此时pool的状态为exhausted(耗尽) | |
| 93 | - max-idle: 8 # 连接池中的最大空闲连接 ,默认值也是8 | |
| 94 | - max-wait: 100 # # 等待可用连接的最大时间,单位毫秒,默认值为-1,表示永不超时。如果超过等待时间,则直接抛出JedisConnectionException | |
| 95 | - min-idle: 2 # 连接池中的最小空闲连接 ,默认值也是0 | |
| 96 | - shutdown-timeout: 100ms | |
| 97 | 29 | \ No newline at end of file | ... | ... |
| ... | ... | @@ -0,0 +1,14 @@ |
| 1 | +<?xml version="1.0" encoding="UTF-8" ?> | |
| 2 | +<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" > | |
| 3 | +<mapper namespace="com.sincere.autho.mapper.UserMapper"> | |
| 4 | + | |
| 5 | + | |
| 6 | + <select id="loginTeacher" parameterType="com.sincere.autho.dto.req.LoginReqDto" resultType="java.lang.String"> | |
| 7 | + select user_id from SZ_User where mobile = #{account} and pass = #{password} | |
| 8 | + </select> | |
| 9 | + | |
| 10 | + <select id="loginStudent" parameterType="com.sincere.autho.dto.req.LoginReqDto" resultType="java.lang.String"> | |
| 11 | + select user_id from SZ_User where othername = #{account} and pass = #{password} | |
| 12 | + </select> | |
| 13 | + | |
| 14 | +</mapper> | ... | ... |
cloud/common/src/main/java/com/sincere/common/util/TokenUtils.java
cloud/getaway/src/main/java/com/sincere/getaway/client/filter/AccessFilter.java
| ... | ... | @@ -63,8 +63,8 @@ public class AccessFilter implements GlobalFilter, Ordered { |
| 63 | 63 | exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED); |
| 64 | 64 | ServerHttpResponse response = exchange.getResponse(); |
| 65 | 65 | JSONObject message = new JSONObject(); |
| 66 | - message.put("resp_code", result.getCode()); | |
| 67 | - message.put("resp_msg", result.getMessage()); | |
| 66 | + message.put("code", result.getCode()); | |
| 67 | + message.put("message", result.getMessage()); | |
| 68 | 68 | byte[] bits = message.toJSONString().getBytes(StandardCharsets.UTF_8); |
| 69 | 69 | DataBuffer buffer = response.bufferFactory().wrap(bits); |
| 70 | 70 | response.setStatusCode(HttpStatus.UNAUTHORIZED); |
| ... | ... | @@ -86,7 +86,7 @@ public class AccessFilter implements GlobalFilter, Ordered { |
| 86 | 86 | return ResultEnums.getByCode(e.getCode()); |
| 87 | 87 | } |
| 88 | 88 | } |
| 89 | - return ResultEnums.error ; | |
| 89 | + return ResultEnums.success ; | |
| 90 | 90 | } |
| 91 | 91 | |
| 92 | 92 | public String extractToken(ServerHttpRequest request) { | ... | ... |
cloud/getaway/src/main/resources/application.yml
| ... | ... | @@ -27,5 +27,11 @@ spring: |
| 27 | 27 | - Path=/haikangserver/** |
| 28 | 28 | filters: |
| 29 | 29 | - StripPrefix=1 |
| 30 | + - id: authserver | |
| 31 | + uri: lb://authserver | |
| 32 | + predicates: | |
| 33 | + - Path=/authserver/** | |
| 34 | + filters: | |
| 35 | + - StripPrefix=1 | |
| 30 | 36 | url: |
| 31 | - ignored: /user/** | |
| 32 | 37 | \ No newline at end of file |
| 38 | + ignored: /authserver/** | |
| 33 | 39 | \ No newline at end of file | ... | ... |
cloud/user_search/src/main/java/com/sincere/userSearch/controller/UserController.java
| ... | ... | @@ -40,8 +40,8 @@ public class UserController { |
| 40 | 40 | */ |
| 41 | 41 | @ApiOperation("根据userId 获取用户信息") |
| 42 | 42 | @RequestMapping(value = "getUserInfo" , method = RequestMethod.GET) |
| 43 | - public String getUserInfo(){ | |
| 44 | - return "aa" ; | |
| 43 | + public String getUserInfo(UserInfo userInfo){ | |
| 44 | + return userInfo.getUserId() ; | |
| 45 | 45 | } |
| 46 | 46 | |
| 47 | 47 | public void getUserId(){ | ... | ... |
cloud/user_search/src/main/resources/application.yaml
| ... | ... | @@ -12,7 +12,7 @@ spring: |
| 12 | 12 | ##mybatis |
| 13 | 13 | mybatis: |
| 14 | 14 | mapper-locations: classpath:mapper/*.xml |
| 15 | - type-aliases-package: com.sincere.quartz.mapper | |
| 15 | + type-aliases-package: com.sincere.userSearch.mapper | |
| 16 | 16 | check-config-location: true |
| 17 | 17 | ribbon: |
| 18 | 18 | ReadTimeout: 50000 | ... | ... |