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

JHipster示例应用:如何确保仅资源所有者可删除银行账户?

Answer to Your JHipster Bank Account Authorization Question

Great question! You’re absolutely right to flag this—this is a common gap in basic CRUD examples, and JHipster’s sample app is designed to show core framework functionality rather than complete business-level security checks. Let’s break down why this isn’t in the sample, and how you’d implement it properly.

Why the Sample App Doesn’t Include This Check

JHipster’s sample app prioritizes demonstrating CRUD flows, entity relationships, and basic security setup (like authentication) over granular business permissions. The BankAccountResource uses a plain Repository to keep the example simple, but in real-world apps, you’d add authorization logic to prevent users from modifying resources they don’t own.

How to Implement the Ownership Validation

You have a few solid options to add this check, and the best place to put it is in a Service layer (not directly in the Resource or Repository) to keep your logic centralized and reusable. Here’s a step-by-step implementation:

1. Ensure Your BankAccount Entity Tracks Ownership

First, confirm your BankAccount entity has a way to link to its owner. JHipster automatically adds createdBy and createdDate fields if you enabled auditing during entity generation, so you can use createdBy (a string of the user’s login) as the owner identifier. If you don’t have this, add a field like:

@Column(name = "created_by")
private String createdBy;

2. Add Validation in the Service Layer

Create a BankAccountService (if you don’t have one already) and add a delete method that checks ownership:

import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.core.AuthenticationException;
import io.github.jhipster.security.SecurityUtils;

@Service
public class BankAccountService {

    private final BankAccountRepository bankAccountRepository;

    public BankAccountService(BankAccountRepository bankAccountRepository) {
        this.bankAccountRepository = bankAccountRepository;
    }

    public void deleteBankAccount(Long id) {
        // Get current logged-in user's login
        String currentUserLogin = SecurityUtils.getCurrentUserLogin()
            .orElseThrow(() -> new AuthenticationException("User is not authenticated"));

        // Fetch the bank account and verify ownership
        BankAccount bankAccount = bankAccountRepository.findById(id)
            .orElseThrow(() -> new EntityNotFoundException("BankAccount not found with ID: " + id));

        if (!currentUserLogin.equals(bankAccount.getCreatedBy())) {
            throw new AccessDeniedException("You do not have permission to delete this bank account");
        }

        // Proceed with deletion
        bankAccountRepository.delete(bankAccount);
    }
}

3. Update the Resource to Use the Service

Modify your BankAccountResource to call the service instead of directly using the repository:

@RestController
@RequestMapping("/api")
public class BankAccountResource {

    private final BankAccountService bankAccountService;

    public BankAccountResource(BankAccountService bankAccountService) {
        this.bankAccountService = bankAccountService;
    }

    @DeleteMapping("/bank-accounts/{id}")
    public ResponseEntity<Void> deleteBankAccount(@PathVariable Long id) {
        bankAccountService.deleteBankAccount(id);
        return ResponseEntity.noContent().build();
    }
}

Alternative: Add a Custom Repository Method

You can also create a repository method to fetch only the current user’s bank accounts, which adds an extra layer of safety:

public interface BankAccountRepository extends JpaRepository<BankAccount, Long> {
    Optional<BankAccount> findByIdAndCreatedBy(Long id, String createdBy);
}

Then in the service, use this method instead of findById—if it returns Optional.empty(), you can throw either an EntityNotFoundException or AccessDeniedException (depending on whether you want to hide the existence of the resource from unauthorized users).

Key Takeaways

  • JHipster’s sample app is a starting point, not a production-ready app—business-specific authorization is up to you to implement.
  • Always keep authorization logic in the Service layer (not the Resource) to ensure consistency across your app.
  • Use JHipster’s built-in SecurityUtils to easily access the current user’s details.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 09:52:32