SpingBoot(八):Okhttp實現GitHub第三方登陸

最近一直在學習springboot,剛剛看完雷豐陽老師講的springboot基礎、整合視頻,相見恨晚的趕腳,瓜熟蒂落的看了尚硅谷的springboot穀粒商城項目視頻,可是,有種說不出的感受,看了16節,仍是放棄了,在bilibili上又搜索了一番,找到了如今學習的這個視頻,碼匠社區項目,看了幾節,感受還能夠,項目中用到了GitHub第三方登陸,第一次接觸,感受挺好用的,天然要寫篇博客記錄一下啦。
 

1、基本概念java

 OkHTTP:HTTP是現代應用程序網絡的方式,也就是咱們交換數據和媒體的方式,有效地執行HTTP可以使您的內容加載更快更節省帶寬。git

一、OkHTTP是默認狀況下有效的HTTP客戶端:github

(1)HTTP/2支持容許對同一主機的全部請求共享一個套接字。web

(2)鏈接池可減小請求延遲spring

(3)透明的GZIP縮小了下載大小json

(4)響應緩存能夠徹底避免網絡重複請求api

二、GitHub OAuth APP:OAuth是一種受權機制,數據的全部者告訴系統,同一受權第三方應用進入系統,獲取這些數據。系統從而產生一個短時間的進入令牌token,用來代替密碼,供第三方使用。緩存

2、APIspringboot

https://developer.github.com/apps/building-oauth-apps/authorizing-oauth-apps/網絡

3、OkHTTP實現GitHub第三方登陸

4、Maven 
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
 
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
        <scope>runtime</scope>
        <optional>true</optional>
    </dependency>
 
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
        <exclusions>
            <exclusion>
                <groupId>org.junit.vintage</groupId>
                <artifactId>junit-vintage-engine</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
 
    <!--HTTPClient-->
    <dependency>
        <groupId>com.squareup.okhttp3</groupId>
        <artifactId>okhttp</artifactId>
        <version>4.3.1</version>
    </dependency>
    <dependency>
        <groupId>com.squareup.okhttp3</groupId>
        <artifactId>mockwebserver</artifactId>
        <version>4.3.1</version>
    </dependency>
    <!--JSON-->
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>fastjson</artifactId>
        <version>1.2.58</version>
    </dependency>
</dependencies>

 5、代碼實例

application.properties

server.port=8080
 
github.client.id=27dda83xxxxxx36043d4
github.client.secret=01f948axxxxxxef10d9132cfe6083dxxxxxx5f3503
github.redirect.uri=http://localhost:8080/callback

GitHubProvider.java

package life.majiang.community.provider;
 
import life.majiang.community.dto.AccessTokenDTO;
import life.majiang.community.dto.GitHubUser;
import com.alibaba.fastjson.JSON;
import okhttp3.*;
import org.springframework.stereotype.Component;
 
import java.io.IOException;
 
@Component
public class GitHubProvider {
    private static final MediaType MediaType_JSON
            = MediaType.get("application/json; charset=utf-8");
    public String getAccessToken(AccessTokenDTO accessTokenDTO){
 
        OkHttpClient client = new OkHttpClient();
        RequestBody body = RequestBody.create(JSON.toJSONString(accessTokenDTO), MediaType_JSON);
        Request request = new Request.Builder()
                .url("https://github.com/login/oauth/access_token")
                .post(body)
                .build();
        try (Response response = client.newCall(request).execute()) {
            String resstring = response.body().string();
            String token =resstring.split("&")[0]
                    .split("=")[1];
            return token;
        }catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
    public GitHubUser getUser(String AccessToken){
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url("https://api.github.com/user?access_token="+AccessToken)
                .build();
        try{
            Response response = client.newCall(request).execute();
            String res = response.body().string();
            GitHubUser gitHubUser = JSON.parseObject(res, GitHubUser.class);
            return gitHubUser;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}

AuthorizeController.java 

package life.majiang.community.controller;
 
 
import life.majiang.community.dto.AccessTokenDTO;
import life.majiang.community.dto.GitHubUser;
import life.majiang.community.provider.GitHubProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
 
import javax.servlet.http.HttpServletRequest;
 
/**
 *
 */
@Controller
public class AuthorizeController {
 
    @Autowired
    private GitHubProvider gitHubProvider;
    @Value("${github.client.id}")
    private String clientId;
    @Value("${github.client.secret}")
    private String clientSecret;
    @Value("${github.redirect.uri}")
    private String redirectURI;
 
    @GetMapping("/callback")
    public String callBack(@RequestParam(name = "code")String code,
                           @RequestParam(name = "state") String state,
                           HttpServletRequest request){
        AccessTokenDTO accessTokenDTO = new AccessTokenDTO();
        accessTokenDTO.setClient_id(clientId);
        accessTokenDTO.setClient_secret(clientSecret);
        accessTokenDTO.setCode(code);
        accessTokenDTO.setRedirect_uri(redirectURI);
        accessTokenDTO.setState(state);
        String accessToken = gitHubProvider.getAccessToken(accessTokenDTO);
        GitHubUser user = gitHubProvider.getUser(accessToken);
        if(user != null){
            //登陸成功
            request.getSession().setAttribute("user",user);
            return "redirect:index";
        }else {
            //登陸失敗
            return "redirect:index";
        }
        //return "index"+user.toString();
    }
 
}

HTTP Request 

https://github.com/login/oauth/authorize?client_id=27dda83ebxxxxxxx43d4&redirect_uri=http://localhost:8080/callback&scope=user&state=1

6、運行結果

 

相關文章
相關標籤/搜索