最近一直在学习springboot,刚刚看完雷丰阳老师讲的springboot基础、整合视频,相见恨晚的赶脚,顺理成章的看了尚硅谷的springboot谷粒商城项目视频,但是,有种说不出的感觉,看了16节,还是放弃了,在bilibili上又搜索了一番,找到了现在学习的这个视频,码匠社区项目,看了几节,感觉还可以,项目中用到了GitHub第三方登录,第一次接触,感觉挺好用的,自然要写篇博客记录一下啦。
一、基本概念
OkHTTP:HTTP是现代应用程序网络的方式,也就是我们交换数据和媒体的方式,有效地执行HTTP可使您的内容加载更快更节省带宽。
1、OkHTTP是默认情况下有效的HTTP客户端:
(1)HTTP/2支持允许对同一主机的所有请求共享一个套接字。
(2)连接池可减少请求延迟
(3)透明的GZIP缩小了下载大小
(4)响应缓存可以完全避免网络重复请求
2、GitHub OAuth APP:OAuth是一种授权机制,数据的所有者告诉系统,同一授权第三方应用进入系统,获取这些数据。系统从而产生一个短期的进入令牌token,用来代替密码,供第三方使用。
二、API
https://developer.github.com/apps/building-oauth-apps/authorizing-oauth-apps/
三、OkHTTP实现GitHub第三方登录
四、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>
五、代码实例
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
六、运行结果