忽略ssl证书错误

增加多应用选项
This commit is contained in:
APLS 2020-12-18 00:15:08 +08:00
parent 478f5dbf47
commit ce35e3abeb
14 changed files with 163 additions and 36 deletions

View File

@ -55,7 +55,7 @@ public class SecurityAuthenticationHandler implements AuthenticationSuccessHandl
public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
httpServletResponse.setContentType("application/json;charset=utf-8");
PrintWriter writer = httpServletResponse.getWriter();
writer.write(gson.toJson(ResultUtil.error(-1, "failed!")));
writer.write(gson.toJson(ResultUtil.error(-1, e.getMessage())));
writer.flush();
}

View File

@ -59,11 +59,11 @@ public class UsernamePasswordAuthenticationProvider implements AuthenticationPro
// 根据用户Token中的用户名查找用户信息如果有该用户信息则验证用户密码是否正确
String code = authenticationToken.getCode();
String state = authenticationToken.getState();
logger.info("Github 认证: code{} state{} Token", code, state);
logger.info("认证: code{} state{} Token{}", code, state, authenticationToken.getToken());
Map<String, Object> userInfo_redis = new HashMap<>();
if (!redisUtil.hasKey(states + state)) {
throw new UsernameNotFoundException("status不存在");
throw new UsernameNotFoundException("STATUS不存在");
// return ResultUtil.error(ResultEnum.STATE_HAS_EXPIRED);
}
redisUtil.del(states + state);

View File

@ -13,6 +13,7 @@ import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.io.File;
@ -53,19 +54,28 @@ public class AdminController {
@Value("${user.token.expire}")
private int tokenExpire;
/**
* 测试队列
*
* @Author: 落叶随风
* @Date: 2020/9/7 14:44
* @Return: * @return: void
*/
@GetMapping("/send")
public void send() {
Task.sendTaskOutlookMQ(Integer.valueOf(adminGithubId) );
public void send(@RequestParam int githubId, @RequestParam int outlookId) {
Task.sendTaskOutlookMQ(githubId, outlookId);
}
@GetMapping("/execute")
public void execute(@RequestParam int githubId, @RequestParam int outlookId) {
Task.executeE5(githubId, outlookId);
}
/**
* 对所有队列重新添加
*
* @Author: 落叶随风
* @Date: 2020/9/7 14:43
* @Return: * @return: java.lang.String
@ -78,6 +88,7 @@ public class AdminController {
/**
* 清空redis
*
* @Author: 落叶随风
* @Date: 2020/9/7 14:41
* @Return: * @return: java.lang.String

View File

@ -0,0 +1,20 @@
package io.qyi.e5.outlook.bean;
import lombok.Data;
/**
* @program: e5
* @description:
* @author: 落叶随风
* @create: 2020-12-17 22:20
**/
@Data
public class OutlookMq {
private int githubId;
private int outlookId;
public OutlookMq(int githubId, int outlookId) {
this.githubId = githubId;
this.outlookId = outlookId;
}
}

View File

@ -39,15 +39,25 @@ public class AuthController {
@Autowired
IOutlookService outlookService;
@Value("${isdebug}")
boolean isDebug;
@Value("${redis.auth2.outlook}")
String states;
@Value("${outlook.replyUrl}")
String replyUrl;
@Value("${outlook.replyUrlDebug}")
String replyUrlDebug;
@Value("${outlook.authorize.url}")
String authorizeUrl;
@Autowired
ITask Task;
@RequestMapping("/receive")
public Result Receive(String code, String state, String session_state) throws Exception {
if (!redisUtil.hasKey(states + state)) {
@ -55,21 +65,27 @@ public class AuthController {
}
/*这里不应该查询在进行授权时因该把基础数据丢到redis*/
QueryWrapper<Outlook> outlookQueryWrapper = new QueryWrapper<>();
outlookQueryWrapper.eq("github_id", redisUtil.get(states + state));
int outlookId = (int) redisUtil.get(states + state);
outlookQueryWrapper.eq("id", outlookId);
Outlook outlook = outlookService.getOne(outlookQueryWrapper);
/*删除redis中的此键*/
redisUtil.del(states + state);
if (outlook == null) {
throw new APIException("没有查询到此用户,请检查是否在系统中注册!");
throw new APIException("没有查询到此记录,请检查是否在系统中注册!");
}
System.out.println(outlook);
boolean authorization_code = outlookService.getTokenAndSave(code, outlook.getClientId(), outlook.getClientSecret(), "https://e5.qyi.io/outlook/auth2/receive"
String reUrl = "";
if (isDebug) {
reUrl = replyUrlDebug;
} else {
reUrl = replyUrl;
}
boolean authorization_code = outlookService.getTokenAndSave(code, outlook.getClientId(), outlook.getClientSecret(), reUrl
, "authorization_code");
if (!authorization_code) {
throw new APIException("clientId 或 clientSecret 填写错误!授权失败!");
}
/*添加此用户进消息队列*/
Task.sendTaskOutlookMQ(outlook.getGithubId());
Task.sendTaskOutlookMQ(outlook.getGithubId(),outlookId);
return ResultUtil.success();
}
@ -88,8 +104,15 @@ public class AuthController {
}
// 生成随机uuid标识用户
String state = EncryptUtil.getInstance().SHA1Hex(UUID.randomUUID().toString());
redisUtil.set(states + state, outlook.getGithubId(), 600);
String url = String.format(authorizeUrl, outlook.getClientId(), "https://e5.qyi.io/outlook/auth2/receive", state);
redisUtil.set(states + state, id, 600);
String reUrl = "";
if (isDebug) {
reUrl = replyUrlDebug;
} else {
reUrl = replyUrl;
}
String url = String.format(authorizeUrl, outlook.getClientId(), reUrl, state);
return ResultUtil.success(url);
} else {
throw new APIException("没有此记录");

View File

@ -128,7 +128,6 @@ public class OutlookController {
List<OutlookListVo> vo = new ArrayList<>();
outlooklist.forEach(outlook -> {
OutlookListVo v = new OutlookListVo();
log.info(outlook.toString());
BeanUtils.copyProperties(outlook, v);
vo.add(v);
});

View File

@ -59,7 +59,7 @@ public class OutlookServiceImpl extends ServiceImpl<OutlookMapper, Outlook> impl
logger.info("请求access_token返回数据" + s);
if (jsonObject.get("error") != null) {
logger.error("错授权误!");
return false;
throw new APIException(jsonObject.get("error_description").toString());
} else {
int expires_in = jsonObject.getIntValue("expires_in");
String access_token = jsonObject.getString("access_token");

View File

@ -12,6 +12,6 @@ import com.baomidou.mybatisplus.extension.service.IService;
* @since 2020-03-03
*/
public interface IOutlookLogService extends IService<OutlookLog> {
void addLog(int githubId, String msg,int result,String original_msg);
void addLog(int githubId,int outlookId, String msg,int result,String original_msg);
int deleteInfo(int github_id);
}

View File

@ -18,9 +18,10 @@ import org.springframework.stereotype.Service;
@Service
public class OutlookLogServiceImpl extends ServiceImpl<OutlookLogMapper, OutlookLog> implements IOutlookLogService {
@Override
public void addLog(int githubId, String msg, int result,String original_msg) {
public void addLog(int githubId,int outlookId, String msg, int result,String original_msg) {
OutlookLog outlookLog = new OutlookLog();
outlookLog.setGithubId(githubId)
.setOutlookId(outlookId)
.setResult(result)
.setCallTime((int) (System.currentTimeMillis() / 1000))
.setMsg(msg)

View File

@ -1,6 +1,8 @@
package io.qyi.e5.service.rabbitMQ.impl;
import com.google.gson.Gson;
import com.rabbitmq.client.Channel;
import io.qyi.e5.outlook.bean.OutlookMq;
import io.qyi.e5.outlook.service.IOutlookService;
import io.qyi.e5.service.task.ITask;
import lombok.extern.slf4j.Slf4j;
@ -29,17 +31,18 @@ public class ListenerImpl {
@Autowired
ITask Task;
private static final Gson gson = new Gson();
@RabbitHandler
@RabbitListener(queues = "delay_queue1", containerFactory = "rabbitListenerContainerFactory")
public void listen(Message message, Channel channel) throws IOException {
log.info("消费者1开始处理消息 {},时间戳:{}" ,message,System.currentTimeMillis());
System.out.println("消费者1开始处理消息"+System.currentTimeMillis());
int github_id = Integer.valueOf(new String(message.getBody()));
boolean b = Task.executeE5(github_id);
OutlookMq mq = gson.fromJson(new String(message.getBody()), OutlookMq.class);
boolean b = Task.executeE5(mq.getGithubId(),mq.getOutlookId());
channel.basicAck(message.getMessageProperties().getDeliveryTag(), true);
/*再次进行添加任务*/
if (b) {
Task.sendTaskOutlookMQ(github_id);
Task.sendTaskOutlookMQ(mq.getGithubId(),mq.getOutlookId());
}
}
}

View File

@ -7,10 +7,10 @@ package io.qyi.e5.service.task;
* @create: 2020-04-16 16:51
**/
public interface ITask {
void sendTaskOutlookMQ(int github_id);
void sendTaskOutlookMQ(int github_id, int outlookId);
void sendTaskOutlookMQALL();
boolean executeE5(int github_id);
boolean executeE5(int github_id,int outlookId);
}

View File

@ -1,6 +1,7 @@
package io.qyi.e5.service.task.impl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.qyi.e5.outlook.bean.OutlookMq;
import io.qyi.e5.outlook.entity.Outlook;
import io.qyi.e5.outlook.service.IOutlookService;
import io.qyi.e5.outlook_log.service.IOutlookLogService;
@ -47,8 +48,8 @@ public class TaskImpl implements ITask {
@Override
@Async
public void sendTaskOutlookMQ(int github_id) {
Outlook Outlook = outlookService.getOne(new QueryWrapper<Outlook>().eq("github_id", github_id));
public void sendTaskOutlookMQ(int github_id, int outlookId) {
Outlook Outlook = outlookService.getOne(new QueryWrapper<Outlook>().eq("github_id", github_id).eq("id", outlookId));
if (Outlook == null) {
logger.warn("未找到此用户,github_id: {}", github_id);
return;
@ -56,9 +57,13 @@ public class TaskImpl implements ITask {
/*根据用户设置生成随机数*/
int Expiration = getRandom(Outlook.getCronTimeRandomStart(), Outlook.getCronTimeRandomEnd());
/*将此用户信息加入redis如果存在则代表在队列中同时提前10秒过期*/
if (!redisUtil.hasKey("user.mq:" + github_id)) {
redisUtil.set("user.mq:" + github_id, 0, Expiration - 10);
send(github_id, Expiration* 1000);
String rsKey = "user.mq:" + github_id + ".outlookId:" + outlookId;
if (!redisUtil.hasKey(rsKey)) {
redisUtil.set(rsKey, 0, Expiration - 10);
OutlookMq mq = new OutlookMq(github_id, outlookId);
send(mq, Expiration * 1000);
} else {
logger.info("Key 存在,不执行{}",rsKey);
}
}
@ -80,17 +85,17 @@ public class TaskImpl implements ITask {
}
@Override
public boolean executeE5(int github_id) {
Outlook Outlook = outlookService.getOne(new QueryWrapper<Outlook>().eq("github_id", github_id));
public boolean executeE5(int github_id,int outlookId) {
Outlook Outlook = outlookService.getOne(new QueryWrapper<Outlook>().eq("github_id", github_id).eq("id",outlookId));
if (Outlook == null) {
logger.warn("未找到此用户,github_id: {}", github_id);
return false;
}
boolean isExecuteE5 ;
String errorKey = "user.mq:" + github_id + ":error";
boolean isExecuteE5;
String errorKey = "user.mq:" + github_id + ":outlook.id:" + outlookId + ":error";
try {
int mail_count = outlookService.getMailList(Outlook);
outlookLogService.addLog(github_id, "ok", 1, "读取邮件数量:" + mail_count);
outlookLogService.addLog(github_id,outlookId, "ok", 1, "读取邮件数量:" + mail_count);
if (redisUtil.hasKey(errorKey)) {
redisUtil.del(errorKey);
}
@ -102,13 +107,14 @@ public class TaskImpl implements ITask {
redisUtil.set(errorKey, 1);
isExecuteE5 = true;
} else {
int error_count = (int)redisUtil.get(errorKey);
int error_count = (int) redisUtil.get(errorKey);
if (error_count >= errorCountMax) {
outlookLogService.addLog(github_id, "error", 0, e.getMessage());
outlookLogService.addLog(github_id, "error", 0, "检测到3次连续错误下次将不再自动调用请修正错误后再授权开启续订。");
outlookLogService.addLog(github_id, outlookId,"error", 0, e.getMessage());
outlookLogService.addLog(github_id, outlookId,"error", 0, "检测到3次连续错误下次将不再自动调用请修正错误后再授权开启续订。");
isExecuteE5 = false;
} else {
redisUtil.incr(errorKey, 1);
outlookLogService.addLog(github_id, outlookId,"error", 0, e.getMessage());
isExecuteE5 = true;
}
}
@ -133,7 +139,6 @@ public class TaskImpl implements ITask {
MessageProperties messageProperties = message.getMessageProperties();
// 设置这条消息的过期时间
// messageProperties.setExpiration(Expiration);
messageProperties.setHeader("x-delay", Expiration);
return message;
}, correlationData);

View File

@ -2,6 +2,7 @@ package io.qyi.e5.util.netRequest;
import okhttp3.*;
import javax.net.ssl.X509TrustManager;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.TimeUnit;
@ -13,11 +14,14 @@ public class OkHttpClientUtil {
public static OkHttpClient client = null;
static {
X509TrustManager manager = SSLSocketClientUtil.getX509TrustManager();
client = new OkHttpClient.Builder()
.connectTimeout(connTimeOut, TimeUnit.SECONDS)
.readTimeout(readTimeOut, TimeUnit.SECONDS)
.writeTimeout(writeTimeOut, TimeUnit.SECONDS)
.retryOnConnectionFailure(true)
.sslSocketFactory(SSLSocketClientUtil.getSocketFactory(manager), manager)// 忽略校验
.hostnameVerifier(SSLSocketClientUtil.getHostnameVerifier())//忽略校验
.build();
}

View File

@ -0,0 +1,61 @@
package io.qyi.e5.util.netRequest;
import javax.net.ssl.*;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
/**
* @author wcy
* @date 2020/3/4
* 为了支持okhttp 绕过验签功能
**/
public class SSLSocketClientUtil {
public static SSLSocketFactory getSocketFactory(TrustManager manager) {
SSLSocketFactory socketFactory = null;
try {
SSLContext sslContext = SSLContext.getInstance("SSL");
sslContext.init(null, new TrustManager[]{manager}, new SecureRandom());
socketFactory = sslContext.getSocketFactory();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyManagementException e) {
e.printStackTrace();
}
return socketFactory;
}
public static X509TrustManager getX509TrustManager() {
return new X509TrustManager() {
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
};
}
public static HostnameVerifier getHostnameVerifier() {
HostnameVerifier hostnameVerifier = new HostnameVerifier() {
@Override
public boolean verify(String s, SSLSession sslSession) {
return true;
}
};
return hostnameVerifier;
}
}