[英]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?
我尝试: 如何从 spring 安全获取当前登录用户 object?
but doesn't work.但不起作用。
How convert org.springframework.security.oauth2.jwt.Jwt@9f4f7d6e
to username jwt?如何将
org.springframework.security.oauth2.jwt.Jwt@9f4f7d6e
转换为用户名 jwt?
My Class Starts With:我的 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));
....
If you just need the username, then you can access it from request.getRemoteUser()
.如果您只需要用户名,那么您可以从
request.getRemoteUser()
访问它。 Alternatively, you can also get the username from request.getUserPrincipal().getName()
.或者,您也可以从
request.getUserPrincipal().getName()
获取用户名。 If you don't need the WebRequest
, you can instead change your signature to be:如果您不需要
WebRequest
,您可以改为将签名更改为:
@ExceptionHandler(Throwable.class)
public final ResponseEntity<ErrorResponse> handleException(Throwable ex, Principal principal) {
String username = principal.getName();
You can also get the Jwt
using @AuthenticationPrincipal
您还可以使用
@AuthenticationPrincipal
获取Jwt
@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) {
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.