使用SpringBoot+OkHttp+fastjson實現Github的OAuth第三方登陸

1、在GitHub上建立一個OAuth


Settings.png
Developer settings.png
OAuthApps.png
建立oauth.png
建立成功.png


2、OAuth的原理

Spring官方文檔
圖解.png前端


3、OkHttp的使用

OkHttp官方網站git

1.Post

Post.png

代碼示例
//官方文檔:        public static final MediaType JSON  
//                = MediaType.get("application/json; charset=utf-8");  
  MediaType mediaType = MediaType.get("application/json; charset=utf-8");//去掉前綴,而且修改MediaType對象名,由於一會使用fastjson變量會重名  
  OkHttpClient client = new OkHttpClient();//第二句照抄
  RequestBody body = RequestBody.create(json,mediaType);//直接複製方法體中的內容
  Request request = new Request.Builder()  
        .url("")//填寫要發送請求的地址  
        .post(body)  
        .build();  
try (Response response = client.newCall(request).execute()) {  
         return response.body().string();//返回的字符串(json)
}
2.Get

Get.png

代碼示例
OkHttpClient client = new OkHttpClient();//同上
  Request request = new Request.Builder()//直接複製方法體中的內容
      .url(url)//同上
      .build();

  try (Response response = client.newCall(request).execute()) {
    return response.body().string();//同上
  }

4、fastJson的使用

JSON.toJSONString(實體類)//將實體類轉換爲JSON字符串
JSON.parseObject(string, 實體類.class);//將JSON字符串轉換爲實體類

5、代碼示例

前端代碼github

<a href="https://github.com/login/oauth/authorize?client_id=xxx&redirect_uri=http://127.0.0.1:8080/xxx&scope=user&state=1">Login</a>
//scope和state不寫可能會報錯
@Controller  
public class AuthorizeController {  
  
  @Autowired  
  GithubProvider githubProvider;  
  
  @GetMapping("/callback")  
  public String callback(@RequestParam(name ="code") String code, @RequestParam(name ="state") String state){  
      AccessTokenDTO accessTokenDTO = new AccessTokenDTO();  
      accessTokenDTO.setClient_id("");  
      accessTokenDTO.setClient\_secret("");  
      accessTokenDTO.setCode(code);  
      accessTokenDTO.setState(state);  
      accessTokenDTO.setRedirect\_uri("https://github.com/login/oauth/access_token");  
      String token = githubProvider.getAccessToken(accessTokenDTO);  
      GithubUser githubUser = githubProvider.getUser(token);  
      return "index";  
  }  
  
}
@Component  
public class GithubProvider {  
  
    public String getAccessToken(AccessTokenDTO accessTokenDTO){  
        MediaType mediaType = MediaType.get("application/json; charset=utf-8");
        OkHttpClient client = new OkHttpClient();
        RequestBody body = RequestBody.create(JSON.toJSONString(accessTokenDTO),mediaType);//用fastjson將實體類轉換爲json字符串傳入
        Request request = new Request.Builder()  
                 .url("https://github.com/login/oauth/access_token?cilen_id=xxx&client_secret=xxx"+accessTokenDTO.getCode()+  
                        "&redirect_uri=http://127.0.0.1:8080/callback&state=1")  
                .post(body)  
                .build();  
        try (Response response = client.newCall(request).execute()) {  
            String string = response.body().string();  
            String token = string.split("&")\[0\].split("=")\[1\];   
            return token;  
  } catch (IOException e) {  
            e.printStackTrace();  
  }  
        return null;  
  }  
  
    public GithubUser getUser(String token){  
        OkHttpClient client = new OkHttpClient();  
        Request request = new Request.Builder()  
                .url("https://api.github.com/user?access_token="+token)  
                .build();   
        try (Response response = client.newCall(request).execute()) {  
            String string = response.body().string();  
            GithubUser githubUser = JSON.parseObject(string, GithubUser.class);//用fastjson將json字符串轉換爲實體類
            return githubUser;  
  } catch (IOException e) {  
            e.printStackTrace();  
  }  
        return null;  
  }  
  
}
相關文章
相關標籤/搜索