我在配置 Spring Security 时遇到了困难。我试图允许某些路由无需身份验证即可访问,并保护其他路由,但是 .permitAll 和 .hasRole 似乎不会对我的代码产生影响。有人可以向我解释我做错了什么以及如何解决它吗?谢谢。附件是我的代码片段。
package com.productiv.authentication;
import javax.sql.DataSource;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityCustomizer;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
@Configuration
@EnableWebSecurity
public class SpringSecurityBasicAuthConfig {
private static final Logger logger = LogManager.getLogger(SpringSecurityBasicAuthConfig.class);
@Autowired
private DataSource dataSource;
protected void configure(AuthenticationManagerBuilder authentication) throws Exception {
authentication.jdbcAuthentication().dataSource(dataSource);
}
/* The below code block allows access to the H2 console */
@Bean
public WebSecurityCustomizer webSecurityCustomizer() {
return (web) -> web.ignoring().anyRequest();
}
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
String methodName = "filterChain";
logger.info("Executing, " + methodName);
http.authorizeHttpRequests()
.requestMatchers("/h2/**").permitAll()
.requestMatchers("/api/v1/registration/**").permitAll()
.requestMatchers("/users/**").hasAuthority("USER")
.and()
.formLogin()
.and()
.csrf().disable();
return http.build();
}
@Bean
public BCryptPasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
您的安全配置已正确实施。
首先,删除这个
(web) -> web.ignoring().anyRequest()
。它将忽略所有安全路径。相反,您可以像这样定义您想要允许的所有路线:
(web) -> web.ignoring().requestMatchers("/h2/**, "/api/v1/registration/**")
您的
SecurityFilterChain
将如下所示:
http.authorizeHttpRequests()
.requestMatchers("/users/**").hasRole("USER")
您还需要提供
AuthenticationProvider
。您当前的配置方法没有执行任何操作。例如:
@Bean
public UserDetailsService users() {
UserDetails user = User.builder()
.username("user")
.password(passwordEncoder.encode("user"))
.roles("USER")
.build();
UserDetails admin = User.builder()
.username("admin")
.password(passwordEncoder.encode("admin"))
.roles("USER", "ADMIN")
.build();
return new InMemoryUserDetailsManager(user, admin);
}
阅读此以了解详细信息。