spring-security Spring控制器参数'@AuthenticationPrincipal Jwt principal'导致异常:tokenValue不能为空

t30tvxxf  于 2022-11-11  发布在  Spring
关注(0)|答案(1)|浏览(250)

控制器方法如下所示

QuotaChangeResponseDTO memoryQuotaIncreaseRequest(
            @Valid @RequestBody QuotaIncreaseRequestDTO requestDTO,
            @AuthenticationPrincipal Jwt principal) {

然后我得到了下面的异常。
但是,如果我删除第二个参数,并使用SecurityContextHolder代替,它就可以工作。
此方法需要身份验证。
更新(一天后):我只是把论点改为:Principal principal,这个可以用。

java.lang.IllegalArgumentException: tokenValue cannot be empty
    at org.springframework.util.Assert.hasText(Assert.java:284) ~[spring-core-5.2.6.RELEASE.jar:5.2.6.RELEASE]
    at org.springframework.security.oauth2.core.AbstractOAuth2Token.<init>(AbstractOAuth2Token.java:55) ~[spring-security-oauth2-core-5.3.2.RELEASE.jar:5.3.2.RELEASE]
    at org.springframework.security.oauth2.jwt.Jwt.<init>(Jwt.java:69) ~[spring-security-oauth2-jose-5.3.2.RELEASE.jar:5.3.2.RELEASE]
    at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) ~[na:na]
    at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62) ~[na:na]
    at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) ~[na:na]
    at java.base/java.lang.reflect.Constructor.newInstanceWithCaller(Constructor.java:500) ~[na:na]
    at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:481) ~[na:na]
    at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:204) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
    at ...
sxpgvts3

sxpgvts31#

举个例子,通过@AuthenticationPrincipal从JwtAuthenticationToken派生值不起作用(谢谢@Matt F.),所以我使用了以下代码:

public ResponseEntity<xxResponse> performXXXRequest (final @AuthenticationPrincipal Jwt principal, final @RequestBody XXDTO xxDTO){
.....
}

这是可行的:

public ResponseEntity<xxResponse> performXXXRequest (final Principal principal, @RequestBody final XXDTO xxDTO){
.....
}

//To derive Claims or other JWT details like this:
    private String resolveCallerIdFromJwtPrincipal(final Principal principal) {
        JwtAuthenticationToken jwtAuthToken = (JwtAuthenticationToken) principal;
        Jwt jwtPrincipal = (Jwt) jwtAuthToken.getPrincipal();
        return jwtPrincipal.getClaimAsString("name");
    }

相关问题