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> <parent>
<groupId>com.chinaunicom.ebtp</groupId> <groupId>com.chinaunicom.ebtp</groupId>
<artifactId>mall-ebtp-cloud-parent</artifactId> <artifactId>mall-ebtp-cloud-parent</artifactId>
<version>2.0.1-SNAPSHOT</version> <version>2.1.0-SNAPSHOT</version>
<relativePath>../mall-ebtp-cloud-parent</relativePath> <relativePath>../mall-ebtp-cloud-parent</relativePath>
</parent> </parent>
<groupId>com.chinaunicom.ebtp</groupId> <groupId>com.chinaunicom.ebtp</groupId>
<artifactId>mall-ebtp-cloud-jpa-starter</artifactId> <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> <name>mall-ebtp-cloud-jpa-starter</name>

View File

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

View File

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

View File

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

View File

@ -6,13 +6,13 @@
<parent> <parent>
<groupId>com.chinaunicom.ebtp</groupId> <groupId>com.chinaunicom.ebtp</groupId>
<artifactId>mall-ebtp-cloud-parent</artifactId> <artifactId>mall-ebtp-cloud-parent</artifactId>
<version>2.0.1-SNAPSHOT</version> <version>2.1.0-SNAPSHOT</version>
<relativePath>../mall-ebtp-cloud-parent</relativePath> <relativePath>../mall-ebtp-cloud-parent</relativePath>
</parent> </parent>
<groupId>com.chinaunicom.mall.ebtp</groupId> <groupId>com.chinaunicom.mall.ebtp</groupId>
<artifactId>uboot-common</artifactId> <artifactId>uboot-common</artifactId>
<version>2.0.1-SNAPSHOT</version> <version>2.1.0-SNAPSHOT</version>
<name>uboot-common</name> <name>uboot-common</name>
<dependencies> <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 lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.AuthenticationException; import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint; import org.springframework.security.web.AuthenticationEntryPoint;
@ -41,7 +42,10 @@ public class UserAuthenticationEntryPoint implements AuthenticationEntryPoint {
response.setContentType(RESPONSE_CONTENT_TYPE); response.setContentType(RESPONSE_CONTENT_TYPE);
String code = (String) request.getSession().getAttribute("code");// security filter 返回的自定义状态码 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<String, Object> map = adapterException(StringUtils.defaultIfBlank(code, DEFAULT_ERROR_MESSAGE), response);
map.put("success", false); map.put("success", false);
map.put("path", request.getServletPath()); 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 TOKEN_PREFIX = "Bearer ";
public static final String CURRENT_ROLE_CODE = "currentRoleCode"; public static final String CURRENT_ROLE_CODE = "currentRoleCode";
public static final String COOKIE_TOKEN_CODE = "mall3_token"; 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 TOKEN_EXPIRED = "90401";
public static final String REMOTE_ACCESS_FAILURE = "90500"; 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() .sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
.addFilterBefore(authenticationTokenFilterBean(), UsernamePasswordAuthenticationFilter.class) .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 cn.hutool.core.bean.BeanUtil;
import com.chinaunicom.mall.ebtp.cloud.security.starter.common.Constants; 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.RoleCodeAuthority;
import com.chinaunicom.mall.ebtp.cloud.security.starter.entity.SecurityUser; import com.chinaunicom.mall.ebtp.cloud.security.starter.entity.SecurityUser;
import com.chinaunicom.mall.ebtp.cloud.userinfo.starter.service.UserInfoService; 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.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.remoting.RemoteTimeoutException; import org.springframework.remoting.RemoteTimeoutException;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication; import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.context.SecurityContextHolder;
@ -22,10 +22,8 @@ import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import java.io.IOException; import java.io.IOException;
import java.util.Collections; import java.util.*;
import java.util.List; import java.util.regex.Pattern;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import java.util.stream.Stream; import java.util.stream.Stream;
@ -38,9 +36,12 @@ import static com.chinaunicom.mall.ebtp.cloud.security.starter.common.Constants.
*/ */
@Slf4j @Slf4j
public class TokenAuthenticationFilter extends OncePerRequestFilter { public class TokenAuthenticationFilter extends OncePerRequestFilter {
@Autowired
private UserInfoService client;
private @Autowired
UserInfoService client; @Autowired
private AuthAllows allows;
/** /**
* @param request * @param request
@ -52,37 +53,39 @@ public class TokenAuthenticationFilter extends OncePerRequestFilter {
@Override @Override
protected void doFilterInternal(final HttpServletRequest request, final HttpServletResponse response, protected void doFilterInternal(final HttpServletRequest request, final HttpServletResponse response,
final FilterChain filterChain) throws ServletException, IOException { final FilterChain filterChain) throws ServletException, IOException {
if (!StringUtils.contains(request.getRequestURI(), "actuator/prometheus")) { String api = request.getRequestURI();
log.info("--------" + request.getMethod() + " - " + request.getRequestURI() + "?" + Optional.ofNullable(request.getQueryString()).orElse("")); String method = request.getMethod();
if (!StringUtils.contains(api, "actuator/prometheus")) {
log.info("--------" + method + " - " + api + "?" + Optional.ofNullable(request.getQueryString()).orElse(""));
} }
// 清空上下文中的缓存信息, 防止二次请求时数据异常 (如此, 每次有新的请求进入都会进行token的验证) // 清空上下文中的缓存信息, 防止二次请求时数据异常 (如此, 每次有新的请求进入都会进行token的验证)
SecurityContextHolder.getContext().setAuthentication(null); SecurityContextHolder.getContext().setAuthentication(null);
boolean isWhite = checkWhiteList(api, method);
if (isWhite) {
isNullThenAssignDefault();
}
// 提取request头信息 // 提取request头信息
final String header = request.getHeader(AUTHORIZATION_HEADER); final String header = request.getHeader(AUTHORIZATION_HEADER);
final String currentRoleCode = request.getHeader(CURRENT_ROLE_CODE); final String currentRoleCode = request.getHeader(CURRENT_ROLE_CODE);
boolean skip = !StringUtils.equals(request.getHeader(NO_AUTH), NO_AUTH_TOKEN);
try { try {
if (skip) { // 检查请求头是否包含 Bearer 前缀
// 检查请求头是否包含 Bearer 前缀 if (StringUtils.startsWith(header, Constants.TOKEN_PREFIX)) {
if (StringUtils.startsWith(header, Constants.TOKEN_PREFIX)) { setAuthentication(currentRoleCode, RegExUtils.replaceAll(header, Constants.TOKEN_PREFIX, ""), isWhite);// 移除header的前缀提取出token字串
setAuthentication(currentRoleCode, RegExUtils.replaceAll(header, Constants.TOKEN_PREFIX, ""));// 移除header的前缀提取出token字串 }
} // 检查cookie
// 检查cookie else {
else { Optional.ofNullable(request.getCookies())
Optional.ofNullable(request.getCookies()) .flatMap(cookies ->
.flatMap(cookies -> Stream.of(cookies)
Stream.of(cookies) .filter(item -> StringUtils.equals(item.getName(), COOKIE_TOKEN_CODE))
.filter(item -> StringUtils.equals(item.getName(), COOKIE_TOKEN_CODE)) .findFirst())
.findFirst()) .ifPresent(cookie -> setAuthentication(currentRoleCode, cookie.getValue(), isWhite));
.ifPresent(cookie -> setAuthentication(currentRoleCode, cookie.getValue()));
}
} }
// TODO 临时放行未传递token且session中未包含access token信息的服务调用
isNullThenAssignDefault();
} catch (Exception e) { } catch (Exception e) {
request.getSession().setAttribute("code", e.getMessage()); request.getSession().setAttribute("code", e.getMessage());
log.error(e.getMessage()); log.error(e.getMessage());
@ -90,14 +93,27 @@ public class TokenAuthenticationFilter extends OncePerRequestFilter {
filterChain.doFilter(request, response); 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 currentRoleCode
* @param authToken * @param authToken
*/ */
private void setAuthentication(final String currentRoleCode, final String authToken) { private void setAuthentication(final String currentRoleCode, final String authToken, final boolean isWhite) {
SecurityContextHolder.getContext().setAuthentication(getAuthentication(authToken, currentRoleCode)); SecurityContextHolder.getContext().setAuthentication(getAuthentication(authToken, currentRoleCode, isWhite));
} }
/** /**
@ -106,16 +122,17 @@ public class TokenAuthenticationFilter extends OncePerRequestFilter {
* @param token * @param token
* @return * @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); BaseCacheUser userInfo = client.getUserInfo(token);
if (Objects.isNull(userInfo)) {// 对象为空, 则说明网络异常feign已熔断 if (Objects.isNull(userInfo)) {// 对象为空, 则说明网络异常feign已熔断
throw new RemoteTimeoutException(REMOTE_ACCESS_FAILURE); 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); SecurityUser securityUser = BeanUtil.toBean(userInfo, SecurityUser.class);
// 根据当前角色设定权限列表 // 根据当前角色设定权限列表

View File

@ -1,5 +1,7 @@
package com.chinaunicom.mall.ebtp.common.config; package com.chinaunicom.mall.ebtp.common.config;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import feign.RequestInterceptor; import feign.RequestInterceptor;
import feign.RequestTemplate; import feign.RequestTemplate;
import lombok.Setter; import lombok.Setter;
@ -7,9 +9,17 @@ import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpHeaders;
import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes; 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.List;
import java.util.Objects; import java.util.Objects;
import java.util.Optional; import java.util.Optional;
@ -81,14 +91,70 @@ public class FeignConfig implements RequestInterceptor {
if (StringUtils.startsWith(header, TOKEN_PREFIX)) { if (StringUtils.startsWith(header, TOKEN_PREFIX)) {
template.header(AUTHORIZATION_HEADER, header); template.header(AUTHORIZATION_HEADER, header);
} else {// 检查cookie } else {// 检查cookie
Optional.ofNullable(attributes.getRequest().getCookies()) Optional<Cookie> cookie = Optional.ofNullable(attributes.getRequest().getCookies())
.flatMap(cookies -> Stream.of(cookies) .flatMap(cookies -> Stream.of(cookies)
.filter(item -> StringUtils.equals(item.getName(), COOKIE_TOKEN_CODE) .filter(item -> StringUtils.equals(item.getName(), COOKIE_TOKEN_CODE)
).findFirst()).ifPresent(token -> { ).findFirst());
String authToken = token.getValue(); if (cookie.isPresent()) {
String authToken = cookie.get().getValue();
template.header(AUTHORIZATION_HEADER, String.format("%s%s", TOKEN_PREFIX, authToken)); 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> <parent>
<groupId>com.chinaunicom.ebtp</groupId> <groupId>com.chinaunicom.ebtp</groupId>
<artifactId>mall-ebtp-cloud-parent</artifactId> <artifactId>mall-ebtp-cloud-parent</artifactId>
<version>2.0.1-SNAPSHOT</version> <version>2.1.0-SNAPSHOT</version>
<relativePath>../mall-ebtp-cloud-parent</relativePath> <relativePath>../mall-ebtp-cloud-parent</relativePath>
</parent> </parent>
<groupId>com.chinaunicom.mall.ebtp</groupId> <groupId>com.chinaunicom.mall.ebtp</groupId>
<artifactId>uboot-core</artifactId> <artifactId>uboot-core</artifactId>
<version>2.0.1-SNAPSHOT</version> <version>2.1.0-SNAPSHOT</version>
<name>uboot-core</name> <name>uboot-core</name>
<dependencies> <dependencies>
@ -20,7 +20,7 @@
<dependency> <dependency>
<groupId>com.chinaunicom.mall.ebtp</groupId> <groupId>com.chinaunicom.mall.ebtp</groupId>
<artifactId>uboot-common</artifactId> <artifactId>uboot-common</artifactId>
<version>2.0.1-SNAPSHOT</version> <version>2.1.0-SNAPSHOT</version>
</dependency> </dependency>
<dependency> <dependency>