Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: security utils and setting userid on jwt #28910

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

OAllanFernando
Copy link

this makes possible recover the current user id by the jwt, its useful and can save requests

@CLAassistant
Copy link

CLAassistant commented Mar 9, 2025

CLA assistant check
All committers have signed the CLA.

@OAllanFernando
Copy link
Author

OAllanFernando commented Mar 9, 2025

Avoid this behavior

@GetMapping("/bank-accounts/{id}")
@Timed
public ResponseEntity<BankAccountDTO> getBankAccount(@PathVariable Long id) {
    log.debug("REST request to get BankAccount : {}", id);
    Optional<BankAccountDTO> bankAccountDTO = bankAccountRepository.findById(id)
        .map(bankAccountMapper::toDto);

    // Return 404 if the entity is not owned by the connected user
    Optional<String> userLogin = SecurityUtils.getCurrentUserLogin();
    if (bankAccountDTO.isPresent() &&
        userLogin.isPresent() &&
        userLogin.get().equals(bankAccountDTO.get().getUserLogin())) {
        return ResponseUtil.wrapOrNotFound(bankAccountDTO);
    } else {
        return ResponseEntity.notFound().build();
    }
}

setting this as solution

@GetMapping("/bank-accounts/{login:" + Constants.LOGIN_REGEX + "}")
@Timed
public ResponseEntity<BankAccountDTO> getBankAccount(@PathVariable String login) {
    log.debug("REST request to get BankAccount of : {}", login);
    
    // We can also validate login. Double security
   Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    if(!Objects.equals(login, authentication){
         return ResponseEntity.notFound().build();
    };

    Long userId = SecurityUtils.getCurrentUserId();
    if (userId == null) {
        return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
    }

    return bankAccountRepository.findById(userId)
        .map(bankAccountMapper::toDto)
        .map(ResponseEntity::ok)
        .orElseGet(() -> ResponseEntity.notFound().build());
}
}

This aproch can mitigate data transfer, clowd does not need to be our associates, rigth ?

The previos code can be used to force the server, if the data is in a different server

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants