赞
踩
参考::github授权api
授权用户使用您的应用的流程为:
1,重定向用户以请求其GitHub身份
2,GitHub将用户重定向回您的站点
3,您的应用使用用户的访问令牌访问API
首先申请一个APP授权的应用,获得App ID、Client ID、Client secret,填写CallBack回调函数
1,请求用户的GitHub身份,要带参数(全部都是String类型):
client_id:必填项。注册时从GitHub收到的客户端ID 。
redirect_uri:授权后回调的的函数。
scope:有user范围的令牌和具有repo范围的令牌,user令牌可以获取用户信息,repo可以获取用户的仓库信息。
state:不可猜测的随机字符串,它用于防止跨站点请求伪造攻击。
GET https://github.com/login/oauth/authorize
实例:
<a href="https://github.com/login/oauth/authorize?client_id=Iv1.253693de8c3fc1e1&redirect_uri=http://localhost:8887/callback&scope=user&state=1">登录</a>
Get请求发送后会返回:redirect_uri的路径,这里是:http://localhost:8887/callback,并且会附带参数code和state用于临时令牌发送Post请求,需要带上以下参数:
client_id:需要。您从GitHub收到的GitHub App的客户端ID。
client_secret:需要。您从GitHub收到的GitHub App的客户密码。
code:需要。您收到的作为对步骤1的响应的代码。
redirect_uri:授权后将用户发送到应用程序中的URL。
state:您在步骤1中提供的无法猜测的随机字符串。
POST https://github.com/login/oauth/access_token
2,GitHub将用户重定向回您的站点。
在Controller层创建一个类拦截redirect_uri的路径。同时,创建一个AccessTokenDTO实体类方便信息传递,在控制层调用模拟发送Post请求的方法,获取access_token,然后用access_token调用模拟发送Get请求的方法
GET https://api.github.com/user?access_token = 获取的access_token值。
获取User对象信息。
返回的数据格式如下:
{ "login": "cchaos98", "id": 49442586, "node_id": "MDQ6VXNlcjQ5NDQyNTg2", "avatar_url": "https://avatars3.githubusercontent.com/u/49442586?v=4", "gravatar_id": "", "url": "https://api.github.com/users/cchaos98", "html_url": "https://github.com/cchaos98", "followers_url": "https://api.github.com/users/cchaos98/followers", "following_url": "https://api.github.com/users/cchaos98/following{/other_user}", "gists_url": "https://api.github.com/users/cchaos98/gists{/gist_id}", "starred_url": "https://api.github.com/users/cchaos98/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/cchaos98/subscriptions", "organizations_url": "https://api.github.com/users/cchaos98/orgs", "repos_url": "https://api.github.com/users/cchaos98/repos", "events_url": "https://api.github.com/users/cchaos98/events{/privacy}", "received_events_url": "https://api.github.com/users/cchaos98/received_events", "type": "User", "site_admin": false, "name": "超超", "company": null, "blog": "", "location": null, "email": null, "hireable": null, "bio": "超棒得儿", "public_repos": 6, "public_gists": 0, "followers": 0, "following": 0, "created_at": "2019-04-09T12:48:50Z", "updated_at": "2019-11-07T10:31:51Z" }
模拟请求的类:
@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(mediaType,JSON.toJSONString(accessTokenDTO)); Request request = new Request.Builder() .url("https://github.com/login/oauth/access_token") .post(body) .build(); try (Response response = client.newCall(request).execute()) { String string = response.body().string(); System.out.println("token:"+string); //返回的String 格式为为access_token=80b1fed6ef8db5ccef12a79e9c950ed7cd3d7678&scope=&token_type=beare String token=string.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 string = response.body().string(); GithubUser githubUser = JSON.parseObject(string, GithubUser.class); return githubUser; } catch (IOException e) { e.printStackTrace(); } return null; } }
AccessTokenDTO 类:
@Data
public class AccessTokenDTO {
private String client_id;
private String client_secret;
private String code;
private String redirect_uri;
private String state;
}
Controller类:
@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 RedirectURL; @Resource private UserMapper userMapper; @GetMapping("/callback") public String callback(@RequestParam(name="code")String code, @RequestParam(name = "state")String state, HttpServletRequest request, HttpServletResponse response){ AccessTokenDTO accessTokenDTO = new AccessTokenDTO(); accessTokenDTO.setCode(code); accessTokenDTO.setState(state); accessTokenDTO.setClient_secret(ClientSecret); accessTokenDTO.setClient_id(ClientId); accessTokenDTO.setRedirect_uri(RedirectURL); String accessToken = githubProvider.getAccessToken(accessTokenDTO); GithubUser githubUser=githubProvider.getUser(accessToken); System.out.println("githubUser:"+githubUser); if (githubUser!=null){ //登陆成功,写cookie 和session User user = new User(); String token = UUID.randomUUID().toString(); user.setToken(token); user.setName(githubUser.getName()); user.setAvatarUrl(githubUser.getAvatar_url()); user.setAccountId(String.valueOf(githubUser.getId())); user.setGmtCreate(System.currentTimeMillis()); user.setGmtModified(user.getGmtCreate()); System.out.println("*****************user:"+user.toString()); userMapper.insertUser(user); response.addCookie(new Cookie("token",token)); request.getSession().setAttribute("githubUser",githubUser); System.out.println("8888888888888888"+githubUser.getName()); return "redirect:/"; }else { //登陆失败,重新登陆 return "redirect:/"; } } }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。