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

Spring Boot Twitter后端:Postman请求存库失败+403错误求助

问题:Spring Boot Twitter后端注册接口403错误,数据无法存入数据库

我跟着YouTube教程做Twitter后端Spring Boot项目,用Postman调用/api/register接口时返回403错误,Spring Boot控制台能看到请求,但数据没写入数据库。相关代码如下:

实体类 ApplicationUser

@Entity
@Table(name="users")
public class ApplicationUser {
 
 @Id
 @GeneratedValue(strategy = GenerationType.AUTO)
 @Column(name="user_id")
 private Integer userId;
 
 @Column(name="first_name")
 private String firstName;
 
 @Column(name="last_name")
 private String lastName;
 
 @Column(unique = true)
 private String email;
 
 private String phone;
 
 @Column(name="dob")
 private Date dateOfBirth;
 
 @Column(unique = true)
 private String userName;
 
 @JsonIgnore
 //@JsonIgnore is used at field level to mark a property or list of properties to be ignored.
 private String password;
 
 @ManyToMany(fetch=FetchType.EAGER)
 @JoinTable(
         name="user_role_junction",
         joinColumns = {@JoinColumn(name="user_id")},
         inverseJoinColumns = {@JoinColumn(name="role_id")}
 )
 private Set<Role> authorities;

 public Integer getUserId() {
     return userId;
 }

 public void setUserId(Integer userId) {
     this.userId = userId;
 }

 public String getFirstName() {
     return firstName;
 }

 public void setFirstName(String firstName) {
     this.firstName = firstName;
 }

 public String getLastName() {
     return lastName;
 }

 public void setLastName(String lastName) {
     this.lastName = lastName;
 }

 public String getEmail() {
     return email;
 }

 public void setEmail(String email) {
     this.email = email;
 }

 public String getPhone() {
     return phone;
 }

 public void setPhone(String phone) {
     this.phone = phone;
 }

 public Date getDateOfBirth() {
     return dateOfBirth;
 }

 public void setDateOfBirth(Date dateOfBirth) {
     this.dateOfBirth = dateOfBirth;
 }

 public String getUserName() {
     return userName;
 }

 public void setUserName(String userName) {
     this.userName = userName;
 }

 public String getPassword() {
     return password;
 }

 public void setPassword(String password) {
     this.password = password;
 }

 public Set<Role> getAuthorities() {
     return authorities;
 }

 public void setAuthorities(Set<Role> authorities) {
     this.authorities = authorities;
 }

 public ApplicationUser(){
     this.authorities=new HashSet<>();
 }

 @Override
 public String toString() {
     return "ApplicationUser{" +
             "userId=" + userId +
             ", firstName='" + firstName + '\'' +
             ", lastName='" + lastName + '\'' +
             ", email='" + email + '\'' +
             ", phone='" + phone + '\'' +
             ", dateOfBirth=" + dateOfBirth +
             ", userName='" + userName + '\'' +
             ", password='" + password + '\'' +
             ", authorities=" + authorities +
             '}';
 }
}

权限配置类 SecurityConfiguration

@Configuration
public class SecurityConfiguration {
    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception{
        return http
                .csrf(csrf -> csrf.disable())
                .authorizeHttpRequests(auth -> auth.anyRequest().permitAll())
                .build();
    }
}

服务类 UserService

@Service
public class UserService {

private final UserRepository userRepo;
private final RoleRepository roleRepo;


@Autowired
    public UserService(UserRepository userRepo,RoleRepository roleRepo){
    this.userRepo=userRepo;
    this.roleRepo=roleRepo;
}

    public ApplicationUser registerUser(ApplicationUser user){
        Set<Role> roles=user.getAuthorities();
        roles.add(roleRepo.findByAuthority("USER").get());
        roles.add(roleRepo.findByAuthority("ADMIN").get()) ;
        user.setAuthorities(roles);
        return userRepo.save(user);
    }

}

控制器 AuthenticationController

@RestController
@RequestMapping("/auth")
public class AuthenticationController {

    private final UserService userService;
    
    @Autowired
    public AuthenticationController(UserService userService){
        this.userService=userService;
    }
    
    //goes to http://localhost:8000/auth/register
    @PostMapping("/register")
    public ApplicationUser registerUser(@RequestBody ApplicationUser user){
         userService.registerUser(user);
         return user;
    }
    

}

解决方案

1. 修正接口路径不匹配

Postman调用的是/api/register,但控制器的@RequestMapping是/auth,实际有效接口路径为/auth/register。二选一调整:

  • 修改Postman请求地址为http://localhost:8000/auth/register
  • 把控制器的@RequestMapping("/auth")改为@RequestMapping("/api")

2. 修复服务类的潜在异常

服务类中直接调用roleRepo.findByAuthority("USER").get(),如果数据库中不存在对应角色,会抛出NoSuchElementException,导致请求失败且无返回提示:

  • 先手动往数据库插入角色数据:
    INSERT INTO roles (role_id, authority) VALUES (1, 'USER');
    INSERT INTO roles (role_id, authority) VALUES (2, 'ADMIN');
    
  • 或者修改服务类代码,添加空值判断避免崩溃:
    public ApplicationUser registerUser(ApplicationUser user){
        Set<Role> roles=user.getAuthorities();
        roleRepo.findByAuthority("USER").ifPresent(roles::add);
        roleRepo.findByAuthority("ADMIN").ifPresent(roles::add);
        user.setAuthorities(roles);
        return userRepo.save(user);
    }
    

3. 确认Security配置生效

确保SecurityConfiguration类被Spring扫描到(和主启动类在同一包或子包下),否则会启用默认Spring Security配置,要求认证才能访问接口,导致403。

4. 检查请求参数与实体类映射

确认Postman请求体的参数名和实体类属性名一致:

  • 实体类属性为firstName、userName、dateOfBirth,Postman中不能用first_name这类下划线格式(除非配置了驼峰转下划线的全局映射),否则属性值会为null,触发数据库非空约束导致插入失败。

5. 查看完整控制台异常日志

控制台显示请求到达但未写入数据库,大概率是服务层抛出了未捕获的异常。查看完整堆栈日志,定位具体问题(比如角色不存在、邮箱/用户名重复、字段为空违反约束等),针对性解决。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 13:44:56