美文网首页
使用github第三方登录

使用github第三方登录

作者: _麻辣香锅不要辣 | 来源:发表于2019-07-31 21:00 被阅读0次

OAuth 2.0简介
github开发者流程

大致流程

1.先在github中注册的app,获取ClientId和ClientSecret
2.有了开发者的ClientId和ClientSecret后,重定向到:https://github.com/login/oauth/authorize?client_id=" + client_id

@RequestMapping("")
    public String login() {
        System.out.println(client_id);
        return "redirect:https://github.com/login/oauth/authorize?client_id=" + client_id;
    }

3.此时会有一个授权页面,如果用户同意授权之后,链接地址就会跳转到我们之前注册app时填的callback的url.并会带上一个code
4.在callback中发送post请求获取AccessToken,然后根据AccessToken来获取用户信息

callback
 @RequestMapping("/callback")
    @ResponseBody
    public Object callback(@RequestParam("code") String code) {
        System.out.println(code);
        String url = "https://github.com/login/oauth/access_token";
        String accessToken = loginService.getAccessToken(url, code, client_id, client_secret);
        System.out.println(accessToken);
       // return accessToken;
        String url2 = "https://api.github.com/user?access_token=";
        String token = accessToken.split("&")[0].split("=")[1];
        System.out.println(token);
        Object userInfo = loginService.getUserInfo(url2+token);
        return userInfo;
    }
LoginService
public class LoginService {
    public static final MediaType MEDIA_TYPE
            = MediaType.get("application/json; charset=utf-8");

    public String getAccessToken(String url,String code,String client_id,String client_secret) {
        HashMap<String, String> map = new HashMap<>();
        map.put("code", code);
        map.put("client_id", client_id);
        map.put("client_secret", client_secret);

        OkHttpClient client = new OkHttpClient();
        RequestBody body = RequestBody.create(MEDIA_TYPE, JSON.toJSONString(map));
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();
        try (Response response = client.newCall(request).execute()) {
            return response.body().string();
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    public String getUserInfo(String url){
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(url)
                .build();

        try (Response response = client.newCall(request).execute()) {
            return response.body().string();
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
}

相关文章

网友评论

      本文标题:使用github第三方登录

      本文链接:https://www.haomeiwen.com/subject/mvjxdctx.html