更改为token验证

This commit is contained in:
APLS 2020-04-06 22:40:38 +08:00
parent 000dbfac47
commit 126de9aa91
13 changed files with 278 additions and 167 deletions

View File

@ -1,20 +0,0 @@
package io.qyi.e5.bean;
import lombok.Data;
/**
* @program: e5
* @description:
* @author: 落叶随风
* @create: 2020-03-03 16:20
**/
@Data
public class AppQuartz {
private Integer quartzId; //id 主键
private String jobName; //任务名称
private String jobGroup; //任务分组
private String startTime; //任务开始时间
private String cronExpression; //corn表达式
private String invokeParam;//需要传递的参数
}

View File

@ -1,7 +1,10 @@
package io.qyi.e5.config.security; package io.qyi.e5.config.security;
import com.google.gson.Gson;
import io.qyi.e5.util.ResultUtil;
import org.springframework.security.core.Authentication; import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException; import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.AuthenticationFailureHandler; import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler; import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler; import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
@ -12,6 +15,8 @@ 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.io.PrintWriter; import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
/** /**
* @program: msgpush * @program: msgpush
@ -23,8 +28,14 @@ import java.io.PrintWriter;
public class SecurityAuthenticationHandler implements AuthenticationSuccessHandler, AuthenticationFailureHandler , LogoutSuccessHandler { public class SecurityAuthenticationHandler implements AuthenticationSuccessHandler, AuthenticationFailureHandler , LogoutSuccessHandler {
@Override @Override
public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException { public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
httpServletResponse.setStatus(302); UsernamePasswordAuthenticationToken at = (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
httpServletResponse.setHeader("Location", "/user/home"); Gson gson = new Gson();
httpServletResponse.setContentType("application/json;charset=utf-8");
PrintWriter writer = httpServletResponse.getWriter();
Map<String, String> token = new HashMap<>();
token.put("token", at.getToken());
writer.write(gson.toJson(ResultUtil.success(token)) );
writer.flush();
} }
@Override @Override

View File

@ -1,5 +1,6 @@
package io.qyi.e5.config.security; package io.qyi.e5.config.security;
import io.qyi.e5.config.security.filter.LinkTokenAuthenticationFilter;
import io.qyi.e5.service.security.SecurityUserService; import io.qyi.e5.service.security.SecurityUserService;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
@ -7,8 +8,8 @@ import org.springframework.security.config.annotation.authentication.builders.Au
import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
/** /**
* @program: msgpush * @program: msgpush
@ -30,6 +31,7 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
UsernamePasswordAuthenticationConfig usernamePasswordAuthenticationConfig; UsernamePasswordAuthenticationConfig usernamePasswordAuthenticationConfig;
@Override @Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception { protected void configure(AuthenticationManagerBuilder auth) throws Exception {
System.out.println("AuthenticationManagerBuilder auth"); System.out.println("AuthenticationManagerBuilder auth");
@ -57,28 +59,32 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
.logout() .logout()
.logoutUrl("logout") .logoutUrl("logout")
.logoutSuccessHandler( securityAuthenticationHandler);*/ .logoutSuccessHandler( securityAuthenticationHandler);*/
http.addFilterBefore(new LinkTokenAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);
http.csrf().disable() http.csrf().disable()
.apply(usernamePasswordAuthenticationConfig); .apply(usernamePasswordAuthenticationConfig);
/*关闭创建session*/
http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
http.formLogin() http.formLogin()
.loginPage("/user/login")// 登陆页面 .loginPage("/user/login")// 登陆页面
.loginProcessingUrl("/user/loginFrom")// 登陆表单提交请求 .loginProcessingUrl("/user/loginFrom")// 登陆表单提交请求
.and() .and()
.authorizeRequests().antMatchers("/user/login", "/user/loginFrom", "/auth2/getGithubUrl").permitAll()// 指定相应的请求 不需要验证 .authorizeRequests().antMatchers("/user/login", "/user/loginFrom", "/auth2/getGithubUrl").permitAll()// 指定相应的请求 不需要验证
.and() // .and()
.authorizeRequests().antMatchers("/quartz/**").permitAll()//测试 // .authorizeRequests().antMatchers("/quartz/**").permitAll()//测试
.anyRequest()// 任何请求 .anyRequest()// 任何请求
.authenticated();// 都需要身份认证 .authenticated();// 都需要身份认证
// http.exceptionHandling().accessDeniedHandler(); // http.exceptionHandling().accessDeniedHandler();
// http.formLogin().loginProcessingUrl("api/getInfo"); // http.formLogin().loginProcessingUrl("api/getInfo");
// http.formLogin().usernameParameter("username"); // http.formLogin().usernameParameter("username");
// http.formLogin().passwordParameter("password"); // http.formLogin().passwordParameter("password");
} }
/*@Bean
public LinkTokenAuthenticationFilter linkTokenAuthenticationFilter (){
return new LinkTokenAuthenticationFilter();
}*/
/*@Bean /*@Bean
public AccessDeniedHandler getAccessDeniedHandler() { public AccessDeniedHandler getAccessDeniedHandler() {
@ -91,4 +97,5 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
String antPatterns = "/pdfjs-2.1.266/**,/favicon.ico,/css/**,/js/**,/ico/**,/images/**,/jquery-1.12.4/**,/uuid-1.4/**,/layui-2.4.5/**,/jquery-easyui-1.6.11/**,/zTree-3.5.33/**,/select2-4.0.5/**,/greensock-js-1.20.5/**"; String antPatterns = "/pdfjs-2.1.266/**,/favicon.ico,/css/**,/js/**,/ico/**,/images/**,/jquery-1.12.4/**,/uuid-1.4/**,/layui-2.4.5/**,/jquery-easyui-1.6.11/**,/zTree-3.5.33/**,/select2-4.0.5/**,/greensock-js-1.20.5/**";
web.ignoring().antMatchers(antPatterns.split(",")); web.ignoring().antMatchers(antPatterns.split(","));
}*/ }*/
} }

View File

@ -1,12 +1,10 @@
package io.qyi.e5.config.security; package io.qyi.e5.config.security;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.qyi.e5.bean.result.ResultEnum;
import io.qyi.e5.github.entity.Github; import io.qyi.e5.github.entity.Github;
import io.qyi.e5.github.entity.UserInfo; import io.qyi.e5.github.entity.UserInfo;
import io.qyi.e5.github.mapper.GithubMapper; import io.qyi.e5.github.service.IGithubService;
import io.qyi.e5.service.github.GithubService; import io.qyi.e5.util.EncryptUtil;
import io.qyi.e5.util.ResultUtil;
import io.qyi.e5.util.redis.RedisUtil; import io.qyi.e5.util.redis.RedisUtil;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -14,13 +12,16 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.AuthenticationProvider; import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException; import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.Authentication; import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException; import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.authority.AuthorityUtils; import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
/** /**
* @program: e5 * @program: e5
* @description: * @description:
@ -34,17 +35,19 @@ public class UsernamePasswordAuthenticationProvider implements AuthenticationPro
@Value("${redis.auth2.github}") @Value("${redis.auth2.github}")
String states; String states;
@Value("${redis.user.token}")
String token_;
@Value("${isdebug}") @Value("${isdebug}")
boolean isDebug; boolean isDebug;
@Autowired @Autowired
RedisUtil redisUtil; RedisUtil redisUtil;
@Autowired
GithubMapper githubMapper;
@Autowired @Autowired
GithubService githubService; IGithubService githubService;
// 验证 // 验证
@Override @Override
@ -55,10 +58,17 @@ public class UsernamePasswordAuthenticationProvider implements AuthenticationPro
String code = authenticationToken.getCode(); String code = authenticationToken.getCode();
String state = authenticationToken.getState(); String state = authenticationToken.getState();
logger.info("Github 认证: code{} state{} Token", code, state); logger.info("Github 认证: code{} state{} Token", code, state);
Map<String, Object> userInfo_redis = new HashMap<>();
/*是否调试模式*/
if (isDebug) { if (isDebug) {
String token = EncryptUtil.getInstance().SHA1Hex(UUID.randomUUID().toString());
UsernamePasswordAuthenticationToken authenticationToken1 = new UsernamePasswordAuthenticationToken("debugName", UsernamePasswordAuthenticationToken authenticationToken1 = new UsernamePasswordAuthenticationToken("debugName",
"DebugAvatar",19658189, AuthorityUtils.createAuthorityList("user")); "DebugAvatar", 19658189,token, AuthorityUtils.createAuthorityList("user"));
authenticationToken1.setDetails(authenticationToken); authenticationToken1.setDetails(authenticationToken);
userInfo_redis.put("github_name", "debug");
userInfo_redis.put("github_id", 19658189);
userInfo_redis.put("avatar_url", "https://www.baidu.com");
redisUtil.hmset(token_ + token, userInfo_redis, 3600);
return authenticationToken1; return authenticationToken1;
} }
if (!redisUtil.hasKey(states + state)) { if (!redisUtil.hasKey(states + state)) {
@ -78,7 +88,7 @@ public class UsernamePasswordAuthenticationProvider implements AuthenticationPro
} }
QueryWrapper<Github> queryWrapper = new QueryWrapper<>(); QueryWrapper<Github> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("github_id", userInfo.getGithub_id()); queryWrapper.eq("github_id", userInfo.getGithub_id());
Github github = githubMapper.selectOne(queryWrapper); Github github = githubService.selectOne(queryWrapper);
// 未注册就进行注册 // 未注册就进行注册
if (github == null) { if (github == null) {
github = new Github(); github = new Github();
@ -87,17 +97,24 @@ public class UsernamePasswordAuthenticationProvider implements AuthenticationPro
.setGithubId(userInfo.getGithub_id()) .setGithubId(userInfo.getGithub_id())
.setName(userInfo.getName()) .setName(userInfo.getName())
.setLogin(userInfo.getLogin()); .setLogin(userInfo.getLogin());
githubMapper.insert(github); githubService.insert(github);
} else { } else {
// 已注册就进行更新 AccessToken // 已注册就进行更新 AccessToken
github.setAccessToken(accessToken); github.setAccessToken(accessToken);
githubMapper.update(github, queryWrapper); githubService.update(github, queryWrapper);
} }
String token = EncryptUtil.getInstance().SHA1Hex(UUID.randomUUID().toString());
/*写token信息到redis*/
userInfo_redis.put("github_name", github.getName());
userInfo_redis.put("github_id", github.getGithubId());
userInfo_redis.put("avatar_url", github.getAvatarUrl());
redisUtil.hmset(token_ + token, userInfo_redis, 3600);
// 创建一个已认证的token // 创建一个已认证的token
UsernamePasswordAuthenticationToken authenticationToken1 = new UsernamePasswordAuthenticationToken(github.getName(), UsernamePasswordAuthenticationToken authenticationToken1 = new UsernamePasswordAuthenticationToken(github.getName(),
github.getAvatarUrl(),github.getGithubId(), AuthorityUtils.createAuthorityList("user")); github.getAvatarUrl(), github.getGithubId(), token, AuthorityUtils.createAuthorityList("user"));
// 设置一些详细信息 // 设置一些详细信息
authenticationToken1.setDetails(authenticationToken); authenticationToken1.setDetails(authenticationToken);

View File

@ -26,8 +26,15 @@ public class UsernamePasswordAuthenticationToken extends AbstractAuthenticationT
private String name; private String name;
private String avatar_url; private String avatar_url;
private String Token;
private int github_id; private int github_id;
// 创建未认证的用户名密码认证对象
public UsernamePasswordAuthenticationToken() {
super(null);
}
// 创建未认证的用户名密码认证对象 // 创建未认证的用户名密码认证对象
public UsernamePasswordAuthenticationToken(String code) { public UsernamePasswordAuthenticationToken(String code) {
@ -48,7 +55,7 @@ public class UsernamePasswordAuthenticationToken extends AbstractAuthenticationT
// 创建已认证的用户密码认证对象 // 创建已认证的用户密码认证对象
public UsernamePasswordAuthenticationToken( String name, String avatar_url, int github_id,Collection<? extends GrantedAuthority> authorities) { public UsernamePasswordAuthenticationToken(String name, String avatar_url, int github_id, Collection<? extends GrantedAuthority> authorities) {
super(authorities); super(authorities);
this.name = name; this.name = name;
this.avatar_url = avatar_url; this.avatar_url = avatar_url;
@ -56,6 +63,24 @@ public class UsernamePasswordAuthenticationToken extends AbstractAuthenticationT
super.setAuthenticated(true); super.setAuthenticated(true);
} }
// 创建已认证的用户密码认证对象
public UsernamePasswordAuthenticationToken(String name, String avatar_url, int github_id, String token, Collection<? extends GrantedAuthority> authorities) {
super(authorities);
this.name = name;
this.avatar_url = avatar_url;
this.github_id = github_id;
this.Token = token;
super.setAuthenticated(true);
}
public String getToken() {
return Token;
}
public void setToken(String token) {
Token = token;
}
@Override @Override
public String getCredentials() { public String getCredentials() {
return null; return null;
@ -66,6 +91,7 @@ public class UsernamePasswordAuthenticationToken extends AbstractAuthenticationT
return this.code; return this.code;
} }
public String getCode() { public String getCode() {
return code; return code;
} }

View File

@ -0,0 +1,62 @@
package io.qyi.e5.config.security.filter;
import com.google.gson.Gson;
import io.qyi.e5.bean.result.Result;
import io.qyi.e5.bean.result.ResultEnum;
import io.qyi.e5.config.security.UsernamePasswordAuthenticationToken;
import io.qyi.e5.util.ResultUtil;
import io.qyi.e5.util.SpringUtil;
import io.qyi.e5.util.redis.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;
/**
* Token校验
*
* @program: e5
* @description:
* @author: 落叶随风
* @create: 2020-04-05 00:42
**/
public class LinkTokenAuthenticationFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
String token = httpServletRequest.getHeader("token");
if (token != null) {
RedisUtil redisUtil = SpringUtil.getBean(RedisUtil.class);
if (redisUtil.hasKey("token:" + token)) {
Map<Object, Object> userInfo = redisUtil.hmget("token:" +token);
// 将未认证的Authentication转换成自定义的用户认证Token
UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken();
UsernamePasswordAuthenticationToken authenticationToken1 = new UsernamePasswordAuthenticationToken(userInfo.get("github_name").toString(),
userInfo.get("avatar_url").toString(), (int) userInfo.get("github_id"), AuthorityUtils.createAuthorityList("user"));
authenticationToken1.setDetails(authenticationToken);
SecurityContextHolder.getContext().setAuthentication(authenticationToken1);
System.out.println("完成授权");
}
}
System.out.println("--------------Token鉴权---------------");
filterChain.doFilter(httpServletRequest, httpServletResponse);
}
public void sendJson(HttpServletResponse httpServletResponse, Object o) throws IOException {
Gson gson = new Gson();
String s = gson.toJson(o);
PrintWriter writer = httpServletResponse.getWriter();
writer.write(s);
writer.flush();
}
}

View File

@ -1,16 +1,9 @@
package io.qyi.e5.controller.auth2; package io.qyi.e5.controller.auth2;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import io.qyi.e5.bean.result.Result;
import io.qyi.e5.bean.result.ResultEnum;
import io.qyi.e5.github.entity.Github;
import io.qyi.e5.github.entity.UserInfo;
import io.qyi.e5.github.mapper.GithubMapper; import io.qyi.e5.github.mapper.GithubMapper;
import io.qyi.e5.service.github.GithubService; import io.qyi.e5.github.service.IGithubService;
import io.qyi.e5.user.mapper.UserMapper; import io.qyi.e5.user.mapper.UserMapper;
import io.qyi.e5.util.EncryptUtil; import io.qyi.e5.util.EncryptUtil;
import io.qyi.e5.util.ResultUtil;
import io.qyi.e5.util.redis.RedisUtil; import io.qyi.e5.util.redis.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.annotation.Value;
@ -33,13 +26,7 @@ public class Auth {
RedisUtil redisUtil; RedisUtil redisUtil;
@Autowired @Autowired
GithubService githubService; IGithubService githubService;
@Autowired
UserMapper userMapper;
@Autowired
GithubMapper githubMapper;
@Value("${redis.auth2.github}") @Value("${redis.auth2.github}")
String states; String states;

View File

@ -1,7 +1,9 @@
package io.qyi.e5.github.service; package io.qyi.e5.github.service;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.qyi.e5.github.entity.Github; import io.qyi.e5.github.entity.Github;
import com.baomidou.mybatisplus.extension.service.IService; import com.baomidou.mybatisplus.extension.service.IService;
import io.qyi.e5.github.entity.UserInfo;
/** /**
* <p> * <p>
@ -12,5 +14,13 @@ import com.baomidou.mybatisplus.extension.service.IService;
* @since 2020-02-24 * @since 2020-02-24
*/ */
public interface IGithubService extends IService<Github> { public interface IGithubService extends IService<Github> {
String getAccessToken(String code);
String getUserEmail(String access_token) throws Exception;
UserInfo getUserInfo(String access_token);
Github selectOne(QueryWrapper<Github> queryWrapper);
void insert(Github github);
} }

View File

@ -1,11 +1,22 @@
package io.qyi.e5.github.service.impl; package io.qyi.e5.github.service.impl;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.qyi.e5.github.entity.Github; import io.qyi.e5.github.entity.Github;
import io.qyi.e5.github.entity.UserInfo;
import io.qyi.e5.github.mapper.GithubMapper; import io.qyi.e5.github.mapper.GithubMapper;
import io.qyi.e5.github.service.IGithubService; import io.qyi.e5.github.service.IGithubService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.qyi.e5.util.StringUtil;
import io.qyi.e5.util.netRequest.OkHttpRequestUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.Map;
/** /**
* <p> * <p>
* 服务实现类 * 服务实现类
@ -16,5 +27,80 @@ import org.springframework.stereotype.Service;
*/ */
@Service @Service
public class GithubServiceImpl extends ServiceImpl<GithubMapper, Github> implements IGithubService { public class GithubServiceImpl extends ServiceImpl<GithubMapper, Github> implements IGithubService {
@Value("${github.client_id}")
private String client_id;
@Value("${github.client_secret}")
private String client_secret;
@Override
public String getAccessToken(String code) {
Map<String, Object> par = new HashMap<>();
par.put("client_id", client_id);
par.put("client_secret", client_secret);
par.put("code", code);
Map<String, Object> head = new HashMap<>();
head.put("Content-Type", "application/x-www-form-urlencoded");
String s = null;
try {
s = OkHttpRequestUtils.doPost("https://github.com/login/oauth/access_token", head, par);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(s);
Map<String, String> map = StringUtil.ParsingUrl(s);
return map.get("access_token");
}
@Override
public String getUserEmail(String access_token) throws Exception {
Map<String, Object> head = new HashMap<>();
head.put("Authorization", "token " + access_token);
head.put("Content-Type", "application/vnd.github.machine-man-preview+json");
String s = OkHttpRequestUtils.doGet("https://api.github.com/user/emails", head, null);
System.out.println(s);
JSONArray jsonArray = JSON.parseArray(s);
if (!jsonArray.isEmpty()) {
for (int i = 0; i < jsonArray.size(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
// 电子邮件是主要的并且已通过验证
if (jsonObject.getBoolean("primary") && jsonObject.getBoolean("verified")) {
return jsonObject.getString("email");
}
}
}
return null;
}
@Override
public UserInfo getUserInfo(String access_token) {
Map<String, Object> head = new HashMap<>();
head.put("Authorization", "token " + access_token);
head.put("Content-Type", "application/vnd.github.machine-man-preview+json");
try {
String s = OkHttpRequestUtils.doGet("https://api.github.com/user", head, null);
JSONObject jsonObject = JSON.parseObject(s);
UserInfo userInfo = new UserInfo();
if (!jsonObject.isEmpty()) {
userInfo.setLogin(jsonObject.getString("login"));
userInfo.setName(jsonObject.getString("name"));
userInfo.setAvatar_url(jsonObject.getString("avatar_url"));
userInfo.setGithub_id(jsonObject.getIntValue("id"));
userInfo.setNode_id(jsonObject.getString("node_id"));
}
return userInfo;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
public Github selectOne(QueryWrapper<Github> queryWrapper) {
return baseMapper.selectOne(queryWrapper);
}
@Override
public void insert(Github github) {
baseMapper.insert(github);
}
} }

View File

@ -0,0 +1,15 @@
package io.qyi.e5.outlook.bean;
import lombok.Data;
/**
* @program: e5
* @description:
* @author: 落叶随风
* @create: 2020-04-04 22:34
**/
@Data
public class OutlookVo {
private String clientId;
private String clientSecret;
}

View File

@ -1,11 +1,15 @@
package io.qyi.e5.outlook.controller; package io.qyi.e5.outlook.controller;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.qyi.e5.bean.result.Result; import io.qyi.e5.bean.result.Result;
import io.qyi.e5.bean.result.ResultEnum; import io.qyi.e5.bean.result.ResultEnum;
import io.qyi.e5.config.security.UsernamePasswordAuthenticationToken; import io.qyi.e5.config.security.UsernamePasswordAuthenticationToken;
import io.qyi.e5.outlook.bean.OutlookVo;
import io.qyi.e5.outlook.entity.Outlook;
import io.qyi.e5.outlook.service.IOutlookService; import io.qyi.e5.outlook.service.IOutlookService;
import io.qyi.e5.util.ResultUtil; import io.qyi.e5.util.ResultUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
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;
@ -56,4 +60,18 @@ public class OutlookController {
} }
return ResultUtil.error(ResultEnum.UNKNOWN_ERROR); return ResultUtil.error(ResultEnum.UNKNOWN_ERROR);
} }
@GetMapping("/getOutlookInfo")
public Result getOutlookInfo(){
UsernamePasswordAuthenticationToken authentication = (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
int github_id = authentication.getGithub_id();
QueryWrapper<Outlook> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("github_id", github_id);
Outlook one = outlookService.getOne(queryWrapper);
OutlookVo vo = new OutlookVo();
System.out.println(one);
if (one != null) {
BeanUtils.copyProperties(one,vo);
}
return ResultUtil.success(vo);
}
} }

View File

@ -1,18 +0,0 @@
package io.qyi.e5.service.github;
import io.qyi.e5.github.entity.UserInfo;
/**
* @program: msgpush
* @description:
* @author: 落叶随风
* @create: 2020-02-20 00:47
**/
public interface GithubService {
String getAccessToken(String code);
String getUserEmail(String access_token) throws Exception;
UserInfo getUserInfo(String access_token);
}

View File

@ -1,90 +0,0 @@
package io.qyi.e5.service.github.impl;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import io.qyi.e5.github.entity.UserInfo;
import io.qyi.e5.service.github.GithubService;
import io.qyi.e5.util.StringUtil;
import io.qyi.e5.util.netRequest.OkHttpRequestUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.Map;
/**
* @program: msgpush
* @description:
* @author: 落叶随风
* @create: 2020-02-20 00:56
**/
@Service("GithubService")
public class GithubServiceImpl implements GithubService {
@Value("${github.client_id}")
private String client_id;
@Value("${github.client_secret}")
private String client_secret;
@Override
public String getAccessToken(String code) {
Map<String, Object> par = new HashMap<>();
par.put("client_id", client_id);
par.put("client_secret", client_secret);
par.put("code", code);
Map<String, Object> head = new HashMap<>();
head.put("Content-Type", "application/x-www-form-urlencoded");
String s = null;
try {
s = OkHttpRequestUtils.doPost("https://github.com/login/oauth/access_token", head, par);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(s);
Map<String, String> map = StringUtil.ParsingUrl(s);
return map.get("access_token");
}
@Override
public String getUserEmail(String access_token) throws Exception {
Map<String, Object> head = new HashMap<>();
head.put("Authorization", "token " + access_token);
head.put("Content-Type", "application/vnd.github.machine-man-preview+json");
String s = OkHttpRequestUtils.doGet("https://api.github.com/user/emails", head, null);
System.out.println(s);
JSONArray jsonArray = JSON.parseArray(s);
if (!jsonArray.isEmpty()) {
for (int i = 0; i < jsonArray.size(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
// 电子邮件是主要的并且已通过验证
if (jsonObject.getBoolean("primary") && jsonObject.getBoolean("verified")) {
return jsonObject.getString("email");
}
}
}
return null;
}
@Override
public UserInfo getUserInfo(String access_token) {
Map<String, Object> head = new HashMap<>();
head.put("Authorization", "token " + access_token);
head.put("Content-Type", "application/vnd.github.machine-man-preview+json");
try {
String s = OkHttpRequestUtils.doGet("https://api.github.com/user", head, null);
JSONObject jsonObject = JSON.parseObject(s);
UserInfo userInfo = new UserInfo();
if (!jsonObject.isEmpty()) {
userInfo.setLogin(jsonObject.getString("login"));
userInfo.setName(jsonObject.getString("name"));
userInfo.setAvatar_url(jsonObject.getString("avatar_url"));
userInfo.setGithub_id(jsonObject.getIntValue("id"));
userInfo.setNode_id(jsonObject.getString("node_id"));
}
return userInfo;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}