我正在创建一个 Spring Boot API MVC 项目。我被要求使用基本身份验证来保护 API。
现在,我有 3 个端点。
“/tasks/clear”的控制器方法是这样的:
@PostMapping("/tasks/clear")
public String clearAllCacheValues(Model model) {
taskService.clearAllCacheValues("tasksCache");
return "redirect:/";
}
我的问题是我只想在第一次打开网站时登录。但在我的程序中,它:
输入我的用户密码不会执行任何操作,不会调用清除方法,只是一遍又一遍地打开弹出窗口。
SecurityConfig 代码如下所示:
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests((auth) -> auth
.requestMatchers("/login").permitAll()
.anyRequest().authenticated()
)
.httpBasic(withDefaults());
return http.build();
}
如何才能让我只在第一次打开网页时输入密码,而在访问其他端点时不需要输入密码?我对这一切都很陌生,所以如果我的问题结构不佳或基本,我很抱歉。
您可以通过适当配置 Spring Security 来实现这一点。
以下是修改 SecurityConfig 以实现所需行为的方法:
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;
@Configuration
public class SecurityConfig {
@Bean
public SecurityFilterChain defaultSecurityFilterChain(HttpSecurity http) throws Exception {
http
.authorizeRequests(authorizeRequests ->
authorizeRequests
.antMatchers("/").permitAll() // Allow unauthenticated access to the root endpoint
.antMatchers("/tasks").authenticated() // Require authentication for /tasks
.antMatchers("/tasks/clear").authenticated() // Require authentication for /tasks/clear
)
.httpBasic(Customizer.withDefaults()); // Use Basic Authentication
return http.build();
}
@Bean
public InMemoryUserDetailsManager userDetailsManager() {
UserDetails user = User
.withDefaultPasswordEncoder()
.username("your-username") // Change this to your username
.password("your-password") // Change this to your password
.roles("USER")
.build();
return new InMemoryUserDetailsManager(user);
}
}
有关更多信息,请参阅 Spring Security 文档:https://docs.spring.io/spring-security/reference/