Spring boot:3.X + Security OAuth2 自定义登录页面、登出后跳转到登录页
在Spring Boot 3.X中,使用Spring Security和OAuth2进行登录和登出,并自定义登录页面,可以通过以下步骤实现:
- 添加依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-oauth2-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
- 配置Security和OAuth2:
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll();
}
}
- 创建自定义登录页面(例如
src/main/resources/templates/login.html
):
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Login Page</title>
</head>
<body>
<h1>Custom Login Page</h1>
<form th:action="@{/login}" method="post">
<input type="text" name="username" placeholder="Username" />
<input type="password" name="password" placeholder="Password" />
<input type="hidden" name="_csrf" th:value="${_csrf.token}" />
<button type="submit">Login</button>
</form>
</body>
</html>
- 创建Controller处理登出逻辑:
@Controller
public class LogoutController {
@GetMapping("/logout")
public String logout(HttpServletRequest request) {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication != null) {
new SecurityContextLogoutHandler().logout(request, response, authentication);
}
return "redirect:/login";
}
}
- 配置application.properties或application.yml文件,设置OAuth2客户端信息和登录页面:
spring.security.oauth2.client.registration.my-client.client-id=client-id
spring.security.oauth2.client.registration.my-client.client-secret=client-secret
spring.security.oauth2.client.registration.my-client.client-name=Client Name
spring.security.oauth2.client.registration.my-client.scope=read,write
spring.security.oauth2.client.registration.my-client.authorization-grant-type=authorization_code
spring.secu
评论已关闭