📅  最后修改于: 2023-12-03 14:47:33.150000             🧑  作者: Mango
在本文中,我们将学习如何使用Spring Boot和Google OAuth2进行身份验证和用户登录。我们将使用Google开发人员控制台创建并配置OAuth2客户端ID。用户将能够使用他们的Google凭据进行登录并访问您的应用程序。
OAuth2是一种开放标准授权协议,允许用户授权第三方应用程序在其代表使用其受保护的资源,而无需公开用户的凭据。OAuth2以授权令牌代表用户授权,并且可以在令牌到期前进行验证和刷新。
在进行OAuth2身份验证之前,必须先在Google开发人员控制台中创建OAuth2客户端ID。
http://localhost:8080/login/oauth2/code/google
(如果您将应用程序部署在不同的URL上,请相应更改)我们将使用Spring Security和Spring Boot自动配置Spring Security OAuth2客户端对Google OAuth2进行身份验证和用户登录。
以下是我们将要做的步骤:
在pom.xml
文件中添加以下依赖项:
<dependencies>
<!-- ... -->
<dependency>
<groupId>org.springframework.security.oauth.boot</groupId>
<artifactId>spring-security-oauth2-autoconfigure</artifactId>
<version>2.3.1.RELEASE</version>
</dependency>
</dependencies>
我们将添加以下属性,以使用在Google API Console中创建的OAuth2客户端ID和客户端密码进行OAuth2身份验证:
spring.security.oauth2.client.registration.google.client-id=YOUR_CLIENT_ID
spring.security.oauth2.client.registration.google.client-secret=YOUR_CLIENT_SECRET
spring.security.oauth2.client.registration.google.scope=email,profile
我们将创建一个简单的Web控制器,在其中添加一个端点以提供Google登录的URL:
@Controller
public class AuthController {
@GetMapping("/login")
public String login() {
return "login";
}
}
在上面的代码中,我们将添加@GetMapping("/login")
注释,并在login()
方法中返回login
字符串来显示一个简单的HTML登录表单。
在该应用程序的根目录中,创建一个名为login.html
的HTML模板文件,并使用以下代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Login</title>
</head>
<body>
<h1>Login with Google</h1>
<a href="/oauth2/authorization/google">Sign in with Google</a>
</body>
</html>
该模板中包含一个标题和一个具有/oauth2/authorization/google
URL的标记,根据我们在应用程序配置文件中配置的Google OAuth2客户端ID自动添加。
最后,我们将配置Spring Security以使用Google OAuth2身份验证进行登录。
在应用程序中添加以下配置:
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/login**")
.permitAll()
.anyRequest()
.authenticated()
.and()
.oauth2Login();
}
}
在上面的代码中,我们使用HttpSecurity
对象配置应用程序的安全性。 我们使用authorizeRequests()
方法来启用HTTP请求的安全性,并使用antMatchers()
方法指定要保护的URL。 在该例中,我们保护了所有以/login
开头的URL。
我们还使用oauth2Login()
方法启用OAuth2身份验证,并设置成功登录后的重定向URL。
完成以上步骤后,重新启动应用程序并访问http://localhost:8080/login
,您将看到一个授权请求页面,您需要输入您的Google凭据进行身份验证。
恭喜,您已成功为您的应用程序添加了Google OAuth2身份验证和用户登录!