提交 f096060c 编写于 作者: laizhilong's avatar laizhilong

qq授权登录

上级 2decea9b
......@@ -13,11 +13,10 @@
$(function () {
var code = getUrlParam('code');
var state = getUrlParam('state');
alert("code:" + code + "\n state:" + state);
// alert("code:" + code + "\n state:" + state);
if (code && state) {
// 通过授权code请求后台
// alert(window.location.hostname);
var opt = {"code": code, "state": state};
$.ajax({
type: "post",
......@@ -42,7 +41,7 @@
window.location.href = "../index";
} else {
// 跳转微信绑定
window.location.href = "../#/weixinLoginRedirect?code=" + code + "&state=" + state;
window.location.href = "../#/qqLoginRedirect?code=" + code + "&state=" + state;
}
}
},
......
......@@ -259,8 +259,6 @@
* @param thirdpart
*/
public tencentHandleClick(thirdpart: any) {
this.$Message.warning("QQ授权登录暂未支持,敬请期待");
return;
// 截取地址,拼接需要部分组成新地址
const baseUrl = this.getNeedLocation();
......@@ -318,8 +316,6 @@
* @param thirdpart
*/
public wechatHandleClick(thirdpart: any) {
// this.$Message.warning("微信授权登录暂未支持,敬请期待");
// 从后台获取微信开放平台提供的appid
const get: Promise<any> = this.$http.get('/uaa/getWechatAppId');
get.then((response: any) => {
......@@ -375,9 +371,6 @@
* @param thirdpart
*/
public dingtalkHandleClick(thirdpart: any) {
// this.$Message.warning("钉钉授权登录暂未支持,敬请期待");
// return;
// 从后台获取钉钉开放平台提供的appid
const get: Promise<any> = this.$http.get('/uaa/getDingtalkAppId');
get.then((response: any) => {
......
......@@ -81,6 +81,23 @@
public BtnContent: any = "注册并绑定QQ";
/**
* QQ互联授权成功返回的code和state
*/
public code: any;
public state: any;
/**
* QQ用户身份的唯一标识
*/
public openid: any;
/**
* QQ用户名称
*/
public nickname: any;
/**
* 应用名称
*
......@@ -113,12 +130,6 @@
}
};
// 注册方式
public registerType: any = "commom";
// 用户身份的唯一标识。建议保存在本地,以便用户下次登录时可对应到其之前的身份信息,不需要重新授权。
public openId: any;
// 表示当前用户在此网站/应用的登录状态与授权信息,建议保存在本地。
public accessToken: any;
/**
* 生命周期Create
......@@ -134,39 +145,78 @@
*/
public mounted() {
let _this = this;
// 获取qq授权登录的信息,用于后台请求
if (window.QC.Login.check()) {
console.log("qq已经登录");
window.QC.Login.getMe(function(openId:string, accessToken:string){
_this.openId = openId;
_this.accessToken = accessToken;
_this.registerType = "qq";
localStorage.setItem("openId",openId);
localStorage.setItem("accessToken",accessToken);
});
// 根据openId查用户
this.queryUserByOpenId(this.openId);
// 从url获取授权code和state
this.code = this.$route.query.code;
if (!this.code) {
this.code = this.getUrlParam('code');
}
this.state = this.$route.query.state;
if (!this.state) {
this.state = this.getUrlParam('state');
}
// alert("code:" + this.wechatCode + "\nstate:" + this.wechatState);
// 获取失败,回到登录页
if (!this.code || !this.state) {
this.$message.error("微信授权,获取code失败");
this.goLogin();
}
else {
// 根据code获取QQ用户信息
this.getQQUserInfoByCode(this.code);
}
}
/**
* 监听语言变化
*
* @memberof Login
*/
@Watch('$i18n.locale')
onLocaleChange(newval: any, val: any) {
this.setRules();
}
/**
* 跳转登录页面
*
* @memberof Register
*/
public goLogin(): void {
const _this = this;
_this.$router.push('/login');
}
/**
* 获取url参数
*/
public getUrlParam(name: any) {
var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
var r = window.location.search.substr(1).match(reg); //匹配目标参数
if (r != null) return unescape(r[2]);
return null; //返回参数值
}
/**
* 根据openId查用户
* 1.没系统账号的,进行注册并绑定QQ
* 2.有系统账号的,直接登录
* @param openId
* 根据code获取微信用户信息
*/
private queryUserByOpenId(openId: any) {
private getQQUserInfoByCode(code: any) {
var param: any = {};
param.openId = openId;
const post: Promise<any> = this.$http.post('uaa/queryUserByOpenId', param, true);
param.code = code;
const post: Promise<any> = this.$http.post('/uaa/getQQUserInfoByCode', param, true);
post.then((response: any) => {
if (response && response.status === 200) {
const data = response.data;
if (data.ibzuser) {
this.form.loginname = data.ibzuser.loginname;
this.form.password = data.ibzuser.password;
// 直接登录
this.countDown(0);
if (data && data.openid) {
this.openid = data.openid;
this.nickname = data.nickname;
} else {
this.$Message.error({
content: "获取QQ用户信息失败,请重新授权",
duration: 3,
closable: true
});
}
}
}).catch((e: any) => {
......@@ -179,34 +229,12 @@
});
} else {
this.$Message.error({
content: "错误",
content: "获取QQ用户信息失败,请重新授权",
duration: 3,
closable: true
});
}
});
}
/**
* 监听语言变化
*
* @memberof Login
*/
@Watch('$i18n.locale')
onLocaleChange(newval: any, val: any) {
this.setRules();
}
/**
* 跳转登录页面
*
* @memberof Register
*/
public goLogin(): void {
const _this = this;
_this.$router.push('/login');
}
......@@ -228,38 +256,40 @@
}
var param: any = this.form;
if (this.registerType === "qq") {
param.registerType = "qq";
param.openId = this.openId;
param.accessToken = this.accessToken;
if (this.code && this.state) {
param.code = this.code;
param.state = this.state;
param.openid = this.openid;
param.nickname = this.nickname;
}
else {
this.$Message.error({
content: "注册并绑定QQ失败",
duration: 3,
closable: true
});
this.$message.error("QQ授权,获取code失败");
return;
}
const post: Promise<any> = this.$http.post('/uaa/register', param, true);
const post: Promise<any> = this.$http.post('/uaa/bindQQtoRegister', param, true);
post.then((response: any) => {
if (response && response.status === 200) {
const data = response.data;
if (data && data.ibzuser) {
this.$Message.success({
content: "注册成功,用户名:" + data.ibzuser.loginname + ",密码:" + data.ibzuser.password,
duration: 3,
closable: true
});
} else {
if (data) {
this.$Message.success({
content: "注册成功",
duration: 3,
closable: true
content: "注册成功,正在登录"
});
if (data.token) {
localStorage.setItem('token', data.token);
}
if (data.user) {
localStorage.setItem('user', JSON.stringify(data.user));
}
if (data.ibzuser) {
let ibzuser: any = JSON.stringify(data.ibzuser);
// 设置cookie,保存账号密码7天
this.setCookie(ibzuser.loginname, ibzuser.password, 7);
// 跳转首页
const url: any = '*';
this.$router.push({path: url});
}
}
// 3s后自动登录
this.countDown(3);
}
}).catch((e: any) => {
const data = e.data;
......
......@@ -203,15 +203,7 @@
const data = response.data;
if (data && data.ibzuser) {
this.$Message.success({
content: "注册成功,用户名:" + data.ibzuser.loginname + ",密码:" + data.ibzuser.password,
duration: 3,
closable: true
});
} else {
this.$Message.success({
content: "注册成功",
duration: 3,
closable: true
content: "注册成功,正在登录"
});
}
// 自动登录
......
......@@ -87,7 +87,7 @@
public state: any;
/**
* 钉钉用户身份的唯一标识
* 微信用户身份的唯一标识
*/
public openid: any;
......
......@@ -118,6 +118,10 @@ public class DevBootSecurityConfig extends WebSecurityConfigurerAdapter {
.antMatchers("/uaa/getDingtalkUserInfoByCode").permitAll()
.antMatchers("/uaa/bindDingtalkToRegister").permitAll()
.antMatchers("/uaa/getQQAppId").permitAll()
.antMatchers("/uaa/queryQQUserByCode").permitAll()
.antMatchers("/uaa/getQQUserInfoByCode").permitAll()
.antMatchers("/uaa/bindQQtoRegister").permitAll()
.anyRequest().authenticated()
// 防止iframe 造成跨域
.and().headers().frameOptions().disable();
......
package cn.ibizlab.core.uaa.extensions.service;
import cn.ibizlab.util.domain.IBZUSER;
import cn.ibizlab.util.errors.BadRequestAlertException;
import cn.ibizlab.util.helper.HttpUtils;
import cn.ibizlab.util.service.IBZUSERService;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import java.io.UnsupportedEncodingException;
/**
* 实体[IBZUSER] QQ用户注册接口实现
*/
@Service
@Slf4j
public class UserQQRegisterService {
@Autowired
private IBZUSERService ibzuserService;
/**
* 注册
*
* @param ibzuser
*/
public void toRegister(IBZUSER ibzuser) {
// 创建ibzuser
boolean flag = ibzuserService.save(ibzuser);
if (!flag) {
throw new BadRequestAlertException("注册失败", "UserQQRegisterService", "");
}
}
/**
* 通过code获取QQ用户信息
*
* @param code
* @param qqRedirectUri
* @param qqAppid
* @param qqAppkey
* @return
*/
public JSONObject requestQQUserByCode(String code, String qqRedirectUri, String qqAppid, String qqAppkey) {
JSONObject returnObj = null;
try {
// 1.根据code获取access_token
String getAccessTokenUrl = "https://graph.qq.com/oauth2.0/token?" +
"grant_type=authorization_code" +
"&client_id=" + qqAppid +
"&client_secret=" + qqAppkey +
"&code=" + code +
"&redirect_uri=" + qqRedirectUri;
String responserStr = HttpUtils.get(getAccessTokenUrl, null, null);
JSONObject responseObj = new JSONObject();
if (StringUtils.isEmpty(responserStr)) {
throw new BadRequestAlertException("QQ服务端获取access_token失败!", "UserQQRegisterService", "");
}else {
String[] split = responserStr.split("&");
for (int i = 0; i < split.length; i++) {
if (split[i].indexOf("=")!=-1){
String[] split1 = split[i].split("=");
if (split1.length>0) {
responseObj.put(split1[0], split1[1]);
continue;
}
}
}
}
String access_token = responseObj.getString("access_token");
String refresh_token = responseObj.getString("refresh_token");
// 2.使用access_token来获取用户的OpenID
String openid = null;
String getOpenIdUrl = "https://graph.qq.com/oauth2.0/me?access_token=" + access_token;
String responseStr2 = HttpUtils.get(getOpenIdUrl);
if (StringUtils.isEmpty(responseStr2)) {
throw new BadRequestAlertException("QQ服务端请求openid失败!", "UserQQRegisterService", "");
}else {
responseStr2 = responseStr2.replace("callback(","").replace(");","");
JSONObject responseObj2 = JSONObject.parseObject(responseStr2);
if (responseObj2.containsKey("openid")) {
openid = responseObj2.getString("openid");
}else {
throw new BadRequestAlertException("QQ服务端获取openid失败!", "UserQQRegisterService", "");
}
}
// 3.使用access_token以及OpenID来访问和修改用户数据
String getQQUserInfoUrl = "https://graph.qq.com/user/get_user_info?" +
"access_token=" + access_token +
"&oauth_consumer_key=" + qqAppid +
"&openid=" + openid;
returnObj = JSONObject.parseObject(HttpUtils.get(getQQUserInfoUrl, null, null));
if (StringUtils.isEmpty(returnObj)) {
throw new BadRequestAlertException("QQ服务端返回结果为空!", "UserQQRegisterService", "");
} else if (returnObj.getInteger("ret")!=0) {
throw new BadRequestAlertException("获取QQ用户信息失败!", "UserQQRegisterService", "");
} else {
returnObj.put("openid", openid);
}
} catch (UnsupportedEncodingException e) {
throw new BadRequestAlertException("连接微信服务端失败!", "UserQQRegisterService", "");
}
return returnObj;
}
}
\ No newline at end of file
......@@ -47,6 +47,8 @@ public class UserDingtalkRegisterResource {
@Value("${ibiz.auth.dingtalk.nickname:}")
private String DingtalkNickname;
private JSONObject DingtalkUserInfo;// 钉钉用户信息
/**
* 获取钉钉开放平台创建的网站应用appid
*/
......@@ -87,6 +89,7 @@ public class UserDingtalkRegisterResource {
// 将用户信息存到缓存,供当前人后续请求使用
DingtalkOpenid = openid;
DingtalkNickname = nickname;
DingtalkUserInfo = returnObj;
}
//根据openid查用户
......@@ -145,7 +148,7 @@ public class UserDingtalkRegisterResource {
* @return
*/
@PostMapping(value = "/uaa/bindDingtalkToRegister")
public ResponseEntity<JSONObject> thirdPartRegister(@RequestBody JSONObject param) {
public ResponseEntity<JSONObject> bindDingtalkToRegister(@RequestBody JSONObject param) {
JSONObject object = new JSONObject();
// 空校验
String loginname = param.getString("loginname");
......
package cn.ibizlab.api.rest.extensions;
import cn.ibizlab.core.uaa.extensions.service.UserQQRegisterService;
import cn.ibizlab.core.uaa.service.ISysPSSystemService;
import cn.ibizlab.util.domain.IBZUSER;
import cn.ibizlab.util.errors.BadRequestAlertException;
import cn.ibizlab.util.helper.CachedBeanCopier;
import cn.ibizlab.util.security.AuthTokenUtil;
import cn.ibizlab.util.security.AuthenticationUser;
import cn.ibizlab.util.service.AuthenticationUserService;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
@RestController
public class UserQQRegisterResource {
@Value("${ibiz.auth.qq.appid:}")// qq互联appid
@Autowired
private UserQQRegisterService userQQRegisterService;
@Autowired
private ISysPSSystemService iSysPSSystemService;
@Autowired
private AuthTokenUtil jwtTokenUtil;
@Autowired
@Qualifier("UAAUserService")
private AuthenticationUserService userDetailsService;
@Value("${ibiz.auth.qq.appid:101882103}")// qq互联appid
private String qqAppId;
@Value("${ibiz.auth.qq.appkey:}")// qq互联appkey
@Value("${ibiz.auth.qq.appkey:64ebdde56c1aeeacf0c312b49ddc42e1}")// qq互联appkey
private String qqAppKey;
@Value("${ibiz.auth.qq.redirect_uri:}")// qq互联应用回调地址
@Value("${ibiz.auth.qq.redirect_uri:http://passport.ibizlab.cn/assets/qqRedirect.html}")// qq互联应用回调地址
private String qqRedirectUri;
@Value("${ibiz.auth.qq.openid:}")
private String qqOpenid;
@Value("${ibiz.auth.qq.nickname:}")
private String qqNickname;
private JSONObject qqUserInfo;// qq用户信息
/**
* 获取QQ互联平台创建的网站应用appid
*/
@GetMapping(value = "/uaa/getQQAppId")
public ResponseEntity<JSONObject> getQQAppId() {
JSONObject obj = new JSONObject();
String appid = qqAppId;
if (!StringUtils.isEmpty(appid)) {
obj.put("appid", appid);
}
return ResponseEntity.ok(obj);
}
/**
* 根据code查QQ用户
*
* @param param
* @return
*/
@PostMapping(value = "/uaa/queryQQUserByCode")
public ResponseEntity<JSONObject> queryQQUserByCode(@RequestBody JSONObject param) {
JSONObject object = new JSONObject();
// 空校验
String code = param.getString("code");
if (StringUtils.isEmpty(code))
throw new BadRequestAlertException("code为空", "UserQQRegisterResource", "");
// 通过code获取QQ用户信息
String openid = null;
String nickname = null;
JSONObject returnObj = userQQRegisterService.requestQQUserByCode(code, qqRedirectUri, qqAppId, qqAppKey);
if (!StringUtils.isEmpty(returnObj) && !returnObj.containsKey("errcode")) {
openid = returnObj.getString("openid");
nickname = returnObj.getString("nickname");
// 将用户信息存到缓存,供当前人后续请求使用
qqOpenid = openid;
qqNickname = nickname;
qqUserInfo = returnObj;
}
//根据openid查用户
String sql = "select * from ibzuser where avatar=#{et.avatar}";
Map<String, Object> sqlParam = new HashMap<>();
sqlParam.put("avatar", openid);
List<JSONObject> select = iSysPSSystemService.select(sql, sqlParam);
// 该QQ用户注册过账号,登录系统
if (select.size() > 0) {
IBZUSER ibzuser = select.get(0).toJavaObject(IBZUSER.class);
object.put("ibzuser", ibzuser);
// 生成登录token信息
userDetailsService.resetByUsername(ibzuser.getLoginname());
AuthenticationUser user = userDetailsService.loadUserByLogin(ibzuser.getLoginname(), ibzuser.getPassword());
final String token = jwtTokenUtil.generateToken(user);
AuthenticationUser user2 = new AuthenticationUser();
CachedBeanCopier.copy(user, user2);
user2.setAuthorities(null);
user2.setPermissionList(null);
object.put("token", token);
object.put("user", user2);
}
return ResponseEntity.ok().body(object);
}
/**
* 根据code获取QQ用户信息
*
* @param param
* @return
*/
@PostMapping(value = "/uaa/getQQUserInfoByCode")
public ResponseEntity<JSONObject> getQQUserInfoByCode(@RequestBody JSONObject param) {
JSONObject object = new JSONObject();
// 空校验
String code = param.getString("code");
if (StringUtils.isEmpty(code))
throw new BadRequestAlertException("code为空", "UserQQRegisterResource", "");
// 通过code获取微信用户信息
String openid = qqOpenid;
String nickname = qqNickname;
object.put("openid", openid);
object.put("nickname", nickname);
return ResponseEntity.ok().body(object);
}
/**
* 绑定QQ并注册
*
* @param param
* @return
*/
@PostMapping(value = "/uaa/bindQQtoRegister")
public ResponseEntity<JSONObject> bindQQtoRegister(@RequestBody JSONObject param) {
JSONObject object = new JSONObject();
// 空校验
String loginname = param.getString("loginname");
String password = param.getString("password");
String code = param.getString("code");
String state = param.getString("state");
String openid = param.getString("openid");
if (StringUtils.isEmpty(openid)) {
openid = qqOpenid;
}
String nickname = param.getString("nickname");
if (StringUtils.isEmpty(nickname)) {
nickname = qqNickname;
}
if (StringUtils.isEmpty(loginname))
throw new BadRequestAlertException("用户名为空", "UserQQRegisterResource", "");
if (StringUtils.isEmpty(password))
throw new BadRequestAlertException("密码为空", "UserQQRegisterResource", "");
if (StringUtils.isEmpty(code))
throw new BadRequestAlertException("QQ授权code为空", "UserQQRegisterResource", "");
if (StringUtils.isEmpty(state))
throw new BadRequestAlertException("QQ授权state为空", "UserQQRegisterResource", "");
// 检查用户名是否已被注册
String sql = "select loginname from ibzuser where loginname=#{et.loginname}";
Map<String, Object> sqlParam = new HashMap<>();
sqlParam.put("loginname", loginname);
List<JSONObject> select = iSysPSSystemService.select(sql, sqlParam);
if (select.size() > 0)
throw new BadRequestAlertException("该用户名已被注册", "UserQQRegisterResource", "");
IBZUSER ibzuser = new IBZUSER();
if (StringUtils.isEmpty(openid)) {
// 通过code获取微信用户信息
JSONObject returnObj = userQQRegisterService.requestQQUserByCode(code, qqRedirectUri ,qqAppId , qqAppKey);
if (!StringUtils.isEmpty(returnObj)) {
if (returnObj.containsKey("openid")) {
// 微信注册
String uuid = UUID.randomUUID().toString();
ibzuser.setPassword(password);
ibzuser.setLoginname(loginname);
ibzuser.setUserid("tencent-" + uuid);
ibzuser.setPersonname(returnObj.getString("nickname"));
ibzuser.setNickname(returnObj.getString("nickname"));
ibzuser.setAvatar(returnObj.getString("openid"));
userQQRegisterService.toRegister(ibzuser);
}else {
throw new BadRequestAlertException("获取QQ授权用户相关信息失败!", "UserQQRegisterResource", "");
}
}else {
throw new BadRequestAlertException("获取QQ授权用户相关信息失败!", "UserQQRegisterResource", "");
}
} else {
// 已经有微信用户信息直接注册
String uuid = UUID.randomUUID().toString();
ibzuser.setPassword(password);
ibzuser.setLoginname(loginname);
ibzuser.setUserid("tencent-" + uuid);
ibzuser.setPersonname(nickname);
ibzuser.setNickname(nickname);
ibzuser.setAvatar(openid);
userQQRegisterService.toRegister(ibzuser);
}
// 注册成功,登录系统
if (!StringUtils.isEmpty(ibzuser)) {
object.put("ibzuser", ibzuser);
}
// 生成登录token信息
userDetailsService.resetByUsername(ibzuser.getLoginname());
AuthenticationUser user = userDetailsService.loadUserByLogin(ibzuser.getLoginname(), ibzuser.getPassword());
final String token = jwtTokenUtil.generateToken(user);
AuthenticationUser user2 = new AuthenticationUser();
CachedBeanCopier.copy(user, user2);
user2.setAuthorities(null);
user2.setPermissionList(null);
object.put("token", token);
object.put("user", user2);
return ResponseEntity.ok().body(object);
}
}
......@@ -48,6 +48,7 @@ public class UserWechatRegisterResource {
@Value("${ibiz.auth.wechat.nickname:}")
private String WechatNickname;
private JSONObject WechatUserInfo;// 微信用户信息
public static final String TOKEN = ""; // 这里的token要和微信公众测试号网页填写的token一致
/**
......@@ -122,6 +123,7 @@ public class UserWechatRegisterResource {
// 将用户信息存到缓存,供当前人后续请求使用
WechatOpenid = openid;
WechatNickname = nickname;
WechatUserInfo = returnObj;
}
//根据openid查用户
......@@ -181,7 +183,7 @@ public class UserWechatRegisterResource {
* @return
*/
@PostMapping(value = "/uaa/bindWechatToRegister")
public ResponseEntity<JSONObject> thirdPartRegister(@RequestBody JSONObject param) {
public ResponseEntity<JSONObject> bindWechatToRegister(@RequestBody JSONObject param) {
JSONObject object = new JSONObject();
// 空校验
String loginname = param.getString("loginname");
......
Markdown 格式
0% or
您添加了 0 到此讨论。请谨慎行事。
先完成此消息的编辑!
想要评论请 注册