Spring Security 在Sping Boot 应用程序中访问端点时出现404错误

ep6jt1vc  于 2023-08-05  发布在  Spring
关注(0)|答案(2)|浏览(146)

我有一个Sping Boot 应用程序,我试图在其中创建REST端点。但是,当我尝试访问/users/test端点时,收到404错误。我怀疑问题可能与组件扫描配置和@ComponentScan注解的使用有关。
下面是我的项目结构和代码的概述:

后台应用程序

@SpringBootApplication
@EnableWebSecurity
@ComponentScan(basePackages = {"com.kaquya.backend.configs"})
public class BackendApplication {

    public static void main(String[] args) {
        SpringApplication.run(BackendApplication.class, args);
    }
}

字符串

用户控制器

@RestController
public class UserController {
    private final UserService userService;

    @Autowired
    public UserController(UserService userService) {
        this.userService = userService;
    }

    @PostMapping(value = "/users")
    public User createUser(@RequestBody User user) {
        return userService.register(user.getUsername(), user.getPassword(), user.getEmail());
    }

    @GetMapping("/test")
    public String testEndpoint() {
        return "this is a test endpoint";
    }
}

用户服务

@Service
public class UserService {
    private final UserExtractor userExtractor;
    private final UserRepository userRepository;

    public UserService(UserRepository userRepository, UserExtractor userExtractor) {
        this.userRepository = userRepository;
        this.userExtractor = userExtractor;
    }

    public User register(String username, String password, String email) {
        User existingUser = userExtractor.findByUsername(username);

        if(existingUser != null) {
            throw new RuntimeException("Username already exists");
        }

        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        user.setEmail(email);

        return userRepository.save(user);
    }
}

UserExtractor

@Repository
public interface UserExtractor {
    User findByUsername(String username);
}

用户库

@Repository
public interface UserRepository {
    User save(User user);
}

UserRepositoryImpl

@Repository
public class UserRepositoryImpl implements UserRepository {
    private final JdbcTemplate jdbcTemplate;

    @Value("${queries.insertUser}")
    private String insertUserQuery;

    public UserRepositoryImpl(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    @Override
    public User save(User user) {
        String hashedPassword = PasswordHasherService.hashPassword(user.getPassword());

        jdbcTemplate.update(
                insertUserQuery,
                user.getUsername(),
                hashedPassword,
                user.getEmail()
        );

        return user;
    }
}

PropertyConfig

@Configuration
public class PropertyConfig {
    @Bean
    public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
        PropertySourcesPlaceholderConfigurer configurer = new PropertySourcesPlaceholderConfigurer();
        configurer.setLocation(new ClassPathResource("queries/user_queries.xml"));
        return configurer;
    }
}

SecurityConfig

@EnableWebSecurity
@Configuration
public class SecurityConfig {

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
                .authorizeHttpRequests(authorize -> authorize
                        .anyRequest().permitAll()
                )
                .csrf(AbstractHttpConfigurer::disable);

        return http.build();
    }
}


我怀疑这个问题可能与BackendApplication类中的@ComponentScan注解有关。目前,它只扫描"com.kaquya.backend.configs"包,这意味着其他组件可能会被忽略。但是,当我尝试向@ComponentScan注解添加其他包时,遇到了与PropertyConfig类中定义的查询相关的错误。
我使用的是Java Sping Boot v3.1.1,我意识到某些东西,如mvcMatchersantMatchersWebSecurityConfigurerAdapterauthorizeRequests已经被弃用或删除。
请您帮助我确定问题并建议解决方案,以解决404错误并正确配置我的Sping Boot 应用程序中的组件扫描?

58wvjzkj

58wvjzkj1#

在安全配置中添加以下注解:

@EnableWebSecurity

字符串
想了解更多关于 Boot 的信息,你可以访问下面的spring官方网站
https://spring.io/guides/gs/securing-web/

8ftvxx2r

8ftvxx2r2#

您可以使用antMatchers

@Configuration
public class SecurityConfig {

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
                .authorizeRequests(requests -> requests
                        .antMatchers("/users").permitAll()
                        .antMatchers("/test").permitAll()
                        .anyRequest().authenticated()
                )
                .httpBasic(Customizer.withDefaults());

        return http.build();
    }
}

字符串
requestMatchers用于需要基于其他请求条件(如标头、参数等)的复杂匹配,而antMatchers用于基于蚂蚁式路径模式进行匹配

相关问题