Commit 2c45cb04 by tangyi

增加OAuth2.0终端管理、调整项目结构

parent 02ab8671
...@@ -58,6 +58,7 @@ ...@@ -58,6 +58,7 @@
- 部门管理:部门信息增删改查 - 部门管理:部门信息增删改查
- 角色管理:角色信息增删改查、分配权限 - 角色管理:角色信息增删改查、分配权限
- 菜单管理:菜单信息增删改查、导入导出 - 菜单管理:菜单信息增删改查、导入导出
- 终端管理:管理OAuth2.0的客户端,如client_id、client_secret、access_token有效时间等
系统监控:监控服务、日志等 系统监控:监控服务、日志等
- 日志监控:查看系统日志 - 日志监控:查看系统日志
......
...@@ -122,5 +122,10 @@ public class CommonConstant { ...@@ -122,5 +122,10 @@ public class CommonConstant {
* 参数校验失败 * 参数校验失败
*/ */
public static final String IllEGAL_ARGUMENT = "参数校验失败!"; public static final String IllEGAL_ARGUMENT = "参数校验失败!";
/**
* 保存code的前缀
*/
public static final String DEFAULT_CODE_KEY = "DEFAULT_CODE_KEY";
} }
package com.github.tangyi.common.core.constant; package com.github.tangyi.common.security.constant;
/** /**
* @author tangyi * @author tangyi
...@@ -17,12 +17,12 @@ public class SecurityConstant { ...@@ -17,12 +17,12 @@ public class SecurityConstant {
public static final String TOKEN_USER_DETAIL = "token-user-detail"; public static final String TOKEN_USER_DETAIL = "token-user-detail";
/** /**
* 保存code的前缀 * 默认生成图形验证码过期时间
*/ */
public static final String DEFAULT_CODE_KEY = "DEFAULT_CODE_KEY"; public static final int DEFAULT_IMAGE_EXPIRE = 60;
/** /**
* 默认生成图形验证码过期时间 * oauth 客户端信息
*/ */
public static final int DEFAULT_IMAGE_EXPIRE = 60; public static final String CLIENT_DETAILS_KEY = "exam_oauth:client:details";
} }
package com.github.tangyi.common.security.core;
import org.springframework.security.oauth2.common.exceptions.InvalidClientException;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.security.oauth2.provider.client.JdbcClientDetailsService;
import javax.sql.DataSource;
/**
* jdbc客户端service
*
* @author tangyi
* @date 2019/3/30 23:30
*/
public class ClientDetailsServiceImpl extends JdbcClientDetailsService {
public ClientDetailsServiceImpl(DataSource dataSource) {
super(dataSource);
}
/**
* 重写方法
*
* @param clientId clientId
* @return ClientDetails
* @author tangyi
* @date 2019/03/30 23:31
*/
@Override
public ClientDetails loadClientByClientId(String clientId) throws InvalidClientException {
return super.loadClientByClientId(clientId);
}
}
package com.github.tangyi.common.security.properties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
/**
* security oauth2相关配置
*
* @author tangyi
* @date 2019-03-14 16:48
*/
@Configuration
@ConfigurationProperties(prefix = "security.properties")
public class SecurityConfigProperties {
private String clientId;
private String clientSecret;
private String grantTypePassword;
private String authorizationCode;
private String refreshToken;
private String implicit;
private String scopeRead;
private String scopeWrite;
private String trust;
private int accessTokenValiditySeconds;
private int refreshTokenValiditySeconds;
public String getClientId() {
return clientId;
}
public void setClientId(String clientId) {
this.clientId = clientId;
}
public String getClientSecret() {
return clientSecret;
}
public void setClientSecret(String clientSecret) {
this.clientSecret = clientSecret;
}
public String getGrantTypePassword() {
return grantTypePassword;
}
public void setGrantTypePassword(String grantTypePassword) {
this.grantTypePassword = grantTypePassword;
}
public String getAuthorizationCode() {
return authorizationCode;
}
public void setAuthorizationCode(String authorizationCode) {
this.authorizationCode = authorizationCode;
}
public String getRefreshToken() {
return refreshToken;
}
public void setRefreshToken(String refreshToken) {
this.refreshToken = refreshToken;
}
public String getImplicit() {
return implicit;
}
public void setImplicit(String implicit) {
this.implicit = implicit;
}
public String getScopeRead() {
return scopeRead;
}
public void setScopeRead(String scopeRead) {
this.scopeRead = scopeRead;
}
public String getScopeWrite() {
return scopeWrite;
}
public void setScopeWrite(String scopeWrite) {
this.scopeWrite = scopeWrite;
}
public String getTrust() {
return trust;
}
public void setTrust(String trust) {
this.trust = trust;
}
public int getAccessTokenValiditySeconds() {
return accessTokenValiditySeconds;
}
public void setAccessTokenValiditySeconds(int accessTokenValiditySeconds) {
this.accessTokenValiditySeconds = accessTokenValiditySeconds;
}
public int getRefreshTokenValiditySeconds() {
return refreshTokenValiditySeconds;
}
public void setRefreshTokenValiditySeconds(int refreshTokenValiditySeconds) {
this.refreshTokenValiditySeconds = refreshTokenValiditySeconds;
}
}
server: server:
port: 8081 port: 8081
spring: spring:
datasource:
url: jdbc:mysql://${MYSQL_HOST:192.168.0.144}:${MYSQL_PORT:3306}/microservice-auth?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC
username: ${MYSQL_USERNAME:platform}
password: ${MYSQL_PASSWORD:11}
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.jdbc.Driver
redis: redis:
host: ${REDIS_HOST:localhost} host: ${REDIS_HOST:localhost}
port: ${REDIS_PORT:6379} port: ${REDIS_PORT:6379}
rabbitmq:
host: ${RABBIT_HOST:localhost}
port: ${RABBIT_PORT:5672}
username: guest
password: guest
boot: boot:
admin: admin:
client: client:
url: http://${ADMIN_HOST:localhost}:${ADMIN_PORT:8085}/admin url: http://${ADMIN_HOST:localhost}:${ADMIN_PORT:8085}/admin
username: ${ADMIN_USERNAME:admin} username: ${ADMIN_USERNAME:admin}
password: ${ADMIN_PASSWORD:11} password: ${ADMIN_PASSWORD:11}
instance: instance:
service-base-url: http://localhost:${server.port} service-base-url: http://localhost:${server.port}
# sleuth 配置 # sleuth 配置
sleuth: sleuth:
web: web:
...@@ -23,21 +34,6 @@ spring: ...@@ -23,21 +34,6 @@ spring:
zipkin: zipkin:
base-url: http://localhost:9411 # 指定了Zipkin服务器的地址 base-url: http://localhost:9411 # 指定了Zipkin服务器的地址
security:
properties:
client-id: spring-microservice-exam-client
# spring-microservice-exam-secret
client-secret: $2a$10$etIT5xZXGY.g8/C.67lvX.N2PyvbEG1y0gGjATtp7LMsingWcd.1i
grant-type-password: password
authorization-code: authorization_code
refresh-token: refresh_token
implicit: implicit
scope-read: read
scope-write: write
trust: trust
access-token-validity-seconds: 3600 # access_token有效时间
refresh-token-validity-seconds: 21600 # refresh_token有效时间
feign: feign:
hystrix: hystrix:
enabled: true enabled: true
...@@ -61,6 +57,15 @@ management: ...@@ -61,6 +57,15 @@ management:
health: health:
show-details: ALWAYS show-details: ALWAYS
mybatis:
mapperLocations: classpath:mapper/*.xml
configLocation: classpath:/mybatis-config.xml
pagehelper:
helperDialect: mysql
reasonable: true
supportMethodsArguments: true
params: count=countSql
ignore: ignore:
urls: urls:
- / - /
...@@ -87,6 +92,8 @@ ignore: ...@@ -87,6 +92,8 @@ ignore:
- /loggers/** - /loggers/**
- /mobile/token - /mobile/token
mobile:
token: test
logging: logging:
level: level:
root: info root: info
......
...@@ -10,14 +10,19 @@ spring: ...@@ -10,14 +10,19 @@ spring:
redis: redis:
host: ${REDIS_HOST:localhost} host: ${REDIS_HOST:localhost}
port: ${REDIS_PORT:6379} port: ${REDIS_PORT:6379}
rabbitmq:
host: ${RABBIT_HOST:localhost}
port: ${RABBIT_PORT:5672}
username: guest
password: guest
boot: boot:
admin: admin:
client: client:
url: http://${ADMIN_HOST:localhost}:${ADMIN_PORT:8085}/admin url: http://${ADMIN_HOST:localhost}:${ADMIN_PORT:8085}/admin
username: ${ADMIN_USERNAME:admin} username: ${ADMIN_USERNAME:admin}
password: ${ADMIN_PASSWORD:11} password: ${ADMIN_PASSWORD:11}
instance: instance:
service-base-url: http://localhost:${server.port} service-base-url: http://localhost:${server.port}
# sleuth 配置 # sleuth 配置
sleuth: sleuth:
web: web:
...@@ -31,8 +36,8 @@ spring: ...@@ -31,8 +36,8 @@ spring:
security: security:
oauth2: oauth2:
client: client:
clientId: spring-microservice-exam-client clientId: web_app
clientSecret: $2a$10$etIT5xZXGY.g8/C.67lvX.N2PyvbEG1y0gGjATtp7LMsingWcd.1i clientSecret: $2a$10$S84wOzmAw4wqYBzAqNtmPOx1ZRWdDl9omm/W8T1hhW8S9EK2u57xG
accessTokenUri: http://${AUTH_SERVICE_HOST:localhost}:${AUTH_SERVICE_PORT:8000}/api/auth/oauth/token accessTokenUri: http://${AUTH_SERVICE_HOST:localhost}:${AUTH_SERVICE_PORT:8000}/api/auth/oauth/token
grant-type: password grant-type: password
scope: read scope: read
......
...@@ -10,8 +10,8 @@ spring: ...@@ -10,8 +10,8 @@ spring:
url: http://${ADMIN_HOST:localhost}:${ADMIN_PORT:8085}/admin url: http://${ADMIN_HOST:localhost}:${ADMIN_PORT:8085}/admin
username: ${ADMIN_USERNAME:admin} username: ${ADMIN_USERNAME:admin}
password: ${ADMIN_PASSWORD:11} password: ${ADMIN_PASSWORD:11}
instance: instance:
service-base-url: http://localhost:${server.port} service-base-url: http://localhost:${server.port}
# sleuth 配置 # sleuth 配置
sleuth: sleuth:
web: web:
...@@ -80,6 +80,7 @@ swagger: ...@@ -80,6 +80,7 @@ swagger:
providers: providers:
- user-service - user-service
- exam-service - exam-service
- auth-service
logging: logging:
level: level:
......
...@@ -17,8 +17,10 @@ spring: ...@@ -17,8 +17,10 @@ spring:
client: client:
enabled: false enabled: false
auto-registration: false auto-registration: false
instance: instance:
service-base-url: http://localhost:${server.port} service-base-url: http://localhost:${server.port}
discovery:
ignored-services: consul # 或略consul服务
# sleuth 配置 # sleuth 配置
sleuth: sleuth:
web: web:
......
...@@ -10,14 +10,19 @@ spring: ...@@ -10,14 +10,19 @@ spring:
redis: redis:
host: ${REDIS_HOST:localhost} host: ${REDIS_HOST:localhost}
port: ${REDIS_PORT:6379} port: ${REDIS_PORT:6379}
rabbitmq:
host: ${RABBIT_HOST:localhost}
port: ${RABBIT_PORT:5672}
username: guest
password: guest
boot: boot:
admin: admin:
client: client:
url: http://${ADMIN_HOST:localhost}:${ADMIN_PORT:8085}/admin url: http://${ADMIN_HOST:localhost}:${ADMIN_PORT:8085}/admin
username: ${ADMIN_USERNAME:admin} username: ${ADMIN_USERNAME:admin}
password: ${ADMIN_PASSWORD:11} password: ${ADMIN_PASSWORD:11}
instance: instance:
service-base-url: http://localhost:${server.port} service-base-url: http://localhost:${server.port}
# sleuth 配置 # sleuth 配置
sleuth: sleuth:
web: web:
...@@ -31,8 +36,8 @@ spring: ...@@ -31,8 +36,8 @@ spring:
security: security:
oauth2: oauth2:
client: client:
clientId: spring-microservice-exam-client clientId: web_app
clientSecret: $2a$10$etIT5xZXGY.g8/C.67lvX.N2PyvbEG1y0gGjATtp7LMsingWcd.1i clientSecret: $2a$10$S84wOzmAw4wqYBzAqNtmPOx1ZRWdDl9omm/W8T1hhW8S9EK2u57xG
accessTokenUri: http://${AUTH_SERVICE_HOST:localhost}:${AUTH_SERVICE_PORT:8000}/api/auth/oauth/token accessTokenUri: http://${AUTH_SERVICE_HOST:localhost}:${AUTH_SERVICE_PORT:8000}/api/auth/oauth/token
grant-type: password grant-type: password
scope: read scope: read
...@@ -118,7 +123,7 @@ ignore: ...@@ -118,7 +123,7 @@ ignore:
- /metrics/** - /metrics/**
- /loggers/** - /loggers/**
- /mobile/token - /mobile/token
- /bus/refresh
logging: logging:
level: level:
......
/*
Navicat Premium Data Transfer
Source Server : 144
Source Server Type : MySQL
Source Server Version : 50710
Source Host : 192.168.0.144:3306
Source Schema : microservice-auth
Target Server Type : MySQL
Target Server Version : 50710
File Encoding : 65001
Date: 31/03/2019 15:16:50
*/
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for oauth_client_details
-- ----------------------------
DROP TABLE IF EXISTS `oauth_client_details`;
CREATE TABLE `oauth_client_details` (
`id` varchar(64) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '主键',
`client_id` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT 'client_id',
`resource_ids` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT 'resource_ids',
`client_secret_plain_text` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '密钥明文',
`client_secret` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT 'client_secret',
`scope` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '授权范围',
`authorized_grant_types` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '授权类型',
`web_server_redirect_uri` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`authorities` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`access_token_validity` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT 'access_token有效时间',
`refresh_token_validity` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT 'refresh_token有效时间',
`additional_information` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`autoapprove` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`creator` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '创建人',
`create_date` varchar(64) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '创建时间',
`modifier` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '修改人',
`modify_date` varchar(64) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '修改时间',
`del_flag` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '删除标记',
`application_code` varchar(64) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '系统编号',
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of oauth_client_details
-- ----------------------------
INSERT INTO `oauth_client_details` VALUES ('471037a0c1be4df99b40e3f84141cc56', 'web_app', NULL, 'spring-microservice-exam-secret', '$2a$10$S84wOzmAw4wqYBzAqNtmPOx1ZRWdDl9omm/W8T1hhW8S9EK2u57xG', 'read,write', 'password,authorization_code,refresh_token,implicit', NULL, NULL, '3600', '21600', NULL, NULL, 'admin', '2019-03-30 23:43:07', 'admin', '2019-03-31 15:06:55', '0', 'EXAM');
SET FOREIGN_KEY_CHECKS = 1;
This source diff could not be displayed because it is too large. You can view the blob instead.
doc/images/deploy/config.png

99.7 KB | W: | H:

doc/images/deploy/config.png

88 KB | W: | H:

doc/images/deploy/config.png
doc/images/deploy/config.png
doc/images/deploy/config.png
doc/images/deploy/config.png
  • 2-up
  • Swipe
  • Onion skin
doc/images/deploy/config_fdfs.png

90.3 KB | W: | H:

doc/images/deploy/config_fdfs.png

127 KB | W: | H:

doc/images/deploy/config_fdfs.png
doc/images/deploy/config_fdfs.png
doc/images/deploy/config_fdfs.png
doc/images/deploy/config_fdfs.png
  • 2-up
  • Swipe
  • Onion skin
doc/images/deploy/config_redis.png

69.1 KB | W: | H:

doc/images/deploy/config_redis.png

88.2 KB | W: | H:

doc/images/deploy/config_redis.png
doc/images/deploy/config_redis.png
doc/images/deploy/config_redis.png
doc/images/deploy/config_redis.png
  • 2-up
  • Swipe
  • Onion skin
...@@ -44,6 +44,8 @@ fastDfs的IP和端口号: ...@@ -44,6 +44,8 @@ fastDfs的IP和端口号:
`/doc/deploy/mysql/microservice-user.sql` `/doc/deploy/mysql/microservice-user.sql`
`/doc/deploy/mysql/microservice-exam.sql` `/doc/deploy/mysql/microservice-exam.sql`
`/doc/deploy/mysql/microservice-auth.sql`
#### 启动后端项目 #### 启动后端项目
......
...@@ -12,11 +12,12 @@ common -- 系统公共模块 ...@@ -12,11 +12,12 @@ common -- 系统公共模块
service-api -- 服务api公共模块 service-api -- 服务api公共模块
├── user-api -- 用户服务api ├── user-api -- 用户服务api
└── exam-api -- 考试服务api └── exam-api -- 考试服务api
service-api-impl -- 服务api模块实现
├── auth-service -- 授权服务(OAuth2.0)
├── user-service -- 用户服务
└── exam-service -- 考试服务
config-service -- 配置中心(本地仓库) config-service -- 配置中心(本地仓库)
gateway-service -- 网关(动态路由) gateway-service -- 网关(动态路由)
auth-service -- 授权服务(OAuth2.0)
user-service -- 用户服务
exam-service -- 考试服务
monitor-service -- spring boot amdin 监控服务 monitor-service -- spring boot amdin 监控服务
``` ```
......
...@@ -5,6 +5,7 @@ import org.springframework.boot.autoconfigure.SpringBootApplication; ...@@ -5,6 +5,7 @@ import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker; import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.ComponentScan;
@EnableDiscoveryClient @EnableDiscoveryClient
...@@ -12,6 +13,8 @@ import org.springframework.context.annotation.ComponentScan; ...@@ -12,6 +13,8 @@ import org.springframework.context.annotation.ComponentScan;
// 配置包扫描,排查Swagger配置 // 配置包扫描,排查Swagger配置
@ComponentScan(basePackages = {"com.github.tangyi"}) @ComponentScan(basePackages = {"com.github.tangyi"})
@EnableCircuitBreaker @EnableCircuitBreaker
// 动态刷新
@RefreshScope
public class GatewayServiceApplication { public class GatewayServiceApplication {
public static void main(String[] args) { public static void main(String[] args) {
......
package com.github.tangyi.gateway.filters; package com.github.tangyi.gateway.filters;
import cn.hutool.core.util.StrUtil; import cn.hutool.core.util.StrUtil;
import com.github.tangyi.common.core.constant.SecurityConstant; import com.github.tangyi.common.core.constant.CommonConstant;
import com.github.tangyi.common.core.exceptions.InvalidValidateCodeException; import com.github.tangyi.common.core.exceptions.InvalidValidateCodeException;
import com.github.tangyi.common.core.exceptions.ValidateCodeExpiredException; import com.github.tangyi.common.core.exceptions.ValidateCodeExpiredException;
import com.github.tangyi.gateway.constants.GatewayConstant; import com.github.tangyi.gateway.constants.GatewayConstant;
...@@ -74,7 +74,7 @@ public class ValidateCodeFilter implements GlobalFilter, Ordered { ...@@ -74,7 +74,7 @@ public class ValidateCodeFilter implements GlobalFilter, Ordered {
String randomStr = params.getFirst("randomStr"); String randomStr = params.getFirst("randomStr");
if (StrUtil.isBlank(randomStr)) if (StrUtil.isBlank(randomStr))
randomStr = params.getFirst("mobile"); randomStr = params.getFirst("mobile");
String key = SecurityConstant.DEFAULT_CODE_KEY + randomStr; String key = CommonConstant.DEFAULT_CODE_KEY + randomStr;
// 验证码过期 // 验证码过期
if (!redisTemplate.hasKey(key)) if (!redisTemplate.hasKey(key))
throw new ValidateCodeExpiredException(EXPIRED_ERROR); throw new ValidateCodeExpiredException(EXPIRED_ERROR);
......
...@@ -4,6 +4,7 @@ import de.codecentric.boot.admin.server.config.EnableAdminServer; ...@@ -4,6 +4,7 @@ import de.codecentric.boot.admin.server.config.EnableAdminServer;
import org.springframework.boot.SpringApplication; import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.cloud.netflix.hystrix.dashboard.EnableHystrixDashboard; import org.springframework.cloud.netflix.hystrix.dashboard.EnableHystrixDashboard;
import org.springframework.cloud.netflix.turbine.EnableTurbine; import org.springframework.cloud.netflix.turbine.EnableTurbine;
...@@ -12,6 +13,8 @@ import org.springframework.cloud.netflix.turbine.EnableTurbine; ...@@ -12,6 +13,8 @@ import org.springframework.cloud.netflix.turbine.EnableTurbine;
@EnableHystrixDashboard @EnableHystrixDashboard
@EnableTurbine @EnableTurbine
@EnableAdminServer @EnableAdminServer
// 动态刷新
@RefreshScope
public class MonitorServiceApplication { public class MonitorServiceApplication {
public static void main(String[] args) { public static void main(String[] args) {
......
...@@ -27,6 +27,9 @@ public class WebSecurityConfig extends WebSecurityConfigurerAdapter { ...@@ -27,6 +27,9 @@ public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
successHandler.setAlwaysUseDefaultTargetUrl(true); successHandler.setAlwaysUseDefaultTargetUrl(true);
successHandler.setDefaultTargetUrl(adminContextPath + "/"); successHandler.setDefaultTargetUrl(adminContextPath + "/");
// 解决spring boot不允许加载iframe问题
http.headers().frameOptions().disable();
http.authorizeRequests() http.authorizeRequests()
.antMatchers("/actuator/**", "/hystrix/**","/hystrix","*.stream").permitAll() .antMatchers("/actuator/**", "/hystrix/**","/hystrix","*.stream").permitAll()
.antMatchers(adminContextPath + "/assets/**").permitAll() .antMatchers(adminContextPath + "/assets/**").permitAll()
......
...@@ -23,12 +23,10 @@ ...@@ -23,12 +23,10 @@
<modules> <modules>
<module>config-service</module> <module>config-service</module>
<module>gateway-service</module> <module>gateway-service</module>
<module>auth-service</module>
<module>user-service</module>
<module>exam-service</module>
<module>common</module> <module>common</module>
<module>monitor-service</module> <module>monitor-service</module>
<module>service-api</module> <module>service-api</module>
<module>service-api-impl</module>
<module>zipkin-service</module> <module>zipkin-service</module>
</modules> </modules>
...@@ -58,7 +56,7 @@ ...@@ -58,7 +56,7 @@
<swagger.version>2.9.2</swagger.version> <swagger.version>2.9.2</swagger.version>
<driud.version>1.1.4</driud.version> <driud.version>1.1.4</driud.version>
<fastdfs-client.version>1.26.5</fastdfs-client.version> <fastdfs-client.version>1.26.5</fastdfs-client.version>
<mysql.connector.version>8.0.13</mysql.connector.version>
<!-- common--> <!-- common-->
<commons-io.version>2.6</commons-io.version> <commons-io.version>2.6</commons-io.version>
<commons-lang3.version>3.7</commons-lang3.version> <commons-lang3.version>3.7</commons-lang3.version>
...@@ -180,6 +178,13 @@ ...@@ -180,6 +178,13 @@
<version>${project.version}</version> <version>${project.version}</version>
</dependency> </dependency>
<!-- auth-api -->
<dependency>
<groupId>com.github.tangyi</groupId>
<artifactId>auth-api</artifactId>
<version>${project.version}</version>
</dependency>
<!-- exam-api --> <!-- exam-api -->
<dependency> <dependency>
<groupId>com.github.tangyi</groupId> <groupId>com.github.tangyi</groupId>
...@@ -213,6 +218,41 @@ ...@@ -213,6 +218,41 @@
<artifactId>springfox-swagger-ui</artifactId> <artifactId>springfox-swagger-ui</artifactId>
<version>${swagger.version}</version> <version>${swagger.version}</version>
</dependency> </dependency>
<!--MySQL-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.connector.version}</version>
</dependency>
<!-- druid阿里巴巴数据库连接池 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>${driud.version}</version>
</dependency>
<!-- mybatis -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>${mybatis.version}</version>
</dependency>
<!--fastDfs-->
<dependency>
<groupId>com.github.tobato</groupId>
<artifactId>fastdfs-client</artifactId>
<version>${fastdfs-client.version}</version>
</dependency>
<!-- 验证码 -->
<dependency>
<groupId>com.github.axet</groupId>
<artifactId>kaptcha</artifactId>
<version>${kaptcha.version}</version>
</dependency>
</dependencies> </dependencies>
</dependencyManagement> </dependencyManagement>
......
...@@ -4,7 +4,7 @@ ...@@ -4,7 +4,7 @@
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<parent> <parent>
<groupId>com.github.tangyi</groupId> <groupId>com.github.tangyi</groupId>
<artifactId>spring-microservice-exam</artifactId> <artifactId>service-api-impl</artifactId>
<version>2.0-SNAPSHOT</version> <version>2.0-SNAPSHOT</version>
</parent> </parent>
<artifactId>auth-service</artifactId> <artifactId>auth-service</artifactId>
...@@ -24,18 +24,36 @@ ...@@ -24,18 +24,36 @@
<artifactId>common-security</artifactId> <artifactId>common-security</artifactId>
</dependency> </dependency>
<!-- common-log -->
<dependency>
<groupId>com.github.tangyi</groupId>
<artifactId>common-log</artifactId>
</dependency>
<!-- user-api --> <!-- user-api -->
<dependency> <dependency>
<groupId>com.github.tangyi</groupId> <groupId>com.github.tangyi</groupId>
<artifactId>user-api</artifactId> <artifactId>user-api</artifactId>
</dependency> </dependency>
<!-- auth-api -->
<dependency>
<groupId>com.github.tangyi</groupId>
<artifactId>auth-api</artifactId>
</dependency>
<!-- exam-api --> <!-- exam-api -->
<dependency> <dependency>
<groupId>com.github.tangyi</groupId> <groupId>com.github.tangyi</groupId>
<artifactId>exam-api</artifactId> <artifactId>exam-api</artifactId>
</dependency> </dependency>
<!-- web 服务 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- 配置客户端 --> <!-- 配置客户端 -->
<dependency> <dependency>
<groupId>org.springframework.cloud</groupId> <groupId>org.springframework.cloud</groupId>
...@@ -47,17 +65,40 @@ ...@@ -47,17 +65,40 @@
<artifactId>spring-security-oauth2-autoconfigure</artifactId> <artifactId>spring-security-oauth2-autoconfigure</artifactId>
</dependency> </dependency>
<!-- web 服务 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- 管理中心插件 --> <!-- 管理中心插件 -->
<dependency> <dependency>
<groupId>de.codecentric</groupId> <groupId>de.codecentric</groupId>
<artifactId>spring-boot-admin-starter-client</artifactId> <artifactId>spring-boot-admin-starter-client</artifactId>
</dependency> </dependency>
<!--MySQL-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- druid阿里巴巴数据库连接池 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
</dependency>
<!-- mybatis -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
</dependency>
<!-- swagger -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
</dependency>
</dependencies> </dependencies>
<build> <build>
......
...@@ -9,11 +9,11 @@ import org.springframework.cloud.openfeign.EnableFeignClients; ...@@ -9,11 +9,11 @@ import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.ComponentScan;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer; import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
@SpringBootApplication
@EnableDiscoveryClient @EnableDiscoveryClient
@EnableAuthorizationServer @EnableAuthorizationServer
// 扫描api包里的FeignClient // 扫描api包里的FeignClient
@EnableFeignClients(basePackages = {"com.github.tangyi"}) @EnableFeignClients(basePackages = {"com.github.tangyi"})
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
@ComponentScan(basePackages = {"com.github.tangyi"}) @ComponentScan(basePackages = {"com.github.tangyi"})
@EnableCircuitBreaker @EnableCircuitBreaker
public class AuthServiceApplication { public class AuthServiceApplication {
......
package com.github.tangyi.auth.config; package com.github.tangyi.auth.config;
import com.github.tangyi.common.security.core.ClientDetailsServiceImpl;
import com.github.tangyi.common.security.exceptions.CustomOauthException; import com.github.tangyi.common.security.exceptions.CustomOauthException;
import com.github.tangyi.common.security.properties.SecurityConfigProperties;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
...@@ -12,11 +13,13 @@ import org.springframework.security.oauth2.common.exceptions.OAuth2Exception; ...@@ -12,11 +13,13 @@ import org.springframework.security.oauth2.common.exceptions.OAuth2Exception;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer; import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter; import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer; import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.token.TokenStore; import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter; import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.KeyStoreKeyFactory; import org.springframework.security.oauth2.provider.token.store.KeyStoreKeyFactory;
import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore; import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore;
import org.springframework.stereotype.Component;
import javax.sql.DataSource;
/** /**
* 授权服务器配置 * 授权服务器配置
...@@ -24,18 +27,18 @@ import org.springframework.stereotype.Component; ...@@ -24,18 +27,18 @@ import org.springframework.stereotype.Component;
* @author tangyi * @author tangyi
* @date 2019-03-14 11:40 * @date 2019-03-14 11:40
*/ */
@Component @Configuration
public class CustomAuthorizationServerConfigurer extends AuthorizationServerConfigurerAdapter { public class CustomAuthorizationServerConfigurer extends AuthorizationServerConfigurerAdapter {
@Autowired @Autowired
private SecurityConfigProperties properties;
@Autowired
private AuthenticationManager authenticationManager; private AuthenticationManager authenticationManager;
@Autowired @Autowired
private RedisConnectionFactory redisConnectionFactory; private RedisConnectionFactory redisConnectionFactory;
@Autowired
private DataSource dataSource;
@Bean @Bean
public TokenStore tokenStore() { public TokenStore tokenStore() {
// 将token存储到redis // 将token存储到redis
...@@ -50,20 +53,15 @@ public class CustomAuthorizationServerConfigurer extends AuthorizationServerConf ...@@ -50,20 +53,15 @@ public class CustomAuthorizationServerConfigurer extends AuthorizationServerConf
return converter; return converter;
} }
@Bean
public ClientDetailsService clientDetails() {
return new ClientDetailsServiceImpl(dataSource);
}
@Override @Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception { public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients // 从数据库加载客户端信息
.inMemory() clients.withClientDetails(clientDetails());
.withClient(properties.getClientId())
.secret(properties.getClientSecret())
.authorizedGrantTypes(
properties.getGrantTypePassword(),
properties.getAuthorizationCode(),
properties.getRefreshToken(),
properties.getImplicit())
.scopes(properties.getScopeRead(), properties.getScopeWrite())
.accessTokenValiditySeconds(properties.getAccessTokenValiditySeconds())
.refreshTokenValiditySeconds(properties.getRefreshTokenValiditySeconds());
} }
@Override @Override
......
package com.github.tangyi.auth.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.transaction.annotation.TransactionManagementConfigurer;
import javax.sql.DataSource;
/**
* @author tangyi
* @date 2019/3/30 23:48
*/
@Configuration
@EnableTransactionManagement
public class MybatisConfig implements TransactionManagementConfigurer {
private final DataSource dataSource;
@Autowired
public MybatisConfig(DataSource dataSource) {
this.dataSource = dataSource;
}
@Override
public PlatformTransactionManager annotationDrivenTransactionManager() {
return new DataSourceTransactionManager(dataSource);
}
}
package com.github.tangyi.auth.config;
import io.swagger.annotations.ApiOperation;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.ParameterBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.schema.ModelRef;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.service.Parameter;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import java.util.ArrayList;
import java.util.List;
/**
* Swagger配置
*
* @author tangyi
* @date 2019/3/26 16:26
*/
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket createRestApi() {
ParameterBuilder tokenBuilder = new ParameterBuilder();
List<Parameter> parameterList = new ArrayList<>();
tokenBuilder.name("Authorization")
.defaultValue("去其他请求中获取heard中token参数")
.description("令牌")
.modelRef(new ModelRef("string"))
.parameterType("header")
.required(true).build();
parameterList.add(tokenBuilder.build());
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
.paths(PathSelectors.any())
.build()
.globalOperationParameters(parameterList);
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("Swagger API")
.description("https://gitee.com/wells2333/spring-microservice-exam")
.termsOfServiceUrl("https://gitee.com/wells2333/spring-microservice-exam")
.contact(new Contact("tangyi","https://gitee.com/wells2333/spring-microservice-exam","1633736729@qq.com"))
.version("2.0")
.build();
}
}
package com.github.tangyi.auth.controller; package com.github.tangyi.auth.controller;
import com.github.tangyi.common.core.constant.SecurityConstant; import com.github.tangyi.common.security.constant.SecurityConstant;
import com.github.tangyi.common.core.model.ResponseBean; import com.github.tangyi.common.core.model.ResponseBean;
import com.github.tangyi.common.core.web.BaseController; import com.github.tangyi.common.core.web.BaseController;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
......
package com.github.tangyi.auth.controller;
import com.github.pagehelper.PageInfo;
import com.github.tangyi.auth.api.module.OauthClientDetails;
import com.github.tangyi.auth.service.OauthClientDetailsService;
import com.github.tangyi.common.core.constant.CommonConstant;
import com.github.tangyi.common.core.model.ResponseBean;
import com.github.tangyi.common.core.utils.PageUtil;
import com.github.tangyi.common.core.utils.SysUtil;
import com.github.tangyi.common.core.web.BaseController;
import com.github.tangyi.common.log.annotation.Log;
import com.github.tangyi.common.security.utils.SecurityUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;
import java.util.List;
/**
* Oauth2客户端信息管理
*
* @author tangyi
* @date 2019/3/30 16:49
*/
@Api("Oauth2客户端信息管理")
@RestController
@RequestMapping("/v1/client")
public class OauthClientDetailsController extends BaseController {
@Autowired
private OauthClientDetailsService oauthClientDetailsService;
@Autowired
private BCryptPasswordEncoder bCryptPasswordEncoder;
/**
* 根据ID获取
*
* @param id id
* @return ResponseBean
* @author tangyi
* @date 2019/03/30 16:53
*/
@ApiOperation(value = "获取客户端信息", notes = "根据客户端id获取客户端详细信息")
@ApiImplicitParam(name = "id", value = "客户端ID", required = true, dataType = "String", paramType = "path")
@GetMapping("/{id}")
public ResponseBean<OauthClientDetails> oauthClient(@PathVariable String id) {
OauthClientDetails oauthClientDetails = new OauthClientDetails();
if (StringUtils.isNotBlank(id)) {
oauthClientDetails.setId(id);
oauthClientDetails = oauthClientDetailsService.get(oauthClientDetails);
}
return new ResponseBean<>(oauthClientDetails);
}
/**
* 分页查询
*
* @param pageNum pageNum
* @param pageSize pageSize
* @param sort sort
* @param order order
* @param oauthClientDetails oauthClientDetails
* @return PageInfo
* @author tangyi
* @date 2019/03/30 16:54
*/
@RequestMapping("clientList")
@PreAuthorize("hasAnyRole('ROLE_USER', 'ROLE_ADMIN')")
@ApiOperation(value = "获取客户端列表")
@ApiImplicitParams({
@ApiImplicitParam(name = "pageNum", value = "分页页码", defaultValue = CommonConstant.PAGE_NUM_DEFAULT, dataType = "String"),
@ApiImplicitParam(name = "pageSize", value = "分页大小", defaultValue = CommonConstant.PAGE_SIZE_DEFAULT, dataType = "String"),
@ApiImplicitParam(name = "sort", value = "排序字段", defaultValue = CommonConstant.PAGE_SORT_DEFAULT, dataType = "String"),
@ApiImplicitParam(name = "order", value = "排序方向", defaultValue = CommonConstant.PAGE_ORDER_DEFAULT, dataType = "String"),
@ApiImplicitParam(name = "attachment", value = "客户端信息", dataType = "OauthClient")
})
public PageInfo<OauthClientDetails> oauthClientList(@RequestParam(value = "pageNum", required = false, defaultValue = CommonConstant.PAGE_NUM_DEFAULT) String pageNum,
@RequestParam(value = "pageSize", required = false, defaultValue = CommonConstant.PAGE_SIZE_DEFAULT) String pageSize,
@RequestParam(value = "sort", required = false, defaultValue = CommonConstant.PAGE_SORT_DEFAULT) String sort,
@RequestParam(value = "order", required = false, defaultValue = CommonConstant.PAGE_ORDER_DEFAULT) String order,
OauthClientDetails oauthClientDetails) {
return oauthClientDetailsService.findPage(PageUtil.pageInfo(pageNum, pageSize, sort, order), oauthClientDetails);
}
/**
* 查询客户端列表
*
* @param oauthClientDetails oauthClientDetails
* @return ResponseBean
* @author tangyi
* @date 2019/03/30 23:17
*/
@RequestMapping("clients")
@PreAuthorize("hasAnyRole('ROLE_USER', 'ROLE_ADMIN')")
@ApiOperation(value = "查询客户端列表", notes = "查询客户端列表")
@ApiImplicitParam(name = "oauthClient", value = "客户端实体oauthClient", required = true, dataType = "OauthClientDetails")
public ResponseBean<List<OauthClientDetails>> findOauthClientList(@RequestBody OauthClientDetails oauthClientDetails) {
return new ResponseBean<>(oauthClientDetailsService.findList(oauthClientDetails));
}
/**
* 创建客户端
*
* @param oauthClientDetails oauthClientDetails
* @return ResponseBean
* @author tangyi
* @date 2019/03/30 16:57
*/
@PostMapping
@PreAuthorize("hasAnyRole('ROLE_USER', 'ROLE_ADMIN')")
@ApiOperation(value = "创建客户端", notes = "创建客户端")
@ApiImplicitParam(name = "oauthClientDetails", value = "客户端实体oauthClientDetails", required = true, dataType = "OauthClientDetails")
@Log("新增客户端")
public ResponseBean<Boolean> oauthClient(@RequestBody OauthClientDetails oauthClientDetails) {
oauthClientDetails.setCommonValue(SecurityUtil.getCurrentUsername(), SysUtil.getSysCode());
// 加密密钥
oauthClientDetails.setClientSecret(bCryptPasswordEncoder.encode(oauthClientDetails.getClientSecretPlainText()));
return new ResponseBean<>(oauthClientDetailsService.insert(oauthClientDetails) > 0);
}
/**
* 修改客户端
*
* @param oauthClientDetails oauthClientDetails
* @return ResponseBean
* @author tangyi
* @date 2019/03/30 16:56
*/
@PutMapping
@PreAuthorize("hasAnyRole('ROLE_USER', 'ROLE_ADMIN')")
@ApiOperation(value = "更新客户端信息", notes = "根据客户端id更新客户端的基本信息")
@ApiImplicitParam(name = "oauthClientDetails", value = "客户端实体oauthClientDetails", required = true, dataType = "OauthClientDetails")
@Log("修改客户端")
public ResponseBean<Boolean> updateOauthClient(@RequestBody OauthClientDetails oauthClientDetails) {
oauthClientDetails.setCommonValue(SecurityUtil.getCurrentUsername(), SysUtil.getSysCode());
// 加密密钥
oauthClientDetails.setClientSecret(bCryptPasswordEncoder.encode(oauthClientDetails.getClientSecretPlainText()));
return new ResponseBean<>(oauthClientDetailsService.update(oauthClientDetails) > 0);
}
/**
* 根据id删除客户端
*
* @param id id
* @return ResponseBean
* @author tangyi
* @date 2019/03/30 16:59
*/
@DeleteMapping("/{id}")
@PreAuthorize("hasAnyRole('ROLE_USER', 'ROLE_ADMIN')")
@ApiOperation(value = "删除客户端", notes = "根据ID删除客户端")
@ApiImplicitParam(name = "id", value = "客户端ID", required = true, paramType = "path")
@Log("删除客户端")
public ResponseBean<Boolean> deleteOauthClient(@PathVariable String id) {
OauthClientDetails oauthClientDetails = new OauthClientDetails();
oauthClientDetails.setId(id);
oauthClientDetails.setNewRecord(false);
oauthClientDetails.setCommonValue(SecurityUtil.getCurrentUsername(), SysUtil.getSysCode());
return new ResponseBean<>(oauthClientDetailsService.delete(oauthClientDetails) > 0);
}
/**
* 批量删除
*
* @param oauthClientDetails oauthClientDetails
* @return ResponseBean
* @author tangyi
* @date 2019/03/30 17:01
*/
@PostMapping("/deleteAll")
@PreAuthorize("hasAnyRole('ROLE_USER', 'ROLE_ADMIN')")
@ApiOperation(value = "批量删除客户端", notes = "根据客户端id批量删除客户端")
@ApiImplicitParam(name = "oauthClientDetails", value = "客户端信息", dataType = "OauthClientDetails")
@Log("批量删除客户端")
public ResponseBean<Boolean> deleteAllOauthClient(@RequestBody OauthClientDetails oauthClientDetails) {
boolean success = false;
try {
if (StringUtils.isNotEmpty(oauthClientDetails.getIdString()))
success = oauthClientDetailsService.deleteAll(oauthClientDetails.getIdString().split(",")) > 0;
} catch (Exception e) {
logger.error("删除客户端失败!", e);
}
return new ResponseBean<>(success);
}
}
package com.github.tangyi.auth.controller;
import com.github.tangyi.common.core.model.ResponseBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @author tangyi
* @date 2019/3/30 14:40
*/
@RestController
// 动态刷新,修改配置后post请求/actuator/refresh
@RefreshScope
public class TestController {
@Value("${mobile.token}")
private String mobileToken;
@RequestMapping("/mobile/token")
public ResponseBean<String> mobileToken() {
return new ResponseBean<>(mobileToken);
}
}
package com.github.tangyi.auth.mapper;
import com.github.tangyi.auth.api.module.OauthClientDetails;
import com.github.tangyi.common.core.persistence.CrudMapper;
import org.apache.ibatis.annotations.Mapper;
/**
* Oauth2客户端mapper
*
* @author tangyi
* @date 2019/3/30 16:39
*/
@Mapper
public interface OauthClientDetailsMapper extends CrudMapper<OauthClientDetails> {
}
package com.github.tangyi.auth.service;
import com.github.tangyi.auth.api.module.OauthClientDetails;
import com.github.tangyi.auth.mapper.OauthClientDetailsMapper;
import com.github.tangyi.common.core.service.CrudService;
import org.springframework.stereotype.Service;
/**
* Oauth2客户端Service
*
* @author tangyi
* @date 2019/3/30 16:48
*/
@Service
public class OauthClientDetailsService extends CrudService<OauthClientDetailsMapper, OauthClientDetails> {
}
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.github.tangyi.auth.mapper.OauthClientDetailsMapper">
<resultMap id="oauthClientResultMap" type="com.github.tangyi.auth.api.module.OauthClientDetails">
<id column="id" property="id"/>
<result column="client_id" property="clientId"/>
<result column="resource_ids" property="resourceIds"/>
<result column="client_secret" property="clientSecret"/>
<result column="scope" property="scope"/>
<result column="authorized_grant_types" property="authorizedGrantTypes"/>
<result column="web_server_redirect_uri" property="webServerRedirectUri"/>
<result column="authorities" property="authorities"/>
<result column="access_token_validity" property="accessTokenValidity"/>
<result column="refresh_token_validity" property="refreshTokenValidity"/>
<result column="additional_information" property="additionalInformation"/>
<result column="autoapprove" property="autoapprove"/>
<result column="creator" property="creator"/>
<result column="create_date" property="createDate"/>
<result column="modifier" property="modifier"/>
<result column="modify_date" property="modifyDate"/>
<result column="del_flag" property="delFlag"/>
<result column="application_code" property="applicationCode"/>
</resultMap>
<sql id="oauthClientColumns">
a.id as "id",
a.client_id,
a.resource_ids,
a.client_secret_plain_text,
a.client_secret,
a.scope,
a.authorized_grant_types,
a.web_server_redirect_uri,
a.authorities,
a.access_token_validity,
a.refresh_token_validity,
a.additional_information,
a.autoapprove,
a.creator,
a.create_date,
a.modifier,
a.modify_date,
a.del_flag,
a.application_code
</sql>
<!-- where 条件 -->
<sql id="whereColumnList">
<if test="clientId != null and clientId != ''">
and a.client_id like #{clientId}
</if>
</sql>
<select id="get" resultMap="oauthClientResultMap">
SELECT
<include refid="oauthClientColumns"/>
FROM oauth_client_details a
WHERE a.id = #{id} and a.del_flag = 0
</select>
<select id="findList" resultMap="oauthClientResultMap">
SELECT
<include refid="oauthClientColumns"/>
FROM oauth_client_details a
WHERE a.del_flag = 0
<include refid="whereColumnList"/>
ORDER BY CREATE_DATE DESC
</select>
<select id="findListById" resultMap="oauthClientResultMap">
SELECT
<include refid="oauthClientColumns"/>
FROM oauth_client_details a
WHERE a.id IN
<foreach collection="ids" index="index" item="item" open="(" separator="," close=")">
#{item}
</foreach>
</select>
<insert id="insert">
INSERT INTO oauth_client_details (
id,
client_id,
resource_ids,
client_secret_plain_text,
client_secret,
scope,
authorized_grant_types,
web_server_redirect_uri,
authorities,
access_token_validity,
refresh_token_validity,
additional_information,
autoapprove,
creator,
create_date,
modifier,
modify_date,
del_flag,
application_code
) VALUES (
#{id},
#{clientId},
#{resourceIds},
#{clientSecretPlainText},
#{clientSecret},
#{scope},
#{authorizedGrantTypes},
#{webServerRedirectUri},
#{authorities},
#{accessTokenValidity},
#{refreshTokenValidity},
#{additionalInformation},
#{autoapprove},
#{creator},
#{createDate},
#{modifier},
#{modifyDate},
#{delFlag},
#{applicationCode}
)
</insert>
<update id="update">
UPDATE oauth_client_details SET
<if test="clientId != null">
client_id = #{clientId},
</if>
<if test="resourceIds != null">
resource_ids = #{resourceIds},
</if>
<if test="clientSecretPlainText != null">
client_secret_plain_text = #{clientSecretPlainText},
</if>
<if test="clientSecret != null">
client_secret = #{clientSecret},
</if>
<if test="scope != null">
scope = #{scope},
</if>
<if test="authorizedGrantTypes != null">
authorized_grant_types = #{authorizedGrantTypes},
</if>
<if test="webServerRedirectUri != null">
web_server_redirect_uri = #{webServerRedirectUri},
</if>
<if test="authorities != null">
authorities = #{authorities},
</if>
<if test="accessTokenValidity != null">
access_token_validity = #{accessTokenValidity},
</if>
<if test="refreshTokenValidity != null">
refresh_token_validity = #{refreshTokenValidity},
</if>
<if test="additionalInformation != null">
additional_information = #{additionalInformation},
</if>
<if test="autoapprove != null">
autoapprove = #{autoapprove},
</if>
<if test="delFlag != null">
del_flag = #{delFlag},
</if>
modifier = #{modifier},
modify_date = #{modifyDate}
WHERE id = #{id}
</update>
<delete id="delete">
UPDATE oauth_client_details SET
DEL_FLAG = 1
WHERE ID = #{id}
</delete>
<delete id="deleteAll">
UPDATE oauth_client_details SET
del_flag = 1
WHERE id in
<foreach item="item" index="index" collection="array" open="("
separator="," close=")"> #{item}
</foreach>
</delete>
</mapper>
...@@ -4,7 +4,7 @@ ...@@ -4,7 +4,7 @@
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<parent> <parent>
<groupId>com.github.tangyi</groupId> <groupId>com.github.tangyi</groupId>
<artifactId>spring-microservice-exam</artifactId> <artifactId>service-api-impl</artifactId>
<version>2.0-SNAPSHOT</version> <version>2.0-SNAPSHOT</version>
</parent> </parent>
<artifactId>exam-service</artifactId> <artifactId>exam-service</artifactId>
...@@ -76,14 +76,12 @@ ...@@ -76,14 +76,12 @@
<dependency> <dependency>
<groupId>com.alibaba</groupId> <groupId>com.alibaba</groupId>
<artifactId>druid</artifactId> <artifactId>druid</artifactId>
<version>${driud.version}</version>
</dependency> </dependency>
<!-- mybatis --> <!-- mybatis -->
<dependency> <dependency>
<groupId>org.mybatis.spring.boot</groupId> <groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId> <artifactId>mybatis-spring-boot-starter</artifactId>
<version>${mybatis.version}</version>
</dependency> </dependency>
<!-- swagger --> <!-- swagger -->
......
...@@ -4,6 +4,7 @@ import org.springframework.boot.SpringApplication; ...@@ -4,6 +4,7 @@ import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker; import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.cloud.openfeign.EnableFeignClients; import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.ComponentScan;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
...@@ -15,6 +16,8 @@ import org.springframework.security.config.annotation.method.configuration.Enabl ...@@ -15,6 +16,8 @@ import org.springframework.security.config.annotation.method.configuration.Enabl
@ComponentScan(basePackages = {"com.github.tangyi"}) @ComponentScan(basePackages = {"com.github.tangyi"})
@EnableGlobalMethodSecurity(prePostEnabled = true) @EnableGlobalMethodSecurity(prePostEnabled = true)
@EnableCircuitBreaker @EnableCircuitBreaker
// 动态刷新
@RefreshScope
public class ExamServiceApplication { public class ExamServiceApplication {
public static void main(String[] args) { public static void main(String[] args) {
......
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.github.tangyi</groupId>
<artifactId>spring-microservice-exam</artifactId>
<version>2.0-SNAPSHOT</version>
</parent>
<artifactId>service-api-impl</artifactId>
<name>${project.artifactId}</name>
<description>api实现</description>
<modules>
<module>auth-service</module>
<module>user-service</module>
<module>exam-service</module>
</modules>
</project>
...@@ -4,7 +4,7 @@ ...@@ -4,7 +4,7 @@
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<parent> <parent>
<groupId>com.github.tangyi</groupId> <groupId>com.github.tangyi</groupId>
<artifactId>spring-microservice-exam</artifactId> <artifactId>service-api-impl</artifactId>
<version>2.0-SNAPSHOT</version> <version>2.0-SNAPSHOT</version>
</parent> </parent>
<artifactId>user-service</artifactId> <artifactId>user-service</artifactId>
...@@ -64,28 +64,24 @@ ...@@ -64,28 +64,24 @@
<dependency> <dependency>
<groupId>com.alibaba</groupId> <groupId>com.alibaba</groupId>
<artifactId>druid</artifactId> <artifactId>druid</artifactId>
<version>${driud.version}</version>
</dependency> </dependency>
<!-- mybatis --> <!-- mybatis -->
<dependency> <dependency>
<groupId>org.mybatis.spring.boot</groupId> <groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId> <artifactId>mybatis-spring-boot-starter</artifactId>
<version>${mybatis.version}</version>
</dependency> </dependency>
<!--fastDfs--> <!--fastDfs-->
<dependency> <dependency>
<groupId>com.github.tobato</groupId> <groupId>com.github.tobato</groupId>
<artifactId>fastdfs-client</artifactId> <artifactId>fastdfs-client</artifactId>
<version>${fastdfs-client.version}</version>
</dependency> </dependency>
<!-- 验证码 --> <!-- 验证码 -->
<dependency> <dependency>
<groupId>com.github.axet</groupId> <groupId>com.github.axet</groupId>
<artifactId>kaptcha</artifactId> <artifactId>kaptcha</artifactId>
<version>${kaptcha.version}</version>
</dependency> </dependency>
<!-- swagger --> <!-- swagger -->
......
...@@ -4,6 +4,7 @@ import org.springframework.boot.SpringApplication; ...@@ -4,6 +4,7 @@ import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker; import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.cloud.openfeign.EnableFeignClients; import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.ComponentScan;
import org.springframework.scheduling.annotation.EnableAsync; import org.springframework.scheduling.annotation.EnableAsync;
......
...@@ -47,8 +47,6 @@ import java.util.List; ...@@ -47,8 +47,6 @@ import java.util.List;
@RequestMapping("/v1/attachment") @RequestMapping("/v1/attachment")
public class AttachmentController extends BaseController { public class AttachmentController extends BaseController {
private static final Logger logger = LoggerFactory.getLogger(AttachmentController.class);
@Autowired @Autowired
private AttachmentService attachmentService; private AttachmentService attachmentService;
......
...@@ -31,8 +31,6 @@ import org.springframework.web.bind.annotation.*; ...@@ -31,8 +31,6 @@ import org.springframework.web.bind.annotation.*;
@RequestMapping("/v1/log") @RequestMapping("/v1/log")
public class LogController extends BaseController { public class LogController extends BaseController {
private static final Logger logger = LoggerFactory.getLogger(LogController.class);
@Autowired @Autowired
private LogService logService; private LogService logService;
......
...@@ -40,8 +40,6 @@ import java.util.*; ...@@ -40,8 +40,6 @@ import java.util.*;
@RequestMapping("/v1/menu") @RequestMapping("/v1/menu")
public class MenuController extends BaseController { public class MenuController extends BaseController {
private static final Logger logger = LoggerFactory.getLogger(MenuController.class);
@Autowired @Autowired
private MenuService menuService; private MenuService menuService;
......
...@@ -42,8 +42,6 @@ import java.util.List; ...@@ -42,8 +42,6 @@ import java.util.List;
@RequestMapping("/v1/role") @RequestMapping("/v1/role")
public class RoleController extends BaseController { public class RoleController extends BaseController {
private static final Logger logger = LoggerFactory.getLogger(RoleController.class);
@Autowired @Autowired
private RoleService roleService; private RoleService roleService;
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment