前后端分离微信扫码登陆token授权方案

前端Vue 后端SpringBoot

页面加载时声明一个变量state=’时间戳+6位随机数’,其中有个state参数需要我们传递,这个参数你传什么,微信回调的时候就会给你返回什么。 我们用之前生成那个state,当用户点击微信登录的按钮,我们就通过以state值为key和后端进行websocket连接

前端设置socket链接

1
2
3
4
5
6
7
8
9
10
11
let wsname = "ws://xxxxx:xxx/socketServer/" + this.state;
this.ws = new WebSocket(wsname);
//连接成功触发
this.ws.onopen = function(evt) {
};
//这个是接收后台发送信息的方法
this.ws.onmessage = function(evt) {
var data = JSON.parse(evt.data);
console.log(data)
//在这里判断后台给的用户信息和token 并进行相应的操作
})

websocket

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
@ServerEndpoint(value = "/socketServer/{userid}")
@Component
public class SocketServer {

private Session session;
private static Map<String,Session> sessionPool = new HashMap<String,Session>();
private static Map<String,String> sessionIds = new HashMap<String,String>();

/**
* 用户连接时触发
* @param session
* @param userid
*/
@OnOpen
public void open(Session session,@PathParam(value="userid")String userid){
this.session = session;
sessionPool.put(userid, session);
sessionIds.put(session.getId(), userid);
}

/**
* 收到信息时触发
* @param message
*/
@OnMessage
public void onMessage(String message){
System.out.println("当前发送人sessionid为"+session.getId()+"发送内容为"+message);
}

/**
* 连接关闭触发
*/
@OnClose
public void onClose(){
sessionPool.remove(sessionIds.get(session.getId()));
sessionIds.remove(session.getId());
}

/**
* 发生错误时触发
* @param session
* @param error
*/
@OnError
public void onError(Session session, Throwable error) {
error.printStackTrace();
}

/**
*信息发送的方法
* @param message
* @param userId
*/
public static void sendMessage(String message,String userId){
Session s = sessionPool.get(userId);
if(s!=null){
try {
s.getBasicRemote().sendText(message);
} catch (IOException e) {
e.printStackTrace();
}
}
}

}

提供给前端发送信息的api

1
2
3
4
5
6
7
8
@RequestMapping(value = "/sendpost")
public String sendPost(@RequestBody Params params) {
if (params.getJson() == null || params.getUserid() == null) {
return "error";
}
SocketServer.sendMessage(params.getJson(),params.getUserid());
return "success";
}

微信回调代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
@RequestMapping("/callback")
public void login(AuthCallback callback) {
AuthUser authUser = null;
AuthRequest authRequest = getAuthRequest();
AuthResponse response = authRequest.login(callback);
UserInfo user = new UserInfo();
if(response.getData() instanceof AuthUser) {
authUser = (AuthUser)response.getData();
//插入数据
WechatUserInfo wechatUser = new WechatUserInfo();
wechatUser.setOpenId(authUser.getRawUserInfo().get("openid").toString());
wechatUser.setNickName(authUser.getRawUserInfo().get("nickname").toString());
if (authUser.getRawUserInfo().get("sex") == null || authUser.getRawUserInfo().get("sex").toString().equals("")) {
wechatUser.setSex(0);
} else {
wechatUser.setSex(Integer.parseInt(authUser.getRawUserInfo().get("sex").toString()));
}
wechatUser.setHeadImgUrl(authUser.getRawUserInfo().get("headimgurl").toString());
user = userInfoService.wxCallBack(wechatUser);
}
// 添加访问记录
HttpServletRequest request = HttpContextUtil.getHttpServletRequest();
String ip = IPUtil.getIpAddr(request);
accessInfoService.save(new AccessInfo(ip, AddressUtil.getCityInfo(ip), DateUtil.formatDateTime(new Date())));
try {
//这里是将结果通过websocket返回给前端
System.out.println(HttpUtil.doPost(“http://www.niezhiliang.com:8086/websocket/sendpost”,user));
} catch (Exception e) {
e.printStackTrace();
}
}