Commit 02be8110 authored by kang.nie@inzymeits.com's avatar kang.nie@inzymeits.com
Browse files

初始化代码

parent e9f88257
Pipeline #3111 failed with stages
in 0 seconds
package com.cusc.nirvana.user.eiam.dto;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.io.*;
/**
* Description: 用户密码dto
* <br />
* CreateDate 2022-06-11 23:56:43
*
* @author yuyi
**/
@ApiModel(value = "用户密码dto", description = "用户密码dto")
@Data
public class UserPasswordDTO implements Serializable {
private static final long serialVersionUID = 1L;
@ApiModelProperty(value = "业务主键")
private String uuid;
@ApiModelProperty(value = "用户名")
private String userName;
@ApiModelProperty(value = "密钥的请求id")
private String requestId;
@ApiModelProperty(value = "用户密码")
private String password;
@ApiModelProperty(value = "手机号")
private String phone;
@ApiModelProperty(value = "应用id")
private String applicationId;
@ApiModelProperty(value = "租户编号")
private String tenantNo;
@ApiModelProperty(value = "短信发送配置")
private SmsSendConfig smsSendConfig;
@ApiModelProperty(value = "短信验证码,不为空则验证")
private String smsCode;
}
package com.cusc.nirvana.user.eiam.dto;
import com.cusc.nirvana.user.eiam.common.BaseIamPageDTO;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.util.List;
/**
* 用户资源关系(UserResource)传输对象类
*
* @author yuy336
* @since 2022-01-19 13:41:24
*/
@ApiModel(value = "用户资源关系", description = "用户资源关系")
@Data
public class UserResourceDTO extends BaseIamPageDTO {
private static final long serialVersionUID = -52832421917906673L;
@ApiModelProperty(value = "用户id")
private String userId;
@ApiModelProperty(value = "角色id")
private String resourceId;
@ApiModelProperty(value = "租户编号")
private String tenantNo;
@ApiModelProperty(value = "应用id")
private String applicationId;
@ApiModelProperty(value = "最后一次操作人")
private String operator;
@ApiModelProperty(value = "资源id集合")
private List<String> resourceIdList;
@ApiModelProperty(value = "用户id集合")
private List<String> userIdList;
}
package com.cusc.nirvana.user.eiam.dto;
import com.cusc.nirvana.user.eiam.common.BaseIamDTO;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.util.List;
/**
* <p>
*
* </p>
*
* @author auto-generator
* @since 2021-10-20
*/
@ApiModel(value = "UserRoleDTO对象", description = "")
@Data
public class UserRoleDTO extends BaseIamDTO {
@ApiModelProperty(value = "用户id")
private String userId;
@ApiModelProperty(value = "角色id")
private String roleId;
@ApiModelProperty(value = "租户编号")
private String tenantNo;
@ApiModelProperty(value = "应用id")
private String applicationId;
@ApiModelProperty(value = "角色uuid集合")
private List<String> roleUuidList;
@ApiModelProperty(value = "租户编号集合")
private List<String> tenantNoList;
@ApiModelProperty(value = "控制查询的数量")
private Integer size;
@ApiModelProperty(value = "操作人")
private String operator;
@ApiModelProperty(value = "用户uuid集合")
private List<String> userIdList;
@ApiModelProperty(value = "授权类型:1 角色授权 2 用户直接授权")
private Integer authType;
}
package com.cusc.nirvana.user.eiam.dto;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.io.*;
/**
* <p>
* 用户简单对象
* </p>
*
* @author yuy336
* @since 2021-10-20
*/
@ApiModel(value = "用户简单对象", description = "用户简单对象")
@Data
public class UserSimpleDTO implements Serializable {
private static final long serialVersionUID = 1L;
@ApiModelProperty(value = "业务主键")
private String uuid;
@ApiModelProperty(value = "用户名")
private String userName;
@ApiModelProperty(value = "用户姓名")
private String fullName;
@ApiModelProperty(value = "租户编号")
private String tenantNo;
@ApiModelProperty(value = "手机号")
private String phone;
@ApiModelProperty(value = "普通管理员类型")
private Integer ordinaryAdmin;
}
package com.cusc.nirvana.user.util;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.cusc.nirvana.common.result.PageResult;
import com.cusc.nirvana.common.result.Response;
import com.cusc.nirvana.user.common.UserLogOutputJsonSerializeFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;
import java.util.List;
/**
* Description: resttemplate封装
* <br />
* CreateDate 2021-11-01 16:46
*
* @author yuyi
**/
public class RestTemplateUtils {
private static final Logger LOGGER = LoggerFactory.getLogger(RestTemplateUtils.class);
/**
* Description: post请求Response泛型
* <br />
* CreateDate 2021-11-01 16:53:25
*
* @author yuyi
**/
public static <T> Response<T> postForResponse(RestTemplate restTemplate, String url, Object request,
Class<T> cls, Object... urlVariables) {
long startTime = System.currentTimeMillis();
LOGGER.info("postForResponse url: {},request: {}", url,
JSON.toJSONString(request, new UserLogOutputJsonSerializeFilter()));
ResponseEntity<String> entity =
restTemplate.exchange(url, HttpMethod.POST, new HttpEntity<>(request), String.class, urlVariables);
LOGGER.info("postForResponse url: {},response: {},cost: {} ms", url,
JSON.toJSONString(entity.getBody(), new UserLogOutputJsonSerializeFilter()),
System.currentTimeMillis() - startTime);
Response<T> result = JSON.parseObject(entity.getBody(), new TypeReference<Response<T>>(cls) {
}.getType());
return result;
}
/**
* Description: post请求Response泛型
* <br />
* CreateDate 2021-11-01 16:53:25
*
* @author yuyi
**/
public static <T> Response<T> postEntityForResponse(RestTemplate restTemplate, String url, HttpEntity<?> requestEntity, Class<T> cls, Object... urlVariables) {
long startTime = System.currentTimeMillis();
LOGGER.info("postEntityForResponse url: {},request: {}", url,
JSON.toJSONString(requestEntity, new UserLogOutputJsonSerializeFilter()));
ResponseEntity<String> entity =
restTemplate.exchange(url, HttpMethod.POST, requestEntity, String.class, urlVariables);
LOGGER.info("postEntityForResponse url: {},response: {},cost: {} ms", url,
JSON.toJSONString(entity.getBody(), new UserLogOutputJsonSerializeFilter()),
System.currentTimeMillis() - startTime);
Response<T> result = JSON.parseObject(entity.getBody(), new TypeReference<Response<T>>(cls) {
}.getType());
return result;
}
/**
* Description: post请求Response泛型
* <br />
* CreateDate 2021-11-01 16:53:25
*
* @author yuyi
**/
public static Response postForResponse(RestTemplate restTemplate, String url, Object request,
Object... urlVariables) {
long startTime = System.currentTimeMillis();
LOGGER.info("postForResponse url: {},request: {}", url,
JSON.toJSONString(request, new UserLogOutputJsonSerializeFilter()));
ResponseEntity<String> entity =
restTemplate.exchange(url, HttpMethod.POST, new HttpEntity<>(request), String.class, urlVariables);
LOGGER.info("postForResponse url: {},response: {},cost: {} ms", url,
JSON.toJSONString(entity.getBody(), new UserLogOutputJsonSerializeFilter()),
System.currentTimeMillis() - startTime);
Response result = JSON.parseObject(entity.getBody(), Response.class);
return result;
}
/**
* Description: post请求Response<PageResult>泛型
* <br />
* CreateDate 2021-11-01 16:53:25
*
* @author yuyi
**/
public static <T> Response<PageResult<T>> postForResponsePageResult(RestTemplate restTemplate, String url,
Object request,
Class<T> cls, Object... urlVariables) {
long startTime = System.currentTimeMillis();
LOGGER.info("postForResponsePageResult url: {},request: {}", url,
JSON.toJSONString(request, new UserLogOutputJsonSerializeFilter()));
ResponseEntity<String> entity =
restTemplate.exchange(url, HttpMethod.POST, new HttpEntity<>(request), String.class, urlVariables);
LOGGER.info("postForResponsePageResult url: {},response: {},cost: {} ms", url,
JSON.toJSONString(entity.getBody(), new UserLogOutputJsonSerializeFilter()),
System.currentTimeMillis() - startTime);
Response<PageResult<T>> result = JSON.parseObject(entity.getBody(),
new TypeReference<Response<PageResult<T>>>(cls) {
}.getType());
return result;
}
/**
* Description: post请求Response<List>泛型
* <br />
* CreateDate 2021-11-01 16:53:25
*
* @author yuyi
**/
public static <T> Response<List<T>> postForResponseList(RestTemplate restTemplate, String url, Object request,
Class<T> cls, Object... urlVariables) {
long startTime = System.currentTimeMillis();
LOGGER.info("postForResponseList url: {},request: {}", url,
JSON.toJSONString(request, new UserLogOutputJsonSerializeFilter()));
ResponseEntity<String> entity =
restTemplate.exchange(url, HttpMethod.POST, new HttpEntity<>(request), String.class, urlVariables);
LOGGER.info("postForResponseList url: {},response: {},cost: {} ms", url,
JSON.toJSONString(entity.getBody(), new UserLogOutputJsonSerializeFilter()),
System.currentTimeMillis() - startTime);
Response<List<T>> result = JSON.parseObject(entity.getBody(), new TypeReference<Response<List<T>>>(cls) {
}.getType());
return result;
}
/**
* Description: get 请求响应泛型对象
* <br />
* CreateDate 2022-05-13 18:41:15
*
* @author yuyi
**/
public static <T> T getForObject(RestTemplate restTemplate, String url, Class<T> cls) {
long startTime = System.currentTimeMillis();
LOGGER.info("getForObject url: {}", url);
ResponseEntity<String> entity = restTemplate.getForEntity(url, String.class);
LOGGER.info("getForObject url: {},response: {},cost: {} ms", url,
JSON.toJSONString(entity.getBody(), new UserLogOutputJsonSerializeFilter()),
System.currentTimeMillis() - startTime);
return JSON.parseObject(entity.getBody(), cls);
}
public static <T> Response<List<T>> getForResponseList(RestTemplate restTemplate, String url,
Class<T> cls, Object... urlVariables) {
long startTime = System.currentTimeMillis();
LOGGER.info("getForResponseList url: {},request: {}", url,
JSON.toJSONString(urlVariables, new UserLogOutputJsonSerializeFilter()));
ResponseEntity<String> entity =
restTemplate.exchange(url, HttpMethod.GET, null, String.class, urlVariables);
LOGGER.info("getForResponseList url: {},response: {},cost: {} ms", url,
JSON.toJSONString(entity.getBody(), new UserLogOutputJsonSerializeFilter()),
System.currentTimeMillis() - startTime);
Response<List<T>> result = JSON.parseObject(entity.getBody(), new TypeReference<Response<List<T>>>(cls) {
}.getType());
return result;
}
}
<?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">
<parent>
<artifactId>local-rnr-user</artifactId>
<groupId>com.cusc.nirvana</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>local-rnr-user-plug</artifactId>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>com.cusc.nirvana</groupId>
<artifactId>local-rnr-user-remote</artifactId>
<version>${project.version}</version>
</dependency>
</dependencies>
</project>
package com.cusc.nirvana.user.auth.authentication.plug.constants;
/**
* Description: redis相关常量类
* <br />
* CreateDate 2021-11-03 20:36
*
* @author yuyi
**/
public class AuthConstant {
//用户id名称
public static final String USER_ID_NAME = "userId";
//应用id名称
public static final String APP_ID_NAME = "appId";
//租户编号名称
public static final String TENANT_NO_NAME = "tenantNo";
//组织编号名称
public static final String ORGAN_ID_NAME = "organId";
//鉴权模式:最强模式,白名单放行(传了token会自动获取用户id透传),否则拦截(没有token或没权限都会拦截)
public static final int AUTH_MODEL_1 = 1;
//鉴权模式:token鉴权模式,白名单放行(传了token会自动获取用户id透传),否则拦截(没有token或没权限都会拦截)
public static final int AUTH_MODEL_2 = 2;
//鉴权模式:开发鉴权模式,所有url放行(传了token会自动获取用户id透传),否则用户id使用配置中的固定用户
public static final int AUTH_MODEL_3 = 3;
}
package com.cusc.nirvana.user.auth.authentication.plug.constants;
/**
* Description: 响应码
* <br />
* CreateDate 2021-11-02 19:52:36
*
* @author yuyi
**/
public enum ResponseCode {
TOKEN_INVALID(1101, "token已过期");
private Integer code;
private String msg;
ResponseCode(Integer code, String msg) {
this.code = code;
this.msg = msg;
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
}
package com.cusc.nirvana.user.auth.authentication.plug.interceptor;
import com.alibaba.fastjson.JSON;
import com.cusc.nirvana.common.result.Response;
import com.cusc.nirvana.user.auth.authentication.dto.AccessVerifyReq;
import com.cusc.nirvana.user.auth.authentication.plug.constants.AuthConstant;
import com.cusc.nirvana.user.auth.authentication.plug.constants.ResponseCode;
import com.cusc.nirvana.user.auth.authentication.plug.util.ThreadLocalUtil;
import com.cusc.nirvana.user.auth.client.AccessAuthClient;
import com.cusc.nirvana.user.auth.common.dto.AccessTokenHashDTO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
/**
* Description: 鉴权拦截器-最强拦截模式,默认
* <br />
* 注:最强拦截模式是白名单放行(传了token会自动获取用户id透传),否则拦截(没有token或没权限都会拦截)
* CreateDate 2021-11-05 16:00
*
* @author yuyi
**/
public class AuthInterceptor implements HandlerInterceptor {
private static final Logger LOGGER = LoggerFactory.getLogger(AuthInterceptor.class);
@Value("${spring.application.name}")
private String serverName;
@Autowired
private AccessAuthClient accessAuthClient;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
String requestUri = request.getRequestURI();
//从请求头获取token
String token = request.getHeader("Authorization");
AccessVerifyReq accessVerifyReq = new AccessVerifyReq();
accessVerifyReq.setServerName(serverName);
accessVerifyReq.setUrl(requestUri);
//检查请求的url是否是白名单
Response<Boolean> isWhiteListResp = accessAuthClient.isWhiteList(accessVerifyReq);
//token获取的用户id、应用id等信息
Response<AccessTokenHashDTO> authResp;
if (isWhiteListResp != null && isWhiteListResp.isSuccess() && isWhiteListResp.getData()) {
LOGGER.info("AuthInterceptor serverName:{} | url:{} is white list", serverName, requestUri);
if(!StringUtils.isEmpty(token)){
token = token.replaceAll("bearer ", "");
accessVerifyReq.setToken(token);
authResp = accessAuthClient.getUserByToken(accessVerifyReq);
if (authResp.isSuccess() && authResp.getData() != null) {
ThreadLocalUtil.set(AuthConstant.USER_ID_NAME, authResp.getData().getUserId());
ThreadLocalUtil.set(AuthConstant.APP_ID_NAME, authResp.getData().getAppId());
ThreadLocalUtil.set(AuthConstant.TENANT_NO_NAME, authResp.getData().getTenantNo());
ThreadLocalUtil.set(AuthConstant.ORGAN_ID_NAME,authResp.getData().getOrganId());
}
}
}else{
LOGGER.info("AuthInterceptor url:{},token:{}", requestUri, token);
if (StringUtils.isEmpty(requestUri) || StringUtils.isEmpty(token)) {
returnJson(response,
JSON.toJSONString(Response.createError(ResponseCode.TOKEN_INVALID.getMsg(),
ResponseCode.TOKEN_INVALID.getCode())));
return false;
}
token = token.replaceAll("bearer ", "");
//请求鉴权http
accessVerifyReq.setToken(token);
authResp = accessAuthClient.accessVerify(accessVerifyReq);
if (authResp == null) {
returnJson(response,
JSON.toJSONString(Response.createError(ResponseCode.TOKEN_INVALID.getMsg(),
ResponseCode.TOKEN_INVALID.getCode())));
return false;
}
if (!authResp.isSuccess()) {
returnJson(response, JSON.toJSONString(authResp));
return false;
}
// 通过请求获取请求中的header参数
ThreadLocalUtil.set(AuthConstant.USER_ID_NAME, authResp.getData().getUserId());
ThreadLocalUtil.set(AuthConstant.APP_ID_NAME, authResp.getData().getAppId());
ThreadLocalUtil.set(AuthConstant.TENANT_NO_NAME, authResp.getData().getTenantNo());
ThreadLocalUtil.set(AuthConstant.ORGAN_ID_NAME,authResp.getData().getOrganId());
}
return true;
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
Exception ex) {
ThreadLocalUtil.removeByKey(AuthConstant.USER_ID_NAME);
ThreadLocalUtil.removeByKey(AuthConstant.APP_ID_NAME);
ThreadLocalUtil.removeByKey(AuthConstant.TENANT_NO_NAME);
ThreadLocalUtil.removeByKey(AuthConstant.ORGAN_ID_NAME);
}
private void returnJson(HttpServletResponse response, String json) {
response.setCharacterEncoding("utf-8");
response.setContentType("application/json; charset=utf-8");
PrintWriter writer = null;
try {
writer = response.getWriter();
writer.write(json);
} catch (IOException e) {
LOGGER.error("AuthInterceptor 响应json 异常: {}", e);
} finally {
if (writer != null) {
writer.close();
}
}
}
}
package com.cusc.nirvana.user.auth.authentication.plug.interceptor;
import com.cusc.nirvana.common.result.Response;
import com.cusc.nirvana.user.auth.authentication.dto.AccessVerifyReq;
import com.cusc.nirvana.user.auth.authentication.plug.constants.AuthConstant;
import com.cusc.nirvana.user.auth.authentication.plug.util.ThreadLocalUtil;
import com.cusc.nirvana.user.auth.client.AccessAuthClient;
import com.cusc.nirvana.user.auth.common.dto.AccessTokenHashDTO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
/**
* Description: 鉴权拦截器-开发拦截模式
* <br />
* 注:开发拦截模式是所有url放行(传了token会自动获取用户id透传),否则用户id使用配置中的固定用户
* CreateDate 2021-11-05 16:00
*
* @author yuyi
**/
public class DevAuthInterceptor implements HandlerInterceptor {
private static final Logger LOGGER = LoggerFactory.getLogger(DevAuthInterceptor.class);
@Value("${spring.application.name}")
private String serverName;
@Value("${auth.userId: 1}")
private String userId;
@Value("${auth.appId: 1}")
private String appId;
@Value("${auth.tenantNo: 1}")
private String tenantNo;
@Autowired
private AccessAuthClient accessAuthClient;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
String requestUri = request.getRequestURI();
//从请求头获取token
String token = request.getHeader("Authorization");
AccessVerifyReq accessVerifyReq = new AccessVerifyReq();
accessVerifyReq.setServerName(serverName);
accessVerifyReq.setUrl(requestUri);
//检查请求的url是否是白名单
Response<Boolean> isWhiteListResp = accessAuthClient.isWhiteList(accessVerifyReq);
//token获取的用户id、应用id等信息
Response<AccessTokenHashDTO> authResp;
if (isWhiteListResp != null && isWhiteListResp.isSuccess() && isWhiteListResp.getData()) {
LOGGER.info("DevAuthInterceptor serverName:{}, url:{}, token:{}. white list", serverName, requestUri,
token);
} else {
LOGGER.info("DevAuthInterceptor url:{},token:{}", requestUri, token);
}
if (!StringUtils.isEmpty(token)) {
token = token.replaceAll("bearer ", "");
accessVerifyReq.setToken(token);
authResp = accessAuthClient.getUserByToken(accessVerifyReq);
if (authResp.isSuccess() && authResp.getData() != null) {
ThreadLocalUtil.set(AuthConstant.USER_ID_NAME, authResp.getData().getUserId());
ThreadLocalUtil.set(AuthConstant.APP_ID_NAME, authResp.getData().getAppId());
ThreadLocalUtil.set(AuthConstant.TENANT_NO_NAME, authResp.getData().getTenantNo());
ThreadLocalUtil.set(AuthConstant.ORGAN_ID_NAME,authResp.getData().getOrganId());
}
} else {
ThreadLocalUtil.set(AuthConstant.USER_ID_NAME, userId);
ThreadLocalUtil.set(AuthConstant.APP_ID_NAME, appId);
ThreadLocalUtil.set(AuthConstant.TENANT_NO_NAME, tenantNo);
}
LOGGER.info("DevAuthInterceptor url:{},userId:{},appId:{},tenantNo:{}", requestUri, userId, appId, tenantNo);
return true;
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
Exception ex) {
ThreadLocalUtil.removeByKey(AuthConstant.USER_ID_NAME);
ThreadLocalUtil.removeByKey(AuthConstant.APP_ID_NAME);
ThreadLocalUtil.removeByKey(AuthConstant.TENANT_NO_NAME);
ThreadLocalUtil.removeByKey(AuthConstant.ORGAN_ID_NAME);
}
private void returnJson(HttpServletResponse response, String json) {
response.setCharacterEncoding("utf-8");
response.setContentType("application/json; charset=utf-8");
PrintWriter writer = null;
try {
writer = response.getWriter();
writer.write(json);
} catch (IOException e) {
LOGGER.error("AuthInterceptor 响应json 异常: {}", e);
} finally {
if (writer != null) {
writer.close();
}
}
}
}
package com.cusc.nirvana.user.auth.authentication.plug.interceptor;
import com.cusc.nirvana.user.auth.authentication.plug.constants.AuthConstant;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import java.util.List;
/**
* Description: 拦截器配置
* <br />
* CreateDate 2021-11-05 16:06
*
* @author yuyi
**/
@Configuration
public class InterceptorConfig implements WebMvcConfigurer {
@Value("#{'${auth.whiteList}'.split(',')}")
private List<String> whiteList;
/**
* 鉴权模式
**/
@Value("${auth.authModel:1}")
private int authModel;
@Bean
public AuthInterceptor authInterceptor() {
return new AuthInterceptor();
}
@Bean
public SimpleAuthInterceptor simpleAuthInterceptor() {
return new SimpleAuthInterceptor();
}
@Bean
public DevAuthInterceptor devAuthInterceptor() {
return new DevAuthInterceptor();
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
InterceptorRegistration ir;
switch (authModel) {
case AuthConstant.AUTH_MODEL_1:
//最强拦截:白名单放行(传了token会自动获取用户id透传),否则拦截(没有token或没权限都会拦截)
ir = registry.addInterceptor(authInterceptor()).addPathPatterns("/**");
break;
case AuthConstant.AUTH_MODEL_2:
//简单拦截:白名单放行(传了token会自动获取用户id透传),否则拦截(没有token会拦截,不鉴权url请求权限)
ir = registry.addInterceptor(simpleAuthInterceptor()).addPathPatterns("/**");
break;
case AuthConstant.AUTH_MODEL_3:
//开发拦截:所有url放行(传了token会自动获取用户id透传),否则用户id使用配置中的固定用户
ir = registry.addInterceptor(devAuthInterceptor()).addPathPatterns("/**");
break;
default:
//默认不鉴权
return;
}
if(ir != null){
ir.excludePathPatterns(whiteList)
.excludePathPatterns("/swagger-resources/**", "/webjars/**", "/v2/**", "/swagger-ui.html/**");
}
}
}
package com.cusc.nirvana.user.auth.authentication.plug.interceptor;
import com.alibaba.fastjson.JSON;
import com.cusc.nirvana.common.result.Response;
import com.cusc.nirvana.user.auth.authentication.dto.AccessVerifyReq;
import com.cusc.nirvana.user.auth.authentication.plug.constants.AuthConstant;
import com.cusc.nirvana.user.auth.authentication.plug.constants.ResponseCode;
import com.cusc.nirvana.user.auth.authentication.plug.util.ThreadLocalUtil;
import com.cusc.nirvana.user.auth.client.AccessAuthClient;
import com.cusc.nirvana.user.auth.common.dto.AccessTokenHashDTO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
/**
* Description: 鉴权拦截器-简单拦截模式
* <br />
* 注:简单拦截模式是白名单放行(传了token会自动获取用户id透传),否则拦截(没有token会拦截,不鉴权url请求权限)
* CreateDate 2021-11-05 16:00
*
* @author yuyi
**/
public class SimpleAuthInterceptor implements HandlerInterceptor {
private static final Logger LOGGER = LoggerFactory.getLogger(SimpleAuthInterceptor.class);
@Value("${spring.application.name}")
private String serverName;
@Autowired
private AccessAuthClient accessAuthClient;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
String requestUri = request.getRequestURI();
//从请求头获取token
String token = request.getHeader("Authorization");
AccessVerifyReq accessVerifyReq = new AccessVerifyReq();
accessVerifyReq.setServerName(serverName);
accessVerifyReq.setUrl(requestUri);
//检查请求的url是否是白名单
Response<Boolean> isWhiteListResp = accessAuthClient.isWhiteList(accessVerifyReq);
//token获取的用户id、应用id等信息
Response<AccessTokenHashDTO> authResp;
if (isWhiteListResp != null && isWhiteListResp.isSuccess() && isWhiteListResp.getData()) {
LOGGER.info("SimpleAuthInterceptor serverName:{} | url:{} is white list", serverName, requestUri);
} else {
LOGGER.info("SimpleAuthInterceptor url:{},token:{}", requestUri, token);
if (StringUtils.isEmpty(requestUri) || StringUtils.isEmpty(token)) {
returnJson(response,
JSON.toJSONString(Response.createError(ResponseCode.TOKEN_INVALID.getMsg(),
ResponseCode.TOKEN_INVALID.getCode())));
return false;
}
}
if (!StringUtils.isEmpty(token)) {
token = token.replaceAll("bearer ", "");
accessVerifyReq.setToken(token);
authResp = accessAuthClient.getUserByToken(accessVerifyReq);
if (authResp.isSuccess() && authResp.getData() != null && !StringUtils.isEmpty(authResp.getData().getUserId())) {
ThreadLocalUtil.set(AuthConstant.USER_ID_NAME, authResp.getData().getUserId());
ThreadLocalUtil.set(AuthConstant.APP_ID_NAME, authResp.getData().getAppId());
ThreadLocalUtil.set(AuthConstant.TENANT_NO_NAME, authResp.getData().getTenantNo());
ThreadLocalUtil.set(AuthConstant.ORGAN_ID_NAME,authResp.getData().getOrganId());
} else {
returnJson(response,
JSON.toJSONString(Response.createError(ResponseCode.TOKEN_INVALID.getMsg(),
ResponseCode.TOKEN_INVALID.getCode())));
return false;
}
}
return true;
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
Exception ex) {
ThreadLocalUtil.removeByKey(AuthConstant.USER_ID_NAME);
ThreadLocalUtil.removeByKey(AuthConstant.APP_ID_NAME);
ThreadLocalUtil.removeByKey(AuthConstant.TENANT_NO_NAME);
ThreadLocalUtil.removeByKey(AuthConstant.ORGAN_ID_NAME);
}
private void returnJson(HttpServletResponse response, String json) {
response.setCharacterEncoding("utf-8");
response.setContentType("application/json; charset=utf-8");
PrintWriter writer = null;
try {
writer = response.getWriter();
writer.write(json);
} catch (IOException e) {
LOGGER.error("AuthInterceptor 响应json 异常: {}", e);
} finally {
if (writer != null) {
writer.close();
}
}
}
}
package com.cusc.nirvana.user.auth.authentication.plug.user;
import com.cusc.nirvana.user.auth.authentication.plug.constants.AuthConstant;
import com.cusc.nirvana.user.auth.authentication.plug.util.ThreadLocalUtil;
/**
* Description: 用户信息获取service
* <br />
* CreateDate 2021-11-08 9:41
*
* @author yuyi
**/
public class UserSubjectUtil {
/**
* Description: 获取用户id
* <br />
* CreateDate 2021-11-08 10:32:53
*
* @author yuyi
**/
public static String getUserId() {
Object ret = ThreadLocalUtil.getCache(AuthConstant.USER_ID_NAME);
if(ret != null){
return String.valueOf(ret);
}
return null;
}
/**
* Description: 获取应用id
* <br />
* CreateDate 2021-11-08 10:32:53
*
* @author yuyi
**/
public static String getAppId() {
Object ret = ThreadLocalUtil.getCache(AuthConstant.APP_ID_NAME);
if(ret != null){
return String.valueOf(ret);
}
return null;
}
/**
* Description: 获取当前用户所在的租户
* <br />
* CreateDate 2021-11-08 10:32:53
*
* @author yuyi
**/
public static String getTenantNo() {
Object ret = ThreadLocalUtil.getCache(AuthConstant.TENANT_NO_NAME);
if(ret != null){
return String.valueOf(ret);
}
return null;
}
/**
* 获取组织id
* @return
*/
public static String getOrganId(){
Object ret = ThreadLocalUtil.getCache(AuthConstant.ORGAN_ID_NAME);
if(ret != null){
return String.valueOf(ret);
}
return null;
}
}
package com.cusc.nirvana.user.auth.authentication.plug.util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.xml.soap.MimeHeaders;
import java.lang.reflect.Field;
/**
* Description: request工具类
* <br />
* CreateDate 2021-11-08 9:33
*
* @author yuyi
**/
public class RequestUtil {
private static final Logger LOGGER = LoggerFactory.getLogger(RequestUtil.class);
/**
* 获取request header中的值
*
* @return
*/
public static String getToken() {
String token = getRequestHeader("Authorization");
if (token != null && token != "") {
return token.replaceAll("bearer ", "");
}
return token;
}
/**
* 获取request header中的值
*
* @param name
* @return
*/
public static String getRequestHeader(String name) {
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
.getRequest();
return request.getHeader(name);
}
/**
* 获取cookie的值
*
* @param name
* @return
*/
public static String getCookie(String name) {
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
.getRequest();
Cookie[] cookies = request.getCookies();
if (null == cookies || cookies.length == 0) {
return null;
}
for (Cookie c : cookies) {
if (c.getName().equals(name)) {
return c.getValue();
}
}
return null;
}
/**
* 获取httpsession
*
* @return
*/
public static HttpSession getHttpSession() {
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
.getRequest();
return request.getSession();
}
/**
* 获取客户端ip地址
*
* @param request
* @return
*/
public static String getClientIpAddr(HttpServletRequest request) {
String ip = request.getHeader("x-forwarded-for");
if (ip != null && ip.length() != 0 && !"unknown".equalsIgnoreCase(ip)) {
// 多次反向代理后会有多个ip值,第一个ip才是真实ip
if (ip.indexOf(",") != -1) {
ip = ip.split(",")[0];
}
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_CLIENT_IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_X_FORWARDED_FOR");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("X-Real-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
return ip;
}
/**
* 设置request header中的值
*
* @param name
* @return
*/
public static void setRequestHeader(HttpServletRequest request, String name, String value) {
Class<? extends HttpServletRequest> requestClass = request.getClass();
try {
Field requestField = requestClass.getDeclaredField("request");
requestField.setAccessible(true);
Object requestObj = requestField.get(request);
Field coyoteRequestField = requestObj.getClass().getDeclaredField("coyoteRequest");
coyoteRequestField.setAccessible(true);
Object coyoteRequestObj = coyoteRequestField.get(requestObj);
Field headersField = coyoteRequestObj.getClass().getDeclaredField("headers");
headersField.setAccessible(true);
MimeHeaders headersObj = (MimeHeaders) headersField.get(coyoteRequestObj);
headersObj.removeHeader(name);
headersObj.addHeader(name, value);
} catch (Exception e) {
LOGGER.error("setRequestHeader 异常 header key/value: {}. {}", name + "/" + value, e);
}
}
}
package com.cusc.nirvana.user.auth.authentication.plug.util;
import java.util.HashMap;
import java.util.Map;
/**
* Description: 本地线程工具类
* <br />
* CreateDate 2021-11-08 10:25
*
* @author yuyi
**/
public class ThreadLocalUtil {
private static ThreadLocal<Map<String, Object>> cache = new ThreadLocal<>();
/**
* 从ThreadLocal里获取缓存的值
*
* @param key 要获取的数据的KEY
* @return 要获取的值
*/
public static Object getCache(String key) {
Map<String, Object> map = cache.get();
if (isCacheIsNull()) {
return null;
}
if (map.containsKey(key)) {
return map.get(key);
}
return null;
}
/**
* 向ThreadLocal缓存值
*
* @param key 要缓存的KEY
* @param value 要缓存的VALUE
*/
public static void set(String key, Object value) {
if (!isCacheIsNull()) {
cache.get().put(key, value);
} else {
Map<String, Object> vmap = new HashMap<>();
vmap.put(key, value);
cache.set(vmap);
}
}
/**
* 根据KEY移除缓存里的数据
*
* @param key
*/
public static void removeByKey(String key) {
if (!isCacheIsNull()) {
cache.get().remove(key);
}
}
/**
* 移除当前线程缓存
* 用于释放当前线程threadlocal资源
*/
public static void remove() {
cache.remove();
}
private static boolean isCacheIsNull() {
return cache.get() == null;
}
public static String cacheToString() {
return isCacheIsNull() ? null : cache.get().toString();
}
}
<?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">
<parent>
<artifactId>local-rnr-user</artifactId>
<groupId>com.cusc.nirvana</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>local-rnr-user-remote</artifactId>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>com.cusc.nirvana</groupId>
<artifactId>local-rnr-user-dto</artifactId>
<version>${project.version}</version>
</dependency>
</dependencies>
</project>
package com.cusc.nirvana.user.auth.client;
import com.cusc.nirvana.common.result.Response;
import com.cusc.nirvana.user.auth.authentication.dto.AccessVerifyReq;
import com.cusc.nirvana.user.auth.common.dto.AccessTokenHashDTO;
import com.cusc.nirvana.user.auth.constants.UserAuthClientConstant;
import com.cusc.nirvana.user.util.RestTemplateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
/**
* Description: 访问鉴权client调用
* <br />
* CreateDate 2021-10-25 15:36:27
*
* @author yuyi
**/
@Component("accessAuthClient")
public class AccessAuthClient {
@Autowired
RestTemplate restTemplateUser;
/**
* Description: 通过token获取用户id信息
* <br />
* CreateDate 2021-11-05 18:13:44
*
* @author yuyi
**/
public Response<AccessTokenHashDTO> getUserByToken(AccessVerifyReq bean) {
return RestTemplateUtils.postForResponse(restTemplateUser, UserAuthClientConstant.USER_AUTH_URL + "/auth/getUserByToken", bean,
AccessTokenHashDTO.class);
}
/**
* Description: 请求鉴权
* <br />
* CreateDate 2021-11-05 18:13:44
*
* @author yuyi
**/
public Response<AccessTokenHashDTO> accessVerify(AccessVerifyReq bean) {
return RestTemplateUtils.postForResponse(restTemplateUser, UserAuthClientConstant.USER_AUTH_URL + "/auth/accessVerify", bean,
AccessTokenHashDTO.class);
}
/**
* Description: 检查url是否是白名单
* <br />
* CreateDate 2021-11-05 18:13:44
*
* @author yuyi
**/
public Response isWhiteList(AccessVerifyReq bean) {
return restTemplateUser.postForObject(UserAuthClientConstant.USER_AUTH_URL + "/auth/isWhiteList", bean, Response.class);
}
}
package com.cusc.nirvana.user.auth.client;
import com.cusc.nirvana.common.result.Response;
import com.cusc.nirvana.user.auth.constants.UserAuthClientConstant;
import com.cusc.nirvana.user.auth.identification.dto.CaptchaCreateReq;
import com.cusc.nirvana.user.auth.identification.dto.CaptchaCreateResp;
import com.cusc.nirvana.user.auth.identification.dto.CaptchaVerificationReq;
import com.cusc.nirvana.user.util.RestTemplateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.client.RestTemplate;
/**
* Description: 验证码client调用
* <br />
* CreateDate 2021-10-25 15:36:27
*
* @author yuyi
**/
@Component
public class CaptchaClient {
@Autowired
RestTemplate restTemplateUser;
/**
* Description: 简单图形验证码
* <br />
* CreateDate 2022-02-07 17:13:04
*
* @author yuyi
**/
public Response<CaptchaCreateResp> simpleGraphic(CaptchaCreateReq captchaReq) {
return RestTemplateUtils.postForResponse(restTemplateUser, UserAuthClientConstant.USER_AUTH_URL + "/captcha/simpleGraphic", captchaReq,
CaptchaCreateResp.class);
}
/**
* Description: 验证图形验证码
* <br />
* CreateDate 2022-02-07 17:13:04
*
* @author yuyi
**/
public Response<Boolean> verificationCaptcha(@RequestBody CaptchaVerificationReq bean) {
return RestTemplateUtils.postForResponse(restTemplateUser, UserAuthClientConstant.USER_AUTH_URL + "/captcha/verificationCaptcha", bean, Boolean.class);
}
}
package com.cusc.nirvana.user.auth.client;
import com.cusc.nirvana.common.result.Response;
import com.cusc.nirvana.user.auth.constants.UserAuthClientConstant;
import com.cusc.nirvana.user.auth.identification.dto.MobileLoginReq;
import com.cusc.nirvana.user.auth.identification.dto.Oauth2Token;
import com.cusc.nirvana.user.util.RestTemplateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
/**
* Description: 登录client调用
* <br />
* CreateDate 2021-10-25 15:36:27
*
* @author yuyi
**/
@Component
public class CiamLoginClient {
@Autowired
RestTemplate restTemplateUser;
/**
* Description: 手机号登录
* <br />
* CreateDate 2021-11-05 18:13:44
*
* @author yuyi
**/
public Response<Oauth2Token> mobileLogin(MobileLoginReq bean) {
return RestTemplateUtils.postForResponse(restTemplateUser, UserAuthClientConstant.USER_AUTH_URL + "/ciam/login/mobile", bean,
Oauth2Token.class);
}
//郝岩修改 小鹏
public Response<Oauth2Token> mobileLoginXP(MobileLoginReq bean) {
return RestTemplateUtils.postForResponse(restTemplateUser, UserAuthClientConstant.USER_AUTH_URL + "/ciam/login/mobileXP", bean,
Oauth2Token.class);
}
public Response<Oauth2Token> userLoginAdd(MobileLoginReq bean) {
return RestTemplateUtils.postForResponse(restTemplateUser, UserAuthClientConstant.USER_AUTH_URL + "/ciam/login/userLoginAdd", bean,
Oauth2Token.class);
}
}
package com.cusc.nirvana.user.auth.client;
import com.cusc.nirvana.common.result.Response;
import com.cusc.nirvana.user.auth.constants.UserAuthClientConstant;
import com.cusc.nirvana.user.auth.identification.dto.MobileLoginReq;
import com.cusc.nirvana.user.auth.identification.dto.Oauth2Token;
import com.cusc.nirvana.user.auth.identification.dto.UserNameLoginReq;
import com.cusc.nirvana.user.util.RestTemplateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
/**
* Description: 登录client调用
* <br />
* CreateDate 2021-10-25 15:36:27
*
* @author yuyi
**/
@Component
public class LoginClient {
@Autowired
RestTemplate restTemplateUser;
/**
* Description:
* <br />
* CreateDate 2021-11-05 18:13:44
*
* @author yuyi
**/
public Response<Oauth2Token> mobileLogin(MobileLoginReq bean) {
return RestTemplateUtils.postForResponse(restTemplateUser, UserAuthClientConstant.USER_AUTH_URL + "/login/mobile", bean,
Oauth2Token.class);
}
/**
* Description: 发送短信验证码
* <br />
* CreateDate 2021-11-05 18:33:55
*
* @author yuyi
**/
public Response sendSmsCaptcha(MobileLoginReq bean) {
// return restTemplateUser.postForObject(UserAuthClientConstant.USER_AUTH_URL + "/login/sendSmsCaptcha", bean, Response.class);
return RestTemplateUtils.postForResponse(restTemplateUser,
UserAuthClientConstant.USER_AUTH_URL + "/login/sendSmsCaptcha" , bean, Object.class);
}
/**
* @author: jk
* @description: 用于注册登录验证码
* @date: 2022/6/14 10:06
* @version: 1.0
* @Param:
* @Return:
*/
public Response<Object> sendSmsCaptchaNew(MobileLoginReq bean) {
// return restTemplateUser.postForObject(UserAuthClientConstant.USER_AUTH_URL + "/login/sendSmsCaptchaNew", bean, Response.class);
return RestTemplateUtils.postForResponse(restTemplateUser,
UserAuthClientConstant.USER_AUTH_URL + "/login/sendSmsCaptchaNew" , bean, Object.class);
}
/**
* Description: 用户名登录
* <br />
* CreateDate 2021-11-05 18:13:44
*
* @author yuyi
**/
public Response<Oauth2Token> userNameLogin(UserNameLoginReq bean) {
return RestTemplateUtils.postForResponse(restTemplateUser, UserAuthClientConstant.USER_AUTH_URL + "/login/username", bean,
Oauth2Token.class);
}
/**
* Description: C端用户手机号登录
* <br />
* CreateDate 2022-04-16 18:13:44
*
* @author huzl
**/
public Response<Oauth2Token> customerMobileLogin(MobileLoginReq bean) {
return RestTemplateUtils.postForResponse(restTemplateUser, UserAuthClientConstant.USER_AUTH_URL + "/login/customerMobile", bean,
Oauth2Token.class);
}
}
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