本节展示如何使用OAuth 2.0和Spring Boot构建一个示例应用程序,进行各种登录操作。
它从一个简单的单一提供者单点登录开始
这些示例都是在后端使用Spring Boot和Spring Security的单页应用程序。它们也都在前端使用普通jQuery。但是,转换为不同的JavaScript框架或使用服务器端渲染所需的更改将是最小的。
所有示例都使用Spring Boot中的本地OAuth 2.0支持实现。
创建一个springBoot空的Web项目。

在static下创建index.html ,内容如下:
- <!doctype html>
- <html lang="en">
- <head>
- <meta charset="utf-8"/>
- <meta http-equiv="X-UA-Compatible" content="IE=edge"/>
- <title>Demo</title>
- <meta name="description" content=""/>
- <meta name="viewport" content="width=device-width"/>
- <base href="/"/>
- <link rel="stylesheet" type="text/css" href="/webjars/bootstrap/css/bootstrap.min.css"/>
- <script type="text/javascript" src="/webjars/jquery/jquery.min.js"></script>
- <script type="text/javascript" src="/webjars/bootstrap/js/bootstrap.min.js"></script>
- </head>
- <body>
- <h1>Demo</h1>
- <div class="container"></div>
- </body>
- </html>
由于页面引入了bootstrap jquery.需要在Pom里
- <dependency>
- <groupId>org.webjars</groupId>
- <artifactId>jquery</artifactId>
- <version>3.4.1</version>
- </dependency>
- <dependency>
- <groupId>org.webjars</groupId>
- <artifactId>bootstrap</artifactId>
- <version>4.3.1</version>
- </dependency>
- <dependency>
- <groupId>org.webjars</groupId>
- <artifactId>webjars-locator-core</artifactId>
- </dependency>

在github上创建一个appID

复制Client ID 和client Secret ,修改到yaml里。
- spring:
- security:
- oauth2:
- client:
- registration:
- github:
- clientId: 938a bbeaa4d4a
- clientSecret: 68d 5124e0f60c8587
这时再访问,就会跳转到gitHub先登录了。
如果您一直登录到GitHub,即使您在没有cookies和缓存数据的新浏览器中打开它,也无需重新验证此本地应用。(这就是单点登录的含义。)
添加一个controller
- @GetMapping("/user")
- public Map
user(@AuthenticationPrincipal OAuth2User principal) { - return Collections.singletonMap("name", principal.getAttribute("name"));
- }

- <script type="text/javascript">
- $.get("/user", function(data) {
- $("#user").html(data.name);
- $(".unauthenticated").hide()
- $(".authenticated").show()
- });
- </script>

看来可以试一下整合QQ登录。 先QQ互联官网首页




1. 实现QQ登录功能