在使用OAuth2社交登录保护REST API的同时配置Spring Boot登录页面,可以按照以下步骤进行配置:
<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>
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/login", "/login/oauth2/**").permitAll()
.anyRequest().authenticated()
.and()
.oauth2Login()
.loginPage("/login")
.defaultSuccessUrl("/home")
.and()
.logout()
.logoutSuccessUrl("/login")
.and()
.csrf().disable();
}
}
上述配置中,使用antMatchers
方法配置了允许访问登录页面和OAuth2登录相关的URL,其他请求需要进行身份验证。oauth2Login
方法配置了登录页面的URL、登录成功后的默认跳转URL。logout
方法配置了退出登录后的跳转URL。csrf
方法禁用了跨站请求伪造保护。
<!DOCTYPE html>
<html>
<head>
<title>Login</title>
</head>
<body>
<h2>Login</h2>
<form action="/login" method="post">
<div>
<label for="username">Username:</label>
<input type="text" id="username" name="username" required>
</div>
<div>
<label for="password">Password:</label>
<input type="password" id="password" name="password" required>
</div>
<div>
<button type="submit">Login</button>
</div>
</form>
</body>
</html>
spring.security.oauth2.client.registration.<client-id>.client-id=<client-id>
spring.security.oauth2.client.registration.<client-id>.client-secret=<client-secret>
spring.security.oauth2.client.registration.<client-id>.scope=<scope>
其中,<client-id>
为自定义的客户端ID,<client-secret>
为自定义的客户端密钥,<scope>
为授权范围。
以上是在使用OAuth2社交登录保护REST API的同时配置Spring Boot登录页面的步骤。在实际应用中,可以根据具体需求进行进一步的定制和扩展。
领取专属 10元无门槛券
手把手带您无忧上云