例子: 京东商城 ,微博 ,用户三者之间的关系
第一方:用户
第二方:京东商城
第三方:微博
用户不希望在京东商城上注册,可以授权微博使用微博上的用户信息进行登录京东商城。
授权流程:
地址一:授权页面的跳转地址
地址二:授权后的回调地址(将code回调给商城的地址)
地址三:用code交换授权码access_token的地址(在交换过程中要加入商城的Secret的应用密钥)
https://api.weibo.com/oauth2/access_token?client_id=YOUR_CLIENT_ID&client_secret=YOUR_CLIENT_SECRET&grant_type=authorization_code&redirect_uri=YOUR_REGISTERED_REDIRECT_URI&code=CODE
地址四:用access_token交换用户信息的地址(第三方提供的接口api地址,使用授权码+uid交换用户信息)
https://api.weibo.com/2/users/show.json?access_token=2.00S4TE5GH4psNBf534795d1677YqPB&uid=1
6 授权调用演示
授权页面:
https://api.weibo.com/oauth2/authorize?client_id=25920146&response_type=code&redirect_uri=http://passport.gmall.com:8090/vlogin
@RequestMapping("vlogin")
public String vlogin(String code, HttpServletRequest request) {
// 换取access_token
String access_token_url = "https://api.weibo.com/oauth2/access_token?client_id= 25920146&client_secret=dc8de1392f642a01259b136ff8e970b9&grant_type=authorization_code&redirect_uri=http://passport.gmall.com:8090/vlogin&code=e211655dd6c78a66fcfcfdff552424f6";
Map<String,String> map = new HashMap<String,String>();
map.put("client_id","25920146");
map.put("client_secret","dc8de1392f642a01259b136ff8e970b9");
map.put("grant_type","authorization_code");
map.put("redirect_uri","http://passport.gmall.com:8090/vlogin");
map.put("code",code);
String access_json = HttpclientUtil.doPost("https://api.weibo.com/oauth2/access_token", map);
System.out.println(access_json);
Map<String,String> map_access_json = new HashMap<String,String>();
Map access_map = JSON.parseObject(access_json, map_access_json.getClass());
// 获得第三方用户数据
String access_token = (String)access_map.get("access_token");
String uid = (String)access_map.get("uid");// uid uidStr
UmsMember umsMember = new UmsMember();
umsMember = userService.isUidExists(uid);
if(umsMember==null){
String show_url = "https://api.weibo.com/2/users/show.json?access_token="+access_token+"&uid="+uid;
String user_json = HttpclientUtil.doGet(show_url);
Map<String,String> map_user_json = new HashMap<String,String>();
Map user_map = JSON.parseObject(user_json, map_user_json.getClass());
System.out.println(user_map);
// 存入数据库
umsMember.setNickname((String)user_map.get("screen_name"));
umsMember.setUsername((String)user_map.get("name"));
umsMember.setSourceType("2");
umsMember.setSourceUid((String)user_map.get("idstr"));
umsMember.setCreateTime(new Date());
umsMember.setAccessToken(access_token);
umsMember.setAccessCode(code);
umsMember = userService.addUser(umsMember);
}
// 根据用户信息生成token
String key = "athouruisso";
String ip = request.getRemoteAddr();
Map<String,Object> token_map = new HashMap<>();
token_map.put("nickname",umsMember.getNickname());
token_map.put("memberId",umsMember.getId());
String token = JwtUtil.encode(key, token_map, ip);
// 将生成的token和登录用户信息保存在缓存中一分
userService.addUserCache(token,umsMember);
return "redirect:http://192.168.5.3:8090/index?newToken="+token;
}