使用SpringBoot+OkHttp+fastjson实现Github的OAuth第三方登录
一、在GitHub上创建一个OAuth
二、OAuth的原理
Spring官方文档
三、OkHttp的使用
OkHttp官方网站
1.Post
代码示例
//官方文档:publicstaticfinalMediaTypeJSON //=MediaType.get("application/json;charset=utf-8"); MediaTypemediaType=MediaType.get("application/json;charset=utf-8");//去掉前缀,并且修改MediaType对象名,因为一会使用fastjson变量会重名 OkHttpClientclient=newOkHttpClient();//第二句照抄 RequestBodybody=RequestBody.create(json,mediaType);//直接复制方法体中的内容 Requestrequest=newRequest.Builder() .url("")//填写要发送请求的地址 .post(body) .build(); try(Responseresponse=client.newCall(request).execute()){ returnresponse.body().string();//返回的字符串(json) }
2.Get
代码示例
OkHttpClientclient=newOkHttpClient();//同上 Requestrequest=newRequest.Builder()//直接复制方法体中的内容 .url(url)//同上 .build(); try(Responseresponse=client.newCall(request).execute()){ returnresponse.body().string();//同上 }
四、fastJson的使用
JSON.toJSONString(实体类)//将实体类转换为JSON字符串 JSON.parseObject(string,实体类.class);//将JSON字符串转换为实体类
五、代码示例
前端代码
Login //scope和state不写可能会报错
@Controller publicclassAuthorizeController{ @Autowired GithubProvidergithubProvider; @GetMapping("/callback") publicStringcallback(@RequestParam(name="code")Stringcode,@RequestParam(name="state")Stringstate){ AccessTokenDTOaccessTokenDTO=newAccessTokenDTO(); accessTokenDTO.setClient_id(""); accessTokenDTO.setClient\_secret(""); accessTokenDTO.setCode(code); accessTokenDTO.setState(state); accessTokenDTO.setRedirect\_uri("https://github.com/login/oauth/access_token"); Stringtoken=githubProvider.getAccessToken(accessTokenDTO); GithubUsergithubUser=githubProvider.getUser(token); return"index"; } }
@Component publicclassGithubProvider{ publicStringgetAccessToken(AccessTokenDTOaccessTokenDTO){ MediaTypemediaType=MediaType.get("application/json;charset=utf-8"); OkHttpClientclient=newOkHttpClient(); RequestBodybody=RequestBody.create(JSON.toJSONString(accessTokenDTO),mediaType);//用fastjson将实体类转换为json字符串传入 Requestrequest=newRequest.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(Responseresponse=client.newCall(request).execute()){ Stringstring=response.body().string(); Stringtoken=string.split("&")\[0\].split("=")\[1\]; returntoken; }catch(IOExceptione){ e.printStackTrace(); } returnnull; } publicGithubUsergetUser(Stringtoken){ OkHttpClientclient=newOkHttpClient(); Requestrequest=newRequest.Builder() .url("https://api.github.com/user?access_token="+token) .build(); try(Responseresponse=client.newCall(request).execute()){ Stringstring=response.body().string(); GithubUsergithubUser=JSON.parseObject(string,GithubUser.class);//用fastjson将json字符串转换为实体类 returngithubUser; }catch(IOExceptione){ e.printStackTrace(); } returnnull; } }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。