Spring Boot社交认证入门
Spring Boot Social auth
Spring Boot社交认证使用户有可能使用其现有的社交账户认证进入Spring Boot应用程序。使用Spring Boot社交认证使开发人员能够专注于业务逻辑,而不是专注于开发一个自定义的认证系统。
先决条件
在我们继续之前,你将需要以下条件。
- 在你的电脑上安装Java开发者工具包[JDK]。
- 对[Kotlin]编程语言的了解。
- 对[Spring Boot]框架的了解。
创建应用程序
我们将使用[Spring initializr]来创建我们的Spring Boot应用程序。
- 在你的浏览器中导航到[Spring initializr]。
- 在语言部分选择Kotlin。
- 添加
Spring Web,OAuth2 Client, 和Spring Boot DevTools依赖项。 - 将其他配置保留为默认,然后点击生成项目。
- 解压下载的项目,并在你喜欢的IDE中打开。
- 将该项目与maven同步,以下载所有的依赖项。
添加webjar依赖项
由于我们将需要Jquery 来构建应用程序的前端,我们需要添加webjar 的依赖项,使Jquery 在我们的Spring Boot项目中可用。
在pom.xml ,添加下面的依赖项,以便在我们的项目中包括Jquery 。
<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>
Spring安全配置
- 在项目的根包中,创建一个名为
config的包。 - 在上面创建的
config包内,创建一个名为WebConfig的新kotlin文件,并添加下面的代码片段。
import org.springframework.context.annotation.Configuration
import org.springframework.http.HttpStatus
import org.springframework.security.config.annotation.web.builders.HttpSecurity
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter
import org.springframework.security.core.AuthenticationException
import org.springframework.security.web.authentication.AuthenticationEntryPointFailureHandler
import org.springframework.security.web.authentication.HttpStatusEntryPoint
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
@Configuration
class WebConfig : WebSecurityConfigurerAdapter() {
@Throws(Exception::class)
override fun configure(http: HttpSecurity) {
http
.authorizeRequests { a ->
a.antMatchers("/", "/error", "/webjars/**").permitAll()
.anyRequest().authenticated()
}
.exceptionHandling { e ->
e.authenticationEntryPoint(HttpStatusEntryPoint(HttpStatus.UNAUTHORIZED))
}
.oauth2Login { o ->
o.failureHandler { request: HttpServletRequest, response: HttpServletResponse?, exception: AuthenticationException ->
request.session.setAttribute("error.message", exception.message)
val handler: AuthenticationEntryPointFailureHandler? = null
assert(false)
handler!!.onAuthenticationFailure(request, response, exception)
}
}
}
}
@Configuration注解将该类标记为Spring Boot配置类。.authorizeRequests { a -> a.antMatchers("/", "/error", "/webjars/**").permitAll() .anyRequest().authenticated() }允许向 、 和 端点提出的所有请求。向上述端点提出的所有请求都不需要用户认证。//error/webjars/**oauth2Login { o -> o.failureHandler { request: HttpServletRequest, response: HttpServletResponse?, exception: AuthenticationException -> request.session.setAttribute("error.message", exception.message) val handler: AuthenticationEntryPointFailureHandler? = null assert(false) handler!!.onAuthenticationFailure(request, response, exception) } }处理认证过程中出现的任何异常,即当用户取消社交认证对话框或输入错误的社交凭证时。
Spring Social auth控制器
- 在项目根包中,创建一个名为
controller的新包。 - 在上面创建的包中,创建一个名为
SocialController.kt的新文件,并添加以下代码片段。
@RestController
@RequestMapping("/api/v1/")
class SocialController {
@GetMapping("/user")
fun user(@AuthenticationPrincipal principal: OAuth2User): Map<String, Any?>? {
return Collections.singletonMap("name", principal.getAttribute("name"))
}
}
user函数返回用户已登录的社交认证提供商的用户名。
Github认证
为了在我们的应用程序中使用GitHub的OAuth 2.0认证作为登录系统,我们必须创建一个新的Github应用程序。在呈现的页面上,选择一个New OAuth App ,并注册该应用程序。
将http://localhost:8080/login/oauth2/code/github 作为授权回调URL,将http://localhost:8080 作为该应用的主页。
现在我们已经创建了一个Github OAuth应用程序,在资源目录中创建一个名为application.yml 的文件,并将下面的代码片段添加到该文件中。
用你从上面创建的Github OAuth应用程序中获得的凭证替换github-client-id 和github-client-secret 。
spring:
security:
oauth2:
client:
registration:
github:
clientId: github-client-id
clientSecret: github-client-secret
在浏览器中导航到http://localhost:8080 ,你会看到GitHub认证屏幕,如下图所示。

谷歌认证
现在我们已经成功实现了Github认证,让我们也来实现谷歌认证。
在我们上面创建的application.yml 文件中,添加下面代码片段中google auth section 的Google auth代码片段。
用你从google OAuth 2.0仪表板上获得的凭证替换google-client-id 和google-client-secret 。
spring:
security:
oauth2:
client:
registration:
# github auth section
github:
clientId: github-client-id
clientSecret: github-client-secret
# google auth section
google:
client-id: google-client-id
client-secret: google-client-secret
主页
在这一部分,我们将为我们的主页创建一个简单的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>
<div class="container unauthenticated">
<div>
With GitHub: <a href="/oauth2/authorization/github">click here</a>
</div>
<div>
With Google: <a href="/oauth2/authorization/google">click here</a>
</div>
</div>
<div class="container authenticated" style="display:none">
Logged in as: <span id="user"></span>
</div>
<!-- Grabs the username from /api/v1/user endpoint and displays it in the span with the id #user-->
<script type="text/javascript">
$.get('/api/v1/user', function (data) {
$('#user').html(data.name);
$('.unauthenticated').hide();
$('.authenticated').show();
});
</script>
</body>
</html>
当你导航到http://localhost:8080 ,会显示下面的网页。

点击Google auth后,应用程序会重定向到Google认证屏幕,如下图所示。

认证成功后,用户会被重定向到主页,在那里他们的用户名会被从社交档案中获取。下面的截图显示了一个从谷歌认证中获取的用户名。

总结
现在你已经学会了如何在Spring Boot应用程序中通过谷歌和Github认证用户,在Spring Boot应用程序中实现Facebook社交认证。