单点登陆社交登陆 OAuth2.0
OAuth2.0
- 使用微博社交登陆
https://open.weibo.com/connect
- 开发手册
https://open.weibo.com/wiki/%E6%8E%88%E6%9D%83%E6%9C%BA%E5%88%B6%E8%AF%B4%E6%98%8E
更换 YOUR_CLIENT_ID App Key:1514335119
更换 YOUR_REGISTERED_REDIRECT_URI OAuth2.0 授权设置 授权回调页 成功的
https://api.weibo.com/oauth2/authorize?client_id=1514335119&response_type=code&redirect_uri=http://gulimall.com/success
第二
如果用户同意授权,页面跳转至 YOUR_REGISTERED_REDIRECT_URI/?code=CODE
eg http://guliimall.com/success?code=507925fe1eacf95eb09b875fe1cfcf83
第三
换取Access Token 访问令牌
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
使用Code换取Access Token,Code只能用一次
同—个用户的accessToken—段时间是不会变化的
社交登陆
授权登陆后 会有一个回调地址 并携带code 利用code 换取令牌 接下来操作
@GetMapping(/oauth2.0/weibo/success)
public String weibo(@RequestParam(code) String code) throws Exception {
//1.code 换取accessToken
//2.登陆成功调回首页
Map<String, String> map = new HashMap<>();
map.put(client_id, 1514335119);//应用id
map.put(client_secret, d3b69f4674eef8cf01602c4346660556);
map.put(grant_type, authorization_code);
map.put(redirect_uri, http://auth.gulimall.com/oauth2.0/weibo/success);//回调地址
map.put(code, code);//code
//String host, String path, String method, Map<String, String> headers,querys,bodys
HttpResponse response = HttpUtils.doPost(https://api.weibo.com, /oauth2/access_token, post,
new HashMap<>(), map, new HashMap<>());
//如果获取相应码 是200 成功
if (response.getStatusLine().getStatusCode() == 200) {
//获取响应实体类 EntityUtils转换
String json = EntityUtils.toString(response.getEntity());
//转换SocialUser.class 对象
SocialUser socialUser = JSON.parseObject(json, SocialUser.class);
//1.当用户第一次进网站 会自动注册 或者有了 就登陆
} else {
return redirect:http://auth.gulimall.com/login.html;
}
return redirect:http://gulimall.com;
}
- org.apache.http.util下的一个工具类
String json = EntityUtils.toString(response.getEntity());
//json 转换json object
JSONObject jsonObject = JSON.parseObject(json);
//直接获取属性
String name = jsonObject.getString(name);//直接获取名称