Spring Boot 在服务内出现错误 403

问题描述 投票:0回答:1

以下是

SecurityFilterChain
的实现:

@EnableWebSecurity
@Configuration
public class WebSecurity  {
    private final UserService userDetailsService;
    private final BCryptPasswordEncoder bCryptPasswordEncoder;

    public WebSecurity(UserService userDetailsService, BCryptPasswordEncoder bCryptPasswordEncoder) {
        this.userDetailsService = userDetailsService;
        this.bCryptPasswordEncoder = bCryptPasswordEncoder;
    }

    @Bean
    public SecurityFilterChain configure(HttpSecurity http) throws Exception {
        AuthenticationManagerBuilder authenticationManagerBuilder =
                http.getSharedObject(AuthenticationManagerBuilder.class);

        authenticationManagerBuilder
                .userDetailsService(userDetailsService)
                .passwordEncoder(bCryptPasswordEncoder);

        http
            .csrf(csrf -> csrf.disable())
            .authorizeRequests()
            .requestMatchers(HttpMethod.POST, "/users").permitAll()
            .anyRequest().authenticated();

        return http.build();
    }
}

并且

UserService
的实现如下所示:

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private Utils utils;

    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    @Override
    public UserDto createUser(UserDto userDto) {
        UserEntity exists = userRepository.findByEmail(userDto.getEmail());

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

        UserEntity userEntity = new UserEntity();
        BeanUtils.copyProperties(userDto, userEntity);

        String publicUserId = utils.generateUserId(30);
        userEntity.setUserId(publicUserId);
        userEntity.setEncryptedPassword(bCryptPasswordEncoder.encode(userDto.getPassword()));

        UserEntity storedUserEntity = userRepository.save(userEntity);

        UserDto returnValue = new UserDto();
        BeanUtils.copyProperties(storedUserEntity, returnValue);
        return returnValue;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        UserEntity userEntity = userRepository.findByEmail(username);
        if(userEntity == null){
            throw new UsernameNotFoundException(username);
        }
        return new User(username, userEntity.getEncryptedPassword(), new ArrayList<>());
    }
}

现在,我可以通过

/users
端点创建新用户。但是,如果我尝试使用现有电子邮件创建用户,则会收到 403 错误。我预计堆栈跟踪会出现错误。为什么是403?

java spring spring-boot spring-security spring-data-jpa
1个回答
0
投票

发生这种情况是因为 springboot 3 中未添加 securityconfiguration 类,websecurityconfigureadaptor 已弃用,因此您不能使用旧的类定义。

可以使用下面的 bean 定义来代替重写 websecurityconfigureadaptor 中的配置方法

https://spring.io/blog/2022/02/21/spring-security-without-the-websecurityconfigureadapter

© www.soinside.com 2019 - 2024. All rights reserved.