简体   繁体   中英

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

在此处输入图像描述 I try: How to get the current logged in user object from spring security?

but doesn't work.

How convert org.springframework.security.oauth2.jwt.Jwt@9f4f7d6e to username jwt?

My Class Starts With:

@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));
....

If you just need the username, then you can access it from request.getRemoteUser() . Alternatively, you can also get the username from request.getUserPrincipal().getName() . If you don't need the WebRequest , you can instead change your signature to be:

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

You can also get the Jwt using @AuthenticationPrincipal

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

You should also be able to do something like this:

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

Finally if you are using the above code frequently, you can using something like:

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

Then you can access it with:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM