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

SpringBoot REST API实现帖子创建者删除权限的技术问询

实现创建者删除自身博客帖子的功能(SpringBoot REST API)

我基于SpringBoot开发了一个REST API,包含博客帖子、帖子评论、用户资料、角色四个模型。目前仅管理员可删除博客帖子,希望添加创建者删除自身帖子的功能(需先登录),该如何实现?

现有相关代码

User模型

@Setter
@Getter
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Table(name = "users")
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(nullable = false, unique = true)
    private String email;

    private String name;

    @Column(nullable = false, unique = true)
    private String username;

    @Column(nullable = false)
    private String password;

    @ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
    @JoinTable(name = "users_roles",
            joinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id"),
            inverseJoinColumns = @JoinColumn(name = "role_id", referencedColumnName = "id")
    )
    private Set<Role> roles;
}

Posts模型

@Data
@AllArgsConstructor
@NoArgsConstructor

@Entity
@Table(
        name="Posts", uniqueConstraints = {@UniqueConstraint(columnNames = {"title"})}
)
public class Post {
    @Id
    @GeneratedValue(
            strategy = GenerationType.IDENTITY
    )
    private Long id;

    @Column(name = "Title", nullable = false)
    private String title;

    @Column(name = "Description", nullable = false)
    private String description;

    @Column(name = "Content", nullable = false)
    private String content;

    @OneToMany(mappedBy = "post", cascade = CascadeType.ALL, orphanRemoval = true)
    Set<Comment> comments = new HashSet<>();
} 

删除帖子接口

@PreAuthorize("hasRole('ADMIN')")
@DeleteMapping("/{id}")
public ResponseEntity<String> deletePostById(@PathVariable Long id) {
    postService.deletePostById(id);
    return new ResponseEntity<>("Post Deleted Successfully", HttpStatus.OK);
}

完整实现方案

我已经完成了功能配置,以下是完整实现步骤:

1. 给Post模型添加创建者关联

首先需要在Post实体中添加与User的关联,记录帖子的创建者:

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "user_id", nullable = false)
private User createdBy;

同时要确保创建帖子时,将当前登录用户设置为createdBy字段的值。

2. 修改删除接口的权限校验规则

更新@PreAuthorize表达式,允许管理员或帖子创建者执行删除操作:

@PreAuthorize("hasRole('ADMIN') || @postSecurity.isPostCreator(#id)")
@DeleteMapping("/{id}")
public ResponseEntity<String> deletePostById(@PathVariable Long id) {
    postService.deletePostById(id);
    return new ResponseEntity<>("Post Deleted Successfully", HttpStatus.OK);
}

3. 封装权限校验逻辑

创建PostSecurity组件,把获取当前用户和校验创建者的逻辑封装起来:

@Component("postSecurity")
public class PostSecurity {
    private final UserRepository userRepository;
    private final PostRepository postRepository;

    public PostSecurity(UserRepository userRepository, PostRepository postRepository) {
        this.userRepository = userRepository;
        this.postRepository = postRepository;
    }

    public boolean isPostCreator(Long postId) {
        User currentUser = getUser();
        if (currentUser == null) {
            return false;
        }
        Post post = postRepository.findById(postId).orElse(null);
        return post != null && post.getCreatedBy().getId().equals(currentUser.getId());
    }

    private User getUser() {
        SecurityContext context = SecurityContextHolder.getContext();
        Authentication auth = context.getAuthentication();
        return userRepository.findUserByEmail(auth.getName()).orElse(null);
    }
}

4. 确认服务层逻辑

确保postService.deletePostById方法能正确处理关联数据(现有代码已通过@OneToMany(cascade = CascadeType.ALL, orphanRemoval = true)配置了评论的级联删除,无需额外修改)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 02:17:40