use of me.zhyd.oauth.model.AuthResponse in project matecloud by matevip.
the class SocialTokenGranter method getOAuth2Authentication.
@Override
protected OAuth2Authentication getOAuth2Authentication(ClientDetails client, TokenRequest tokenRequest) {
Map<String, String> parameters = new LinkedHashMap<>(tokenRequest.getRequestParameters());
String code = parameters.get("code");
String state = parameters.get("state");
String codeFromRedis = redisService.get(PREFIX + state).toString();
if (StrUtil.isBlank(code)) {
throw new UserDeniedAuthorizationException("未传入请求参数");
}
if (codeFromRedis == null) {
throw new UserDeniedAuthorizationException("openId已过期,请重新发起授权请求");
}
String oauthType = code.split("-")[0];
code = code.split("-")[1];
AuthRequest authRequest = factory.get(oauthType);
AuthCallback authCallback = AuthCallback.builder().code(code).state(state).build();
AuthResponse response = authRequest.login(authCallback);
log.info("【response】= {}", JSON.toJSON(response));
AuthUser authUser = null;
// 第三方登录成功
if (response.getCode() == AuthResponseStatus.SUCCESS.getCode()) {
authUser = (AuthUser) response.getData();
}
log.error("authUser:{}", JSON.toJSON(authUser));
Authentication userAuth = new SocialAuthenticationToken(authUser);
((AbstractAuthenticationToken) userAuth).setDetails(parameters);
try {
userAuth = authenticationManager.authenticate(userAuth);
} catch (AccountStatusException | BadCredentialsException ase) {
// covers expired, locked, disabled cases (mentioned in section 5.2, draft 31)
throw new InvalidGrantException(ase.getMessage());
}
if (userAuth == null || !userAuth.isAuthenticated()) {
throw new InvalidGrantException("Could not authenticate user: " + authUser);
}
OAuth2Request storedOAuth2Request = getRequestFactory().createOAuth2Request(client, tokenRequest);
return new OAuth2Authentication(storedOAuth2Request, userAuth);
}
use of me.zhyd.oauth.model.AuthResponse in project kms by mahonelau.
the class ThirdLoginController method loginThird.
@RequestMapping("/{source}/callback")
public String loginThird(@PathVariable("source") String source, AuthCallback callback, ModelMap modelMap) {
log.info("第三方登录进入callback:" + source + " params:" + JSONObject.toJSONString(callback));
AuthRequest authRequest = factory.get(source);
AuthResponse response = authRequest.login(callback);
log.info(JSONObject.toJSONString(response));
Result<JSONObject> result = new Result<JSONObject>();
if (response.getCode() == 2000) {
JSONObject data = JSONObject.parseObject(JSONObject.toJSONString(response.getData()));
String username = data.getString("username");
String avatar = data.getString("avatar");
String uuid = data.getString("uuid");
// 构造第三方登录信息存储对象
ThirdLoginModel tlm = new ThirdLoginModel(source, uuid, username, avatar);
// 判断有没有这个人
// update-begin-author:wangshuai date:20201118 for:修改成查询第三方账户表
LambdaQueryWrapper<SysThirdAccount> query = new LambdaQueryWrapper<SysThirdAccount>();
query.eq(SysThirdAccount::getThirdUserUuid, uuid);
query.eq(SysThirdAccount::getThirdType, source);
List<SysThirdAccount> thridList = sysThirdAccountService.list(query);
SysThirdAccount user = null;
if (thridList == null || thridList.size() == 0) {
// 否则直接创建新账号
user = saveThirdUser(tlm);
} else {
// 已存在 只设置用户名 不设置头像
user = thridList.get(0);
}
// update-begin-author:wangshuai date:20201118 for:从第三方登录查询是否存在用户id,不存在绑定手机号
if (oConvertUtils.isNotEmpty(user.getSysUserId())) {
String sysUserId = user.getSysUserId();
SysUser sysUser = sysUserService.getById(sysUserId);
String token = saveToken(sysUser);
modelMap.addAttribute("token", token);
} else {
modelMap.addAttribute("token", "绑定手机号," + "" + uuid);
}
// update-end-author:wangshuai date:20201118 for:从第三方登录查询是否存在用户id,不存在绑定手机号
// update-begin--Author:wangshuai Date:20200729 for:接口在签名校验失败时返回失败的标识码 issues#1441--------------------
} else {
modelMap.addAttribute("token", "登录失败");
}
// update-end--Author:wangshuai Date:20200729 for:接口在签名校验失败时返回失败的标识码 issues#1441--------------------
result.setSuccess(false);
result.setMessage("第三方登录异常,请联系管理员");
return "thirdLogin";
}
use of me.zhyd.oauth.model.AuthResponse in project springboot by LiJinHongPassion.
the class RestAuthController method login.
/**
* oauth平台中配置的授权回调地址,以本项目为例,在创建github授权应用时的回调地址应为:http://127.0.0.1:8443/oauth/callback/github
*/
@RequestMapping("/callback/{source}")
public Object login(@PathVariable("source") String source, AuthCallback callback) {
System.out.println("进入callback:" + source + " callback params:" + JSONObject.toJSONString(callback));
AuthRequest authRequest = getAuthRequest(source);
AuthResponse response = authRequest.login(callback);
System.out.println("callback:" + callback.toString());
System.out.println(JSONObject.toJSONString(response));
return response;
}
use of me.zhyd.oauth.model.AuthResponse in project kykms by mahonelau.
the class ThirdLoginController method loginThird.
@RequestMapping("/{source}/callback")
public String loginThird(@PathVariable("source") String source, AuthCallback callback, ModelMap modelMap) {
log.info("第三方登录进入callback:" + source + " params:" + JSONObject.toJSONString(callback));
AuthRequest authRequest = factory.get(source);
AuthResponse response = authRequest.login(callback);
log.info(JSONObject.toJSONString(response));
Result<JSONObject> result = new Result<JSONObject>();
if (response.getCode() == 2000) {
JSONObject data = JSONObject.parseObject(JSONObject.toJSONString(response.getData()));
String username = data.getString("username");
String avatar = data.getString("avatar");
String uuid = data.getString("uuid");
// 构造第三方登录信息存储对象
ThirdLoginModel tlm = new ThirdLoginModel(source, uuid, username, avatar);
// 判断有没有这个人
// update-begin-author:wangshuai date:20201118 for:修改成查询第三方账户表
LambdaQueryWrapper<SysThirdAccount> query = new LambdaQueryWrapper<SysThirdAccount>();
query.eq(SysThirdAccount::getThirdUserUuid, uuid);
query.eq(SysThirdAccount::getThirdType, source);
List<SysThirdAccount> thridList = sysThirdAccountService.list(query);
SysThirdAccount user = null;
if (thridList == null || thridList.size() == 0) {
// 否则直接创建新账号
user = saveThirdUser(tlm);
} else {
// 已存在 只设置用户名 不设置头像
user = thridList.get(0);
}
// update-begin-author:wangshuai date:20201118 for:从第三方登录查询是否存在用户id,不存在绑定手机号
if (oConvertUtils.isNotEmpty(user.getSysUserId())) {
String sysUserId = user.getSysUserId();
SysUser sysUser = sysUserService.getById(sysUserId);
String token = saveToken(sysUser);
modelMap.addAttribute("token", token);
} else {
modelMap.addAttribute("token", "绑定手机号," + "" + uuid);
}
// update-end-author:wangshuai date:20201118 for:从第三方登录查询是否存在用户id,不存在绑定手机号
// update-begin--Author:wangshuai Date:20200729 for:接口在签名校验失败时返回失败的标识码 issues#1441--------------------
} else {
modelMap.addAttribute("token", "登录失败");
}
// update-end--Author:wangshuai Date:20200729 for:接口在签名校验失败时返回失败的标识码 issues#1441--------------------
result.setSuccess(false);
result.setMessage("第三方登录异常,请联系管理员");
return "thirdLogin";
}
use of me.zhyd.oauth.model.AuthResponse in project mogu_blog_v2 by moxi624.
the class AuthRestApi method login.
/**
* oauth平台中配置的授权回调地址,以本项目为例,在创建gitee授权应用时的回调地址应为:http://127.0.0.1:8603/oauth/callback/gitee
*/
@RequestMapping("/callback/{source}")
public void login(@PathVariable("source") String source, AuthCallback callback, HttpServletResponse httpServletResponse) throws IOException {
log.info("进入callback:" + source + " callback params:" + JSONObject.toJSONString(callback));
AuthRequest authRequest = getAuthRequest(source);
AuthResponse response = authRequest.login(callback);
if (response.getCode() == Constants.NUM_5000) {
// 跳转到500错误页面
httpServletResponse.sendRedirect(webSiteUrl + Constants.STR_500);
return;
}
String result = JSONObject.toJSONString(response);
Map<String, Object> map = JsonUtils.jsonToMap(result);
Map<String, Object> data = JsonUtils.jsonToMap(JsonUtils.objectToJson(map.get(SysConf.DATA)));
Map<String, Object> token = new HashMap<>();
String accessToken = "";
if (data == null || data.get(SysConf.TOKEN) == null) {
// 跳转到500错误页面
httpServletResponse.sendRedirect(webSiteUrl + Constants.STR_500);
return;
} else {
token = JsonUtils.jsonToMap(JsonUtils.objectToJson(data.get(SysConf.TOKEN)));
accessToken = token.get(SysConf.ACCESS_TOKEN).toString();
}
Boolean exist = false;
User user;
// 判断user是否存在
if (data.get(SysConf.UUID) != null && data.get(SysConf.SOURCE) != null) {
user = userService.getUserBySourceAnduuid(data.get(SysConf.SOURCE).toString(), data.get(SysConf.UUID).toString());
if (user != null) {
exist = true;
} else {
user = new User();
}
} else {
return;
}
// 判断邮箱是否存在
if (data.get(SysConf.EMAIL) != null) {
String email = data.get(SysConf.EMAIL).toString();
user.setEmail(email);
}
// 判断用户性别
if (data.get(SysConf.GENDER) != null && !exist) {
String gender = data.get(SysConf.GENDER).toString();
if (SysConf.MALE.equals(gender)) {
user.setGender(EGender.MALE);
} else if (SysConf.FEMALE.equals(gender)) {
user.setGender(EGender.FEMALE);
} else {
user.setGender(EGender.UNKNOWN);
}
}
// 通过头像uid获取图片
String pictureList = this.pictureFeignClient.getPicture(user.getAvatar(), SysConf.FILE_SEGMENTATION);
List<String> photoList = webUtil.getPicture(pictureList);
Map<String, Object> picMap = (Map<String, Object>) JsonUtils.jsonToObject(pictureList, Map.class);
// 判断该用户是否含有头像信息
if (SysConf.SUCCESS.equals(picMap.get(SysConf.CODE)) && photoList.size() > 0) {
List<Map<String, Object>> picData = (List<Map<String, Object>>) picMap.get(SysConf.DATA);
String fileOldName = picData.get(0).get(SysConf.FILE_OLD_NAME).toString();
// 如果旧名称为blob表示是用户自定义的,代表用户在本网站使用了自定义头像,那么就再也不同步更新网站上的了
if (fileOldName.equals(data.get(SysConf.AVATAR)) || SysConf.BLOB.equals(fileOldName)) {
user.setPhotoUrl(photoList.get(0));
} else {
updateUserPhoto(data, user);
}
} else {
// 当获取头像失败时,需要从网站上进行获取
updateUserPhoto(data, user);
}
if (data.get(SysConf.NICKNAME) != null) {
user.setNickName(data.get(SysConf.NICKNAME).toString());
}
if (user.getLoginCount() == null) {
user.setLoginCount(0);
} else {
user.setLoginCount(user.getLoginCount() + 1);
}
// 获取浏览器,IP来源,以及操作系统
user = userService.serRequestInfo(user);
// 暂时将token也存入到user表中,为了以后方便更新redis中的内容
user.setValidCode(accessToken);
if (exist) {
user.updateById();
} else {
user.setUuid(data.get(SysConf.UUID).toString());
user.setSource(data.get(SysConf.SOURCE).toString());
String userName = PROJECT_NAME_EN.concat(Constants.SYMBOL_UNDERLINE).concat(user.getSource()).concat(Constants.SYMBOL_UNDERLINE).concat(user.getUuid());
user.setUserName(userName);
// 如果昵称为空,那么直接设置用户名
if (StringUtils.isEmpty(user.getNickName())) {
user.setNickName(userName);
}
// 默认密码
user.setPassWord(MD5Utils.string2MD5(DEFAULE_PWD));
// 设置是否开启评论邮件通知【关闭】
user.setStartEmailNotification(EOpenStatus.CLOSE_STATUS);
user.insert();
}
// 过滤密码
user.setPassWord("");
if (user != null) {
// 将从数据库查询的数据缓存到redis中
stringRedisTemplate.opsForValue().set(RedisConf.USER_TOKEN + Constants.SYMBOL_COLON + accessToken, JsonUtils.objectToJson(user), userTokenSurvivalTime, TimeUnit.HOURS);
}
httpServletResponse.sendRedirect(webSiteUrl + "?token=" + accessToken);
}
Aggregations