spring security报错: Invalid token does not contain resource id 'XXXXXXX'

场景

之前每次在进入新项目时,以及在使用Openfeign调用其他服务的时候出现Invalid token does not contain resource id的报错信息,在确保所有配置都正确的情况下(本地的resourceid和授权服务器的配置相同)

解决过程

首先找到报错信息的地方,可以看到resourceIds 是从auth中获取的

报错位置

那我们就debug进入loadAuthentication方法中

org.springframework.security.oauth2.provider.token.DefaultTokenServices # loadAuthentication()

public OAuth2Authentication loadAuthentication(String accessTokenValue) throws AuthenticationException,
       InvalidTokenException {
    OAuth2AccessToken accessToken = tokenStore.readAccessToken(accessTokenValue);
    if (accessToken == null) {
       throw new InvalidTokenException("Invalid access token: " + accessTokenValue);
    }
    else if (accessToken.isExpired()) {
       tokenStore.removeAccessToken(accessToken);
       throw new InvalidTokenException("Access token expired: " + accessTokenValue);
    }

     // 核心方法
    OAuth2Authentication result = tokenStore.readAuthentication(accessToken);
    if (result == null) {
       // in case of race condition
       throw new InvalidTokenException("Invalid access token: " + accessTokenValue);
    }
    if (clientDetailsService != null) {
       String clientId = result.getOAuth2Request().getClientId();
       try {
          clientDetailsService.loadClientByClientId(clientId);
       }
       catch (ClientRegistrationException e) {
          throw new InvalidTokenException("Client not valid: " + clientId, e);
       }
    }
    return result;
}

继续往里跟踪就可以找到下面的这个方法

org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter #

protected Map<String, Object> decode(String token) {
    try {
        // 解析JWT令牌
       Jwt jwt = JwtHelper.decodeAndVerify(token, verifier);
       String claimsStr = jwt.getClaims();
       Map<String, Object> claims = objectMapper.parseMap(claimsStr);
       if (claims.containsKey(EXP) && claims.get(EXP) instanceof Integer) {
          Integer intValue = (Integer) claims.get(EXP);
          claims.put(EXP, new Long(intValue));
       }
       this.getJwtClaimsSetVerifier().verify(claims);
       return claims;
    }
    catch (Exception e) {
       throw new InvalidTokenException("Cannot convert access token to JSON", e);
    }
}

可以看到这段代码是解析JWT令牌的内容,通过debug看到JWT的数据

JWT解析内容

aud的内容即为我们的resourceids,所以resourceids是从JWT中解析出来的,重新登陆(重新获取Jwt)就行了

posted @ 2025-08-06 00:04  Lwf663  阅读(7)  评论(0)    收藏  举报