You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot JPA中用Spring Security BCrypt遇401未授权问题求助

问题描述

我正尝试实现BCrypt对密码进行哈希处理,但遇到两个问题:

  1. Spring Security默认对所有端点启用认证,我目前仅需实现用户注册并生成密码哈希,用Postman发送Post请求到/users/register时返回401 Unauthorized。
  2. 引入org.mindrot:jbcrypt:0.4依赖后,在服务类中无法从mindrot包导入BCrypt相关类。

我未来会使用Spring Security做认证授权,但当前需要先完成用户注册及密码哈希功能,已经尝试过以下操作但未解决:

  • 在主类添加@EnableWebSecurity
  • 在主类添加@EnableAutoConfiguration或@EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class})
  • 配置SecurityFilterChain仅启用CORS:
    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http.cors(); 
        return http.build();
    }
    
解决方案

一、解决401未授权问题

Spring Security默认拦截所有请求要求认证,需在Security配置中放行注册接口,同时临时关闭CSRF(Postman发送POST请求默认不带CSRF令牌)。创建独立的Security配置类:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
@EnableWebSecurity
public class SecurityConfig {
    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
            .csrf(csrf -> csrf.disable()) // 临时关闭,生产环境按需开启
            .authorizeHttpRequests(auth -> auth
                .requestMatchers("/users/register").permitAll() // 放行注册接口
                .anyRequest().authenticated() // 其他接口保持认证要求
            );
        return http.build();
    }
}

注意:主类仅保留@SpringBootApplication即可,它已包含@EnableAutoConfiguration,无需额外添加。

二、解决jbcrypt导入问题

方案1:使用Spring Security自带的BCrypt实现

你当前代码中使用的org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder是Spring Security内置的BCrypt工具,完全满足密码哈希需求,无需额外引入org.mindrot:jbcrypt依赖,可以直接删除该依赖。

建议将BCryptPasswordEncoder声明为Bean复用:

@Configuration
public class PasswordEncoderConfig {
    @Bean
    public BCryptPasswordEncoder bCryptPasswordEncoder() {
        return new BCryptPasswordEncoder();
    }
}

在UserService中注入使用:

@Service
public class UserService {
    @Autowired
    private UserRepository userRepo;
    
    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    public User create(User body){
        String hashedPassword = passwordEncoder.encode(body.getPassword());
        body.setPassword(hashedPassword);
        return userRepo.save(body);
    }
}

方案2:使用mindrot的BCrypt(若坚持使用)

确保导入正确的包路径:

import org.mindrot.jbcrypt.BCrypt;

在服务类中调用哈希方法:

String hashedPassword = BCrypt.hashpw(body.getPassword(), BCrypt.gensalt());

三、验证效果

修改配置后重启应用,用Postman发送POST请求到http://localhost:8080/users/register,携带User的JSON请求体,即可正常返回创建后的用户,且密码已完成哈希处理。

内容的提问来源于stack exchange,提问作者M Nouman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 00:50:21