簡體   English   中英

如何使用 WebRequest (Spring) 在 @ExceptionHandler class ResponseEntity 中獲取 jwt 'user_name'?

[英]How get jwt 'user_name' inside @ExceptionHandler class ResponseEntity using WebRequest (Spring)?

在此處輸入圖像描述 我嘗試: 如何從 spring 安全獲取當前登錄用戶 object?

但不起作用。

如何將org.springframework.security.oauth2.jwt.Jwt@9f4f7d6e轉換為用戶名 jwt?

我的 Class 開頭為:

@Slf4j
@RestControllerAdvice
public class RestControllerExceptionHandler {

    @ExceptionHandler(Throwable.class)
    public final ResponseEntity<ErrorResponse> handleException(Throwable ex, WebRequest request) {
        // ex.printStackTrace();
        // Authentication authenticantion = SecurityContextHolder.getContext().getAuthentication();
        String username = new String();
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();

        AbstractAuthenticationToken auth = (AbstractAuthenticationToken)
                SecurityContextHolder.getContext().getAuthentication();

        UserDetails details = (UserDetails) auth.getDetails();

        log.error(ex.getMessage().toUpperCase() + " User:  "+ username  + " Source: " + request.getDescription(false));
....

如果您只需要用戶名,那么您可以從request.getRemoteUser()訪問它。 或者,您也可以從request.getUserPrincipal().getName()獲取用戶名。 如果您不需要WebRequest ,您可以改為將簽名更改為:

@ExceptionHandler(Throwable.class)
public final ResponseEntity<ErrorResponse> handleException(Throwable ex, Principal principal) {
    String username = principal.getName();

您還可以使用@AuthenticationPrincipal獲取Jwt

@ExceptionHandler(Throwable.class)
public final ResponseEntity<ErrorResponse> handleException(Throwable ex, @AuthenticationPrincipal Jwt jwt) {
    String username = jwt.getClaim("user_name");

你也應該能夠做這樣的事情:

@ExceptionHandler(Throwable.class)
public final ResponseEntity<ErrorResponse> handleException(Throwable ex, @AuthenticationPrincipal(expression = "claims['user_name']") String username) {

最后,如果你經常使用上面的代碼,你可以使用類似的東西:

@Target({ElementType.PARAMETER, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@AuthenticationPrincipal(expression = "claims['user_name']")
public @interface CurrentUsername {}

然后你可以通過以下方式訪問它:

@ExceptionHandler(Throwable.class)
public final ResponseEntity<ErrorResponse> handleException(Throwable ex, @CurrentUsername String username) {

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM