1、新增apollo热加载appliacation.properties
2、新增feign接口无token情况下,添加临时token
3、拦截所有controller接口,进行token校验,同时添加apollo白名单功能
This commit is contained in:
付庆吉
2022-02-28 15:35:00 +08:00
parent ab177dab75
commit 8059e0e2ae
13 changed files with 224 additions and 59 deletions

View File

@ -7,13 +7,13 @@
<parent>
<groupId>com.chinaunicom.ebtp</groupId>
<artifactId>mall-ebtp-cloud-parent</artifactId>
<version>2.0.1-SNAPSHOT</version>
<version>2.1.0-SNAPSHOT</version>
<relativePath>../mall-ebtp-cloud-parent</relativePath>
</parent>
<groupId>com.chinaunicom.ebtp</groupId>
<artifactId>mall-ebtp-cloud-jpa-starter</artifactId>
<version>2.0.1-SNAPSHOT</version>
<version>2.1.0-SNAPSHOT</version>
<name>mall-ebtp-cloud-jpa-starter</name>

View File

@ -8,13 +8,13 @@
<parent>
<groupId>com.chinaunicom.ebtp</groupId>
<artifactId>mall-ebtp-cloud-parent</artifactId>
<version>2.0.1-SNAPSHOT</version>
<version>2.1.0-SNAPSHOT</version>
<relativePath>../mall-ebtp-cloud-parent</relativePath>
</parent>
<groupId>com.chinaunicom.ebtp</groupId>
<artifactId>mall-ebtp-cloud-kafka-starter</artifactId>
<version>2.0.1-SNAPSHOT</version>
<version>2.1.0-SNAPSHOT</version>
<name>mall-ebtp-cloud-kafka-starter</name>
<dependencies>

View File

@ -7,12 +7,12 @@
<parent>
<groupId>com.chinaunicom.ebtp</groupId>
<artifactId>mall-ebtp-cloud</artifactId>
<version>2.0.1-SNAPSHOT</version>
<version>2.1.0-SNAPSHOT</version>
</parent>
<groupId>com.chinaunicom.ebtp</groupId>
<artifactId>mall-ebtp-cloud-parent</artifactId>
<version>2.0.1-SNAPSHOT</version>
<version>2.1.0-SNAPSHOT</version>
<packaging>pom</packaging>
<name>mall-ebtp-cloud-parent</name>
@ -21,22 +21,22 @@
<dependency>
<groupId>com.chinaunicom.ebtp</groupId>
<artifactId>mall-ebtp-cloud-jpa-starter</artifactId>
<version>2.0.1-SNAPSHOT</version>
<version>2.1.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>com.chinaunicom.ebtp</groupId>
<artifactId>mall-ebtp-cloud-kafka-starter</artifactId>
<version>2.0.1-SNAPSHOT</version>
<version>2.1.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>com.chinaunicom.mall.ebtp</groupId>
<artifactId>uboot-common</artifactId>
<version>2.0.1-SNAPSHOT</version>
<version>2.1.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>com.chinaunicom.mall.ebtp</groupId>
<artifactId>uboot-core</artifactId>
<version>2.0.1-SNAPSHOT</version>
<version>2.1.0-SNAPSHOT</version>
</dependency>
</dependencies>
</dependencyManagement>

View File

@ -13,7 +13,7 @@
<groupId>com.chinaunicom.ebtp</groupId>
<artifactId>mall-ebtp-cloud</artifactId>
<version>2.0.1-SNAPSHOT</version>
<version>2.1.0-SNAPSHOT</version>
<packaging>pom</packaging>
<name>mall-ebtp-cloud</name>

View File

@ -6,13 +6,13 @@
<parent>
<groupId>com.chinaunicom.ebtp</groupId>
<artifactId>mall-ebtp-cloud-parent</artifactId>
<version>2.0.1-SNAPSHOT</version>
<version>2.1.0-SNAPSHOT</version>
<relativePath>../mall-ebtp-cloud-parent</relativePath>
</parent>
<groupId>com.chinaunicom.mall.ebtp</groupId>
<artifactId>uboot-common</artifactId>
<version>2.0.1-SNAPSHOT</version>
<version>2.1.0-SNAPSHOT</version>
<name>uboot-common</name>
<dependencies>

View File

@ -0,0 +1,55 @@
package com.chinaunicom.mall.ebtp.cloud.apollo.starter;
import com.ctrip.framework.apollo.model.ConfigChange;
import com.ctrip.framework.apollo.model.ConfigChangeEvent;
import com.ctrip.framework.apollo.spring.annotation.ApolloConfigChangeListener;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.environment.EnvironmentChangeEvent;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
/**
* @author f
*/
@Slf4j
@Component
@Configuration
public class ApolloHotLoading implements ApplicationContextAware {
private ApplicationContext applicationContext;
@Value("${spring.application.name}")
private String applicationName;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
@ApolloConfigChangeListener()
private void someChangeHandler(ConfigChangeEvent changeEvent) {
log.info(" ------------------- {} apolloHotLoading start ------------------", applicationName);
for (String changedKey : changeEvent.changedKeys()) {
ConfigChange configChange = changeEvent.getChange(changedKey);
String oldValue = configChange.getOldValue();
String newValue = configChange.getNewValue();
log.info("changedKey:【{}】,oldValue=【{}】, newValue:【{}】", changedKey, oldValue, newValue);
}
refreshProperties(changeEvent);
log.info(" ------------------- {} apolloHotLoading end ------------------", applicationName);
}
public void refreshProperties(ConfigChangeEvent changeEvent) {
// 更新相应的bean的属性值主要是存在@ConfigurationProperties注解的bean
this.applicationContext.publishEvent(new EnvironmentChangeEvent(changeEvent.changedKeys()));
}
}

View File

@ -4,6 +4,7 @@ import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
@ -41,7 +42,10 @@ public class UserAuthenticationEntryPoint implements AuthenticationEntryPoint {
response.setContentType(RESPONSE_CONTENT_TYPE);
String code = (String) request.getSession().getAttribute("code");// security filter 返回的自定义状态码
//未获取到token 且不在白名单
if (authException instanceof InsufficientAuthenticationException) {
code = REMOTE_ACCESS_FAILURE;
}
Map<String, Object> map = adapterException(StringUtils.defaultIfBlank(code, DEFAULT_ERROR_MESSAGE), response);
map.put("success", false);
map.put("path", request.getServletPath());

View File

@ -9,10 +9,8 @@ public interface Constants {
public static final String TOKEN_PREFIX = "Bearer ";
public static final String CURRENT_ROLE_CODE = "currentRoleCode";
public static final String COOKIE_TOKEN_CODE = "mall3_token";
public static final String NO_AUTH = "0klui7pj90000bx04lxf";
public static final String TOKEN_EXPIRED = "90401";
public static final String REMOTE_ACCESS_FAILURE = "90500";
public static final String NO_AUTH_TOKEN = "0kluipxcr0000831ztrl";
}

View File

@ -44,7 +44,9 @@ public class BrowserSecurityConfig extends WebSecurityConfigurerAdapter {
.sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
.addFilterBefore(authenticationTokenFilterBean(), UsernamePasswordAuthenticationFilter.class)
// 只对业务节点请求做认证处理
.authorizeRequests().antMatchers("/v1/**").authenticated().and().httpBasic().and().csrf().disable();
// .authorizeRequests().antMatchers("/v1/**").authenticated().and()
.authorizeRequests().anyRequest().authenticated().and()
.httpBasic().and().csrf().disable();
}
}

View File

@ -0,0 +1,23 @@
package com.chinaunicom.mall.ebtp.cloud.security.starter.entity;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import java.util.List;
/**
* @author f
*/
@Data
@Configuration
@ConfigurationProperties(prefix = "allow")
@Accessors(chain = true)
public class AuthAllows {
private List<String> apis;
}

View File

@ -2,6 +2,7 @@ package com.chinaunicom.mall.ebtp.cloud.security.starter.filter;
import cn.hutool.core.bean.BeanUtil;
import com.chinaunicom.mall.ebtp.cloud.security.starter.common.Constants;
import com.chinaunicom.mall.ebtp.cloud.security.starter.entity.AuthAllows;
import com.chinaunicom.mall.ebtp.cloud.security.starter.entity.RoleCodeAuthority;
import com.chinaunicom.mall.ebtp.cloud.security.starter.entity.SecurityUser;
import com.chinaunicom.mall.ebtp.cloud.userinfo.starter.service.UserInfoService;
@ -11,7 +12,6 @@ import org.apache.commons.lang3.RegExUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.remoting.RemoteTimeoutException;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
@ -22,10 +22,8 @@ import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.*;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;
@ -38,9 +36,12 @@ import static com.chinaunicom.mall.ebtp.cloud.security.starter.common.Constants.
*/
@Slf4j
public class TokenAuthenticationFilter extends OncePerRequestFilter {
@Autowired
private UserInfoService client;
private @Autowired
UserInfoService client;
@Autowired
private AuthAllows allows;
/**
* @param request
@ -52,23 +53,28 @@ public class TokenAuthenticationFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(final HttpServletRequest request, final HttpServletResponse response,
final FilterChain filterChain) throws ServletException, IOException {
if (!StringUtils.contains(request.getRequestURI(), "actuator/prometheus")) {
log.info("--------" + request.getMethod() + " - " + request.getRequestURI() + "?" + Optional.ofNullable(request.getQueryString()).orElse(""));
String api = request.getRequestURI();
String method = request.getMethod();
if (!StringUtils.contains(api, "actuator/prometheus")) {
log.info("--------" + method + " - " + api + "?" + Optional.ofNullable(request.getQueryString()).orElse(""));
}
// 清空上下文中的缓存信息, 防止二次请求时数据异常 (如此, 每次有新的请求进入都会进行token的验证)
SecurityContextHolder.getContext().setAuthentication(null);
boolean isWhite = checkWhiteList(api, method);
if (isWhite) {
isNullThenAssignDefault();
}
// 提取request头信息
final String header = request.getHeader(AUTHORIZATION_HEADER);
final String currentRoleCode = request.getHeader(CURRENT_ROLE_CODE);
boolean skip = !StringUtils.equals(request.getHeader(NO_AUTH), NO_AUTH_TOKEN);
try {
if (skip) {
// 检查请求头是否包含 Bearer 前缀
if (StringUtils.startsWith(header, Constants.TOKEN_PREFIX)) {
setAuthentication(currentRoleCode, RegExUtils.replaceAll(header, Constants.TOKEN_PREFIX, ""));// 移除header的前缀提取出token字串
setAuthentication(currentRoleCode, RegExUtils.replaceAll(header, Constants.TOKEN_PREFIX, ""), isWhite);// 移除header的前缀提取出token字串
}
// 检查cookie
else {
@ -77,12 +83,9 @@ public class TokenAuthenticationFilter extends OncePerRequestFilter {
Stream.of(cookies)
.filter(item -> StringUtils.equals(item.getName(), COOKIE_TOKEN_CODE))
.findFirst())
.ifPresent(cookie -> setAuthentication(currentRoleCode, cookie.getValue()));
}
.ifPresent(cookie -> setAuthentication(currentRoleCode, cookie.getValue(), isWhite));
}
// TODO 临时放行未传递token且session中未包含access token信息的服务调用
isNullThenAssignDefault();
} catch (Exception e) {
request.getSession().setAttribute("code", e.getMessage());
log.error(e.getMessage());
@ -90,14 +93,27 @@ public class TokenAuthenticationFilter extends OncePerRequestFilter {
filterChain.doFilter(request, response);
}
/**
* 白名单验证
*
* @param method url地址
* @param methodType 请求方式 GET
* @return
*/
private boolean checkWhiteList(String method, String methodType) {
return Optional.ofNullable(allows.getApis()).orElseGet(ArrayList::new)
.parallelStream().anyMatch(reg -> Pattern.compile(reg).matcher(methodType + "." + method).matches());
}
/**
* 设置认证用户信息
*
* @param currentRoleCode
* @param authToken
*/
private void setAuthentication(final String currentRoleCode, final String authToken) {
SecurityContextHolder.getContext().setAuthentication(getAuthentication(authToken, currentRoleCode));
private void setAuthentication(final String currentRoleCode, final String authToken, final boolean isWhite) {
SecurityContextHolder.getContext().setAuthentication(getAuthentication(authToken, currentRoleCode, isWhite));
}
/**
@ -106,16 +122,17 @@ public class TokenAuthenticationFilter extends OncePerRequestFilter {
* @param token
* @return
*/
private Authentication getAuthentication(final String token, final String currentRoleCode) {
private Authentication getAuthentication(final String token, final String currentRoleCode,
final boolean isWhite) {
BaseCacheUser userInfo = client.getUserInfo(token);
if (Objects.isNull(userInfo)) {// 对象为空, 则说明网络异常feign已熔断
if (!isWhite) {
throw new RemoteTimeoutException(REMOTE_ACCESS_FAILURE);
} else {
return new UsernamePasswordAuthenticationToken(new SecurityUser(), null, null);
}
if (Objects.isNull(userInfo.getUserId())) {// userid 为空则访问山分认证服务返回信息为null
throw new AccessDeniedException(TOKEN_EXPIRED);
}
SecurityUser securityUser = BeanUtil.toBean(userInfo, SecurityUser.class);
// 根据当前角色设定权限列表

View File

@ -1,5 +1,7 @@
package com.chinaunicom.mall.ebtp.common.config;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.Setter;
@ -7,9 +9,17 @@ import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpHeaders;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.Cookie;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
@ -81,14 +91,70 @@ public class FeignConfig implements RequestInterceptor {
if (StringUtils.startsWith(header, TOKEN_PREFIX)) {
template.header(AUTHORIZATION_HEADER, header);
} else {// 检查cookie
Optional.ofNullable(attributes.getRequest().getCookies())
Optional<Cookie> cookie = Optional.ofNullable(attributes.getRequest().getCookies())
.flatMap(cookies -> Stream.of(cookies)
.filter(item -> StringUtils.equals(item.getName(), COOKIE_TOKEN_CODE)
).findFirst()).ifPresent(token -> {
String authToken = token.getValue();
).findFirst());
if (cookie.isPresent()) {
String authToken = cookie.get().getValue();
template.header(AUTHORIZATION_HEADER, String.format("%s%s", TOKEN_PREFIX, authToken));
});
} else {
String access_token = getAccessToken();
log.info("token=======access_token==="+access_token);
template.header(HttpHeaders.AUTHORIZATION,String.format("%s%s", TOKEN_PREFIX, access_token));
}
}
}
@Value("${client.clientHttpUrl}")
private String clientHttpUrl;
public String getAccessToken () {
StringBuffer strBf = new StringBuffer();
try {
log.info("token=======access_token===clientHttpUrl==="+clientHttpUrl);
URL realUrl = new URL(clientHttpUrl);
//将realUrl以 open方法返回的urlConnection 连接强转为HttpURLConnection连接 (标识一个url所引用的远程对象连接)
// 此时cnnection只是为一个连接对象,待连接中
HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection();
//设置连接输出流为true,默认false (post请求是以流的方式隐式的传递参数)
connection.setDoOutput(true);
//设置连接输入流为true
connection.setDoInput(true);
//设置请求方式为post
connection.setRequestMethod("POST");
//post请求缓存设为false
connection.setUseCaches(false);
//设置该HttpURLConnection实例是否自动执行重定向
connection.setInstanceFollowRedirects(true);
//设置请求头里面的各个属性 (以下为设置内容的类型,设置为经过urlEncoded编码过的from参数)
connection.setRequestProperty("Content-Type", "application/json;charset=utf-8");
//建立连接 (请求未开始,直到connection.getInputStream()方法调用时才发起,以上各个参数设置需在此方法之前进行)
log.info("token=======access_token===建立连接===");
connection.connect();
log.info("token=======access_token===创建输入输===");
//创建输入输出流,用于往连接里面输出携带的参数,(输出内容为?后面的内容)
DataOutputStream dataout = new DataOutputStream(connection.getOutputStream());
// //将参数输出到连接
// 输出完成后刷新并关闭流
dataout.flush();
dataout.close(); // 重要且易忽略步骤 (关闭流,切记!)
log.info("token=======access_token===reader===");
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8));
String lines;
while ((lines = reader.readLine()) != null) {
lines = new String(lines.getBytes(), StandardCharsets.UTF_8);
strBf.append(lines);
}
reader.close();
connection.disconnect();
log.info("toke返回数据---------------------- "+strBf.toString());
} catch (Exception e) {
log.info("toke返回数据----------------------失败 "+e.getMessage());
}
log.info("toke返回数据----------strBf------------ "+strBf.toString());
JSONObject json= JSON.parseObject(strBf.toString());
if((boolean)json.get("success")){
return ((JSONObject)json.get("data")).get("value").toString();
}
return null;
}
}

View File

@ -6,13 +6,13 @@
<parent>
<groupId>com.chinaunicom.ebtp</groupId>
<artifactId>mall-ebtp-cloud-parent</artifactId>
<version>2.0.1-SNAPSHOT</version>
<version>2.1.0-SNAPSHOT</version>
<relativePath>../mall-ebtp-cloud-parent</relativePath>
</parent>
<groupId>com.chinaunicom.mall.ebtp</groupId>
<artifactId>uboot-core</artifactId>
<version>2.0.1-SNAPSHOT</version>
<version>2.1.0-SNAPSHOT</version>
<name>uboot-core</name>
<dependencies>
@ -20,7 +20,7 @@
<dependency>
<groupId>com.chinaunicom.mall.ebtp</groupId>
<artifactId>uboot-common</artifactId>
<version>2.0.1-SNAPSHOT</version>
<version>2.1.0-SNAPSHOT</version>
</dependency>
<dependency>