OAuth2简易实战(四)-Github社交联合登录
1. OAuth2简易实战(四)-Github社交联合登录
1.1. 用到的第三方插件
https://github.com/spring-projects/spring-social-github
1.2. 测试步骤
1.2.1. 先在github上注册一个OAuth Apps
我的配置内容如下
- 需要注意的,这里的最后一个回调地址的配置,格式严格规定,/connect/xxx,最后的github参数对应了特定页面,后面我通过阅读源码来详细解释
- 注册完之后,会有一个client id和client secret,这是需要配置到程序中的
1.2.2. 属性配置
- applicaton.properties
spring.social.github.app-id=xxxx
spring.social.github.app-secret=xxxx
- 属性类
@ConfigurationProperties(prefix = "spring.social.github")
public class GitHubProperties extends SocialProperties {}
1.2.3. social核心配置
- 属性配置导入,建立与github连接
@Configuration
@EnableSocial
@EnableConfigurationProperties(GitHubProperties.class)
public class GitHubConfiguration extends SocialAutoConfigurerAdapter {private final GitHubProperties properties;public GitHubConfiguration(GitHubProperties properties) {this.properties = properties;}@Bean@Scope(value = "request", proxyMode = ScopedProxyMode.INTERFACES)public GitHub gitHub(ConnectionRepository repository) {Connection<GitHub> connection = repository.findPrimaryConnection(GitHub.class);return connection != null ? connection.getApi() : null;}@Beanpublic ConnectController connectController(ConnectionFactoryLocator factoryLocator,ConnectionRepository repository) {ConnectController controller = new ConnectController(factoryLocator, repository);controller.setApplicationUrl("http://localhost:8080");return controller;}@Overrideprotected ConnectionFactory<?> createConnectionFactory() {return new GitHubConnectionFactory(properties.getAppId(),properties.getAppSecret());}
}
1.2.4. controller层
@Controller
public class RepositoriesController {@Autowiredprivate GitHub github;@Autowiredprivate ConnectionRepository connectionRepository;@GetMappingpublic String repositories(Model model) {if (connectionRepository.findPrimaryConnection(GitHub.class) == null) {return "redirect:/connect/github";}String name = github.userOperations().getUserProfile().getUsername();String username = github.userOperations().getUserProfile().getUsername();model.addAttribute("name", name);String uri = "https://api.github.com/users/{user}/repos";GitHubRepo[] repos = github.restOperations().getForObject(uri,GitHubRepo[].class, username);model.addAttribute("repositories", Arrays.asList(repos));return "repositories";}}
- 当我们请求localhost:8080 会重定向到localhost:8080/connect/github ,这又是写在哪呢?查看源代码,会发现在social-web包的ConnectController类中有
@Controller
@RequestMapping({"/connect"})
public class ConnectController implements InitializingBean {
@RequestMapping(value = {"/{providerId}"},method = {RequestMethod.GET})public String connectionStatus(@PathVariable String providerId, NativeWebRequest request, Model model) {this.setNoCache(request);this.processFlash(request, model);List<Connection<?>> connections = this.connectionRepository.findConnections(providerId);this.setNoCache(request);if (connections.isEmpty()) {return this.connectView(providerId);} else {model.addAttribute("connections", connections);return this.connectedView(providerId);}}
- 进入connectView方法
protected String connectView(String providerId) {return this.getViewPath() + providerId + "Connect";}
- 可以看到,在这里它固定拼接了参数Connect,所以,在自己的跳转页面中需要有特定的命名规范,这里一定就是githubConnect.html了
<html>
<head><title>Social Authcode</title>
</head>
<body><h2>Connect to GitHub to see your repositories</h2><form action="/connect/github" method="POST"><input type="hidden" name="scope" value="public_repo user" /><div class="formInfo">Click the button to share your repositories with <b>social-github</b></div><p><button type="submit">Connect to GitHub</button></p></form></body>
</html>
- 显示页面如下
- 点击按钮进行post请求,进入源码如下
@RequestMapping(value = {"/{providerId}"},method = {RequestMethod.POST})public RedirectView connect(@PathVariable String providerId, NativeWebRequest request) {ConnectionFactory<?> connectionFactory = this.connectionFactoryLocator.getConnectionFactory(providerId);MultiValueMap<String, String> parameters = new LinkedMultiValueMap();this.preConnect(connectionFactory, parameters, request);try {return new RedirectView(this.connectSupport.buildOAuthUrl(connectionFactory, request, parameters));} catch (Exception var6) {this.sessionStrategy.setAttribute(request, "social_provider_error", var6);return this.connectionStatusRedirect(providerId, request);}}
- 层层深入后,会发现它本质还是在组装授权参数,使用的是OAuth2的授权码模式,最后组装的http请求为如下,很明显为了去获得授权码
https://github.com/login/oauth/authorize?client_id=9fc0081c3dd4f8b11f86&response_type=code&redirect_uri=http%3A%2F%2Flocalhost%3A8080%2Fconnect%2Fgithub&scope=public_repo+user&state=e37f1891-cd45-47b4-adb4-5c541f777e60&state=48742b99-c04e-4dfd-af0a-f19b0193f1bb&state=c2737022-3cc7-4b80-92ce-fcba2ca9beb4
- 这最后跳转这层的代码如下,封装成buildOAuthUrl方法进行了组装
public RedirectView connect(@PathVariable String providerId, NativeWebRequest request) {ConnectionFactory<?> connectionFactory = this.connectionFactoryLocator.getConnectionFactory(providerId);MultiValueMap<String, String> parameters = new LinkedMultiValueMap();this.preConnect(connectionFactory, parameters, request);try {return new RedirectView(this.connectSupport.buildOAuthUrl(connectionFactory, request, parameters));} catch (Exception var6) {this.sessionStrategy.setAttribute(request, "social_provider_error", var6);return this.connectionStatusRedirect(providerId, request);}}
获取授权码后,跳转github登录页面
输入用户名密码正确后立即回调到方法
@RequestMapping(value = {"/{providerId}"},method = {RequestMethod.GET},params = {"code"})public RedirectView oauth2Callback(@PathVariable String providerId, NativeWebRequest request) {try {OAuth2ConnectionFactory<?> connectionFactory = (OAuth2ConnectionFactory)this.connectionFactoryLocator.getConnectionFactory(providerId);Connection<?> connection = this.connectSupport.completeConnection(connectionFactory, request);this.addConnection(connection, connectionFactory, request);} catch (Exception var5) {this.sessionStrategy.setAttribute(request, "social_provider_error", var5);logger.warn("Exception while handling OAuth2 callback (" + var5.getMessage() + "). Redirecting to " + providerId + " connection status page.");}return this.connectionStatusRedirect(providerId, request);}
- 通过授权码再去取得token
- 再继续跳转/connect/github
@RequestMapping(value = {"/{providerId}"},method = {RequestMethod.GET})public String connectionStatus(@PathVariable String providerId, NativeWebRequest request, Model model) {this.setNoCache(request);this.processFlash(request, model);List<Connection<?>> connections = this.connectionRepository.findConnections(providerId);this.setNoCache(request);if (connections.isEmpty()) {return this.connectView(providerId);} else {model.addAttribute("connections", connections);return this.connectedView(providerId);}}
- 此时connections有值,进入connectedView方法
protected String connectedView(String providerId) {return this.getViewPath() + providerId + "Connected";}
- 由此可以知道,下个页面我们命名也定下来了,githubConnected.html,这里简单一个点击连接,跳转到主页
<html><head><title>Social Authcode</title></head><body><h2>Connected to GitHub</h2><p>Click <a href="/">here</a> to see your repositories.</p></body>
</html>
- 到此其实授权操作都已经完成了,接下来就是正式调用github需要权限的接口了,点击here
代码学习地址 https://github.com/spring2go/oauth2lab
转载于:https://www.cnblogs.com/sky-chen/p/10530678.html
OAuth2简易实战(四)-Github社交联合登录相关推荐
- java github关联登录_没错,用三方Github做授权登录就是这么简单!(OAuth2.0实战)...
全2册git版本控制管理(第2版)+ 99.8元 包邮 (需用券) 去购买 > 本文收录在个人博客:www.chengxy-nds.top,技术资源共享. 上一篇<OAuth2.0 的四种 ...
- 没错,用三方 Github 做授权登录就是这么简单!(OAuth2.0实战)
本文收录在个人博客:www.chengxy-nds.top,技术资源共享. 上一篇<OAuth2.0 的四种授权方式>文末说过,后续要来一波OAuth2.0实战,耽误了几天今儿终于补上了. ...
- java oauth2.0_教程:如何实现Java OAuth 2.0以使用GitHub和Google登录
java oauth2.0 将Google和GitHub OAuth登录添加到Java应用程序的指南 我们添加到Takipi的最新功能之一是3rd party登录. 如果您像我一样懒惰,那么我想您也希 ...
- OAuth2的运行机制(GitHub单点登录)
OAuth2的运行机制 1.OAuth2框架简介 2.OAuth2身份验证架构中的组件 3.使用OAuth2的实现选项 3.1 实现授权码授权类型 3.2 使用密码授权类型 3.3 实现客户端凭据授权 ...
- Android简易实战教程--第五十四话《视差特效》
查看更多进阶知识,可以关注我的公众号,微信搜索:Android小菜 这个简易实战教程系列专栏发现已经大半年没更新了啊,赶紧添点东西. 本文实现一个视差特效效果,动态效果如下: 代码十分简单,自定义Vi ...
- aspnet登录界面代码_SPA+.NET Core3.1 GitHub第三方授权登录
GitHub第三方授权登录 有许多文章都讲过GitHub第三方授权登录,但就是没有.NET Core配合前后端分离的项目(Vue,React)的实践.所以本文以前后端分离项目中如何在授权登录后,生成T ...
- 教程:如何实现Java OAuth 2.0以使用GitHub和Google登录
将Google和GitHub OAuth登录添加到Java应用程序的指南 我们添加到Takipi的最新功能之一是3rd party登录. 如果您像我一样懒惰,那么我想您也希望跳过填写表单和输入新密码的 ...
- 一步一步教你开发微信扫码联合登录
近日,公司要求在网站上实现微信联合登录功能,在网上搜索了好多都是调用接口或者是公众号授权登录方面的内容,现公司此功能已调试成功,在此将经验分享给大家: 第一步:注册微信开放平台账号,并进行认证,此认证 ...
- 小米商城html代码_微服务架构实战:商城的用户登录与账户切换设计、订单查询设计...
商城的用户登录与账号切换设计 在移动商城的设计中,除商品和分类查询是完全开放权限的页面外,其他涉及个人隐私的个人信息.订单查询和购物车等都必须进行权限管理. 有关用户权限管理的功能,在这里根据移动设备 ...
最新文章
- UA MATH564 概率论III 期望
- head.s 分析——Linux-0.11 学习笔记(三)
- 2015-4-20 BAV推广页面修改前后对比-安全网购
- 【数据结构与算法】之深入解析“修剪二叉搜索树”的求解思路与算法示例
- 当杯子中的空气被抽走会发生什么?
- Silverlight 设计器加载错误
- ac86u原厂固件去广告_苹果发布最新固件IOS12.3.2,估计不修正你的手机
- 国内外黑客居然都在这些地方聚集
- 图像识别---opencv安装
- 张孝祥《Java就业培训教程》读书笔记
- CV LRO mission (LROC introduction)
- 网站漏洞修复公司 对网站上传文件漏洞的修复与安全加固
- Java实现咖啡馆选餐系统
- 移动互联网世代的焦虑,来自对科技范式转移视而不见
- 计算机基础知识制图,计算机绘图基础
- 一个免费的FLV编码工具(以及免费的FLV播放器)
- aix升级新安装oracle,准备在AIX上安装或升级到Oracle 11.2.0.3的注意事项
- 工作“不可能三角”,建议年后想跳槽的打工人看一下
- python读取cad中的文字,使用Python读写Redis字符串
- 测试真的会被ChatGPT代替一文告诉你