Java实现社交登录
社交登录可以分为大体四个步骤
-
引导用户进入授权页
GET
https://api.weibo.com/oauth2/authorize?client_id=你的开发者app key&response_type=code&redirect_uri=授权成功跳转地址
-
授权认证成功后返回code
授权成功跳转地址?code=1fe1f1caf1d58e727b8cb00be74d4dc1
-
使用code和开发者相关信息换取access_token
POST
https://api.weibo.com/oauth2/access_token?client_id=你的开发者app key&client_secret=你的开发者app secret&grant_type=authorization_code&redirect_uri=授权成功重定向地址&code=上一步返回的授权码
-
后续使用access_token可访问公开的接口
根据用户ID获取用户信息接口
结果
- 注意:
- 使用Code换取AccessToken,Code只能用一次
- 同一个用户的accessToken一段时间是不会变化的(即使多次获取)
换取token核心代码
//换取token
@GetMapping("/oauth2/weibo/success")
public String weiboOauth2(@RequestParam("code") String code, HttpSession session) {
Map<String, String> map = new HashMap<>();
map.put("client_id", "微博给的id");
map.put("client_secret", "微博给的secret");
map.put("grant_type", "authorization_code");
map.put("redirect_uri", "成功后跳转的页面");
map.put("code", code);
Map<String, String> header = new HashMap<>();
try {
HttpResponse response = HttpUtils.doPost("https://api.weibo.com", "/oauth2/access_token", "post",header,null,map);
//成功获取到token 判断是登录还是注册 第一次登录要注册新用户
if (response.getStatusLine().getStatusCode() == 200) {
String json = EntityUtils.toString(response.getEntity());
SocialUserVo socialUserVo = JSONObject.parseObject(json, SocialUserVo.class);
R r = memberFeignService.Oauth2Login(socialUserVo);
if (r.getCode()==0){
MemberEntityResult loginUser = r.getData("data", new TypeReference<MemberEntityResult>() {
});
//存入session
session.setAttribute(AuthConstant.LOGIN_USER,loginUser);
log.info("用户登录成功:"+loginUser.toString());
System.out.println("用户登录成功:"+loginUser.toString());
//授权成功回首页
return "redirect:http://gulimall.com";
}
}
} catch (Exception e) {
log.error("用户登录失败",e);
e.printStackTrace();
}
log.error("用户登录失败");
return "redirect:http://auth.gulimall.com/login.html";
}