<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.8.8</version>
</dependency>
public ResultVO<UserInfoDTO> test(String code, HttpSession session) {
ResultVO<UserInfoDTO> vo = new ResultVO<>();
if(org.apache.commons.lang3.StringUtils.isBlank(authServerUrl)){
LOG.info("---------authServerUrl is null...");
vo.setData(getTestToken(code, session));
vo.setSuccess(true);
return vo;
}
String codeBody = "grant_type=authorization_code"
+ "&code=" + code
+ "&redirect_uri=" + URLUtil.encode(redirectUri);
try {
HttpResponse tokenResponse = HttpUtil.createPost(authServerUrl + "/oauth2/token")
.contentType("application/x-www-form-urlencoded")
.body(codeBody)
.header("Authorization", "Basic " + Base64.encode(clientId + ":" + secretKey))
.execute();
if (200 == tokenResponse.getStatus()) {
String body = tokenResponse.body();
Map<String, Object> tokenMap = JSONUtil.toBean(body, Map.class);
String accessToken = Convert.toStr(tokenMap.get("access_token"));
String idToken = Convert.toStr(tokenMap.get("id_token"));
if (accessToken != null) {
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(java.util.Base64.getDecoder().decode(publicKey));
PublicKey rsaPublicKey = SecureUtil.generatePublicKey("RSA", keySpec);
JWTSigner jwtSigner = JWTSignerUtil.rs256(rsaPublicKey);
// 使用公钥验证access_token和id_token
if (JWTUtil.verify(accessToken, jwtSigner) && JWTUtil.verify(idToken, jwtSigner)) {
// 解析JWT
JWT jwt = JWTUtil.parseToken(idToken);
String userId = (String) jwt.getPayload("id");
String userName = (String) jwt.getPayload("username");
String name = (String) jwt.getPayload("name");
String sid = (String) jwt.getPayload("sid");
LoginUser loginUser = new LoginUser();
loginUser.setId(userId);
loginUser.setUsername(userName);
loginUser.setName(name);
loginUser.setSessionId(UUIDUtils.getUUID());
// 将本地会话与accessToken绑定,在主动退出或调用中央4A接口时需要用到这个accessToken
loginUser.setAccessToken(accessToken);
session.setAttribute(SESSION_USER_KEY, loginUser);
// 绑定token中的会话ID与你的会话ID进行绑定,在被动退出登录时能够用上
String sessionId = session.getId();
// 将单点登录服务的会话ID与本地会话ID(sessionId)进行绑定,被动登出时需要用他来销毁本地会话
cacheManager.getCache("sid").put(sid, sessionId);
cacheManager.getCache("sessionId").put(sessionId, accessToken);
HashMap<String,Object> claims = new HashMap<String,Object>();
claims.put(JwtTokenUtil.ACCOUNT, loginUser.getUsername());
claims.put(JwtTokenUtil.NAME, loginUser.getName());
claims.put(JwtTokenUtil.ID, loginUser.getId());
claims.put(JwtTokenUtil.THIRD_ACCESS_TOKEN, loginUser.getAccessToken());
claims.put(JwtTokenUtil.SESSION_ID, loginUser.getSessionId());
String token = JwtTokenUtil.createToken(loginUser.getUsername(), claims, true);
UserInfoDTO dto = ModelMapperUtil.getStrictModelMapper().map(loginUser, UserInfoDTO.class);
dto.setToken(token);
vo.setSuccess(true);
vo.setData(dto);
return vo;
} else {
LOG.info("------------tokenResponse.getStatus() is " + tokenResponse.getStatus());
throw new TokenExpiredException("认证失败");
}
}else {
LOG.info("------------accessToken is null...");
throw new TokenExpiredException("认证失败");
}
}else {
LOG.info("tokenResponse.getStatus()= " + tokenResponse.getStatus());
String body = tokenResponse.body();
if(body != null){
Map<String, Object> tokenMap = JSONUtil.toBean(body, Map.class);
LOG.info("-------------- " + JSON.toJSONString(tokenMap));
}
throw new TokenExpiredException("认证失败");
}
}catch (Exception e){
LOG.error("----------callback error...");
LOG.info("authServerUrl: "+authServerUrl);
LOG.info("redirectUri: "+ redirectUri);
LOG.info("clientId: "+clientId);
LOG.info("publicKey: " + publicKey);
LOG.error(ExceptionUtils.getExceptionMessage(e));
throw new TokenExpiredException("认证失败");
}
}
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import java.io.File;
@Service
public class GAPlusService {
private static Logger LOG = LoggerFactory.getLogger(GAPlusService.class);
private static final String HEADER_PRE = "Bearer ";
/**
* 这个是往同一个表里面新增数据,根据传的questionId区分是哪个数据,执行成功的话,返回一个任务的id
* @param file
* @param access_token
* @return
*/
public String submitTaskAddData(File file, String access_token, String questionId){
String headerValue = HEADER_PRE + access_token;
String filePath = upload(file, headerValue);
if(StringUtils.isNotBlank(filePath)){
return doSubmitTaskAddData(filePath, questionId, headerValue);
}
return null;
}
/**
* 调用接口上传文件,然后返回文件的路径信息
* @param file
* @param headerValue
* @return
*/
private String upload(File file, String headerValue){
try {
HttpResponse tokenResponse = HttpUtil.createPost(GAPlusConfig.uploadUrl)
.contentType("application/x-www-form-urlencoded")
.header("Authorization", headerValue)
.form("type", "zip")
.form("file", file)
.execute();
int status = tokenResponse.getStatus();
if (200 == status) {
String body = tokenResponse.body();
// Map<String, Object> tokenMap = JSONUtil.toBean(body, Map.class);
JSONObject jsonObject = JSONUtil.parseObj(body);
if(jsonObject.containsKey("data")){
return jsonObject.getStr("data");
}else {
LOG.error("--------upload---------upload msg: " + jsonObject.toString());
}
}else if(401 == status){
LOG.info("-----------upload----status is 401");
throw new TokenExpiredException(HttpStatus.UNAUTHORIZED.value(), "登录状态已过期");
} else {
LOG.info("----------upload----status is " + status);
LOG.info(tokenResponse.body());
throw new TokenExpiredException(HttpStatus.UNAUTHORIZED.value(), "登录状态已过期");
}
}catch (TokenExpiredException e){
throw new TokenExpiredException(HttpStatus.UNAUTHORIZED.value(), "登录状态已过期");
} catch (Exception e){
LOG.error("---------------upload error..." + e.getMessage());
e.printStackTrace();
}
return null;
}
private String doSubmitTaskAddData(String filePath, String id, String headerValue){
try {
HttpResponse tokenResponse = HttpUtil.createPost(GAPlusConfig.taskSubmitAddDataUrl)
.contentType("application/x-www-form-urlencoded")
.header("Authorization", headerValue)
.form("expression", "\"" + id + "\"")
.form("file_path", filePath)
.execute();
int status = tokenResponse.getStatus();
if (200 == status) {
String body = tokenResponse.body();
// Map<String, Object> tokenMap = JSONUtil.toBean(body, Map.class);
JSONObject jsonObject = JSONUtil.parseObj(body);
if(jsonObject.containsKey("data")){
JSONObject data = jsonObject.getJSONObject("data");
if(data != null && data.containsKey("id")){
return data.getStr("id");
}
LOG.info("-------doSubmitTaskAddData------ " + jsonObject.toString());
}else {
LOG.error("-----------------doSubmitTaskAddData msg: " + jsonObject.toString());
}
}else {
LOG.info("--------doSubmitTaskAddData------status is " + status);
LOG.info(tokenResponse.body());
}
}catch (Exception e){
LOG.error("---------doSubmitTaskAddData----submitTask error..." + e.getMessage());
e.printStackTrace();
}
return null;
}
public String submitTaskByGeometry(com.alibaba.fastjson.JSONObject geometry, String id, String headerValue){
try {
HttpResponse tokenResponse = HttpUtil.createPost(GAPlusConfig.taskSubmitByGeometryUrl)
.contentType("application/x-www-form-urlencoded")
.header("Authorization", headerValue)
.form("expression", "\"" + id + "\"")
.form("featurecollection", geometry)
.execute();
int status = tokenResponse.getStatus();
if (200 == status) {
String body = tokenResponse.body();
// Map<String, Object> tokenMap = JSONUtil.toBean(body, Map.class);
JSONObject jsonObject = JSONUtil.parseObj(body);
if(jsonObject.containsKey("data")){
JSONObject data = jsonObject.getJSONObject("data");
if(data != null && data.containsKey("id")){
return data.getStr("id");
}
LOG.info("-------submitTaskByGeometry------ " + jsonObject.toString());
}else {
LOG.error("-----------------submitTaskByGeometry msg: " + jsonObject.toString());
}
}else {
LOG.info("--------submitTaskByGeometry------status is " + status);
LOG.info(tokenResponse.body());
throw new TokenExpiredException(HttpStatus.UNAUTHORIZED.value(), "登录状态已过期");
}
}catch (TokenExpiredException e){
throw new TokenExpiredException(HttpStatus.UNAUTHORIZED.value(), "登录状态已过期");
} catch (Exception e){
LOG.error("---------submitTaskByGeometry----submitTask error..." + e.getMessage());
e.printStackTrace();
}
return null;
}
}