要在Spring Boot、JPA和Spring Security中扩展表单登录以支持Google Sign-in(OAuth2),你需要进行以下步骤:
在pom.xml
中添加以下依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-oauth2-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
spring:
security:
oauth2:
client:
registration:
google:
client-id: YOUR_CLIENT_ID
client-secret: YOUR_CLIENT_SECRET
redirect-uri: "{baseUrl}/login/oauth2/code/google"
scope: profile,email
jpa:
hibernate:
ddl-auto: update
show-sql: true
创建一个配置类来设置Spring Security:
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.web.SecurityFilterChain;
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.authorizeRequests(authorize -> authorize
.antMatchers("/", "/error", "/webjars/**").permitAll()
.anyRequest().authenticated()
)
.oauth2Login(oauth2 -> oauth2.loginPage("/login").permitAll());
return http.build();
}
}
创建一个简单的登录页面src/main/resources/templates/login.html
:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Login</title>
</head>
<body>
<h1>Login</h1>
<form method="post" action="/login">
<button type="submit">Login with Google</button>
</form>
</body>
</html>
Spring Security会自动处理OAuth2回调,并将用户重定向到配置的登录页面。
application.yml
中的配置一致。pom.xml
中的依赖版本,确保没有冲突。通过以上步骤,你可以在Spring Boot应用中集成Google Sign-in功能。
领取专属 10元无门槛券
手把手带您无忧上云