[英]How to get the request body data inside ExceptionHandler class in springboot(REST)
[英]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.