17 Aralık 2019 Salı

SpringSecurity @AuthenticationPrincipal Anotasyonu

Giriş
Şu satırı dahil ederiz
import org.springframework.security.core.annotation.AuthenticationPrincipal;
User nesnesini metoda geçer. Açıklaması şöyle
Spring allows using Authentication as Controller’s method argument. For our convenience, it also provides annotation @AuthenticationPrincipal which will extract Principle implementation from SecurityContext. It can be useful when business logic relies on Principal details. Or it can be additional validation of user permissions.
Örnek
Şöyle yaparız.
@RequestMapping(value = "/", method = RequestMethod.GET)
public String getCurrentUser(@AuthenticationPrincipal User user) {
  ...
}
Örnek - 
Şöyle yaparız
import org.springframework.security.oauth2.jwt.Jwt;

@RestController
@RequiredArgsConstructor
public class BaseController {

  @GetMapping("/accounts/{accountId}")
  public ResponseEntity<AccountData> getAccountData(
    @AuthenticationPrincipal Jwt principal,
    @PathVariable String accountId) {

    if (!accountId.equals(principal.getClaimAsString("accountId"))) {
      ...
    }
    ...
  }
}


Hiç yorum yok:

Yorum Gönder