在Spring Boot中保护根URL可以使用Spring Security来实现。以下是一个使用基于内存的用户认证配置的示例代码:
org.springframework.boot
spring-boot-starter-security
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("admin")
.password("{noop}password") // 设置密码,{noop}表示不使用加密
.roles("ADMIN");
}
}
# 允许所有用户访问根URL
spring.security.basic.enabled=false
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/").authenticated()
.anyRequest().permitAll()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout()
.permitAll();
}
在上述代码中,根URL("/")需要进行身份验证,其他URL则允许所有用户访问。同时,登录页面是"/login",退出页面也是允许所有用户访问。
请注意,这只是一个基本的示例,你可以根据你的需求进行更多的配置。