在使用JWT生成令牌时,报错:

ERROR 25380 --- [nio-8888-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is io.jsonwebtoken.lang.UnknownClassException: Unable to find an implementation for interface io.jsonwebtoken.io.Serializer using java.util.ServiceLoader. Ensure you include a backing implementation .jar in the classpath, for example jjwt-impl.jar, or your own .jar for custom implementations.] with root cause

io.jsonwebtoken.impl.lang.UnavailableImplementationException: Unable to find an implementation for interface io.jsonwebtoken.io.Serializer using java.util.ServiceLoader. Ensure you include a backing implementation .jar in the classpath, for example jjwt-impl.jar, or your own .jar for custom implementations.
        at io.jsonwebtoken.impl.lang.Services.loadFirst(Services.java:105) ~[jjwt-impl-0.11.5.jar:0.11.5]
        at io.jsonwebtoken.impl.lang.LegacyServices.loadFirst(LegacyServices.java:24) ~[jjwt-impl-0.11.5.jar:0.11.5]
        at io.jsonwebtoken.impl.DefaultJwtBuilder.compact(DefaultJwtBuilder.java:291) ~[jjwt-impl-0.11.5.jar:0.11.5]

这种情况是因为pom文件中的依赖没有添加完全,JWT分别有三个依赖:

        <!-- JWT -->
        <dependency>
            <groupId>io.jsonwebtoken</groupId>
            <artifactId>jjwt-api</artifactId>
            <version>0.11.5</version>
        </dependency>
        <dependency>
            <groupId>io.jsonwebtoken</groupId>
            <artifactId>jjwt-impl</artifactId>
            <version>0.11.5</version>
            <scope>runtime</scope>
        </dependency>
<!--         JSON处理,解决秘钥序列化问题-->
        <dependency>
            <groupId>io.jsonwebtoken</groupId>
            <artifactId>jjwt-jackson</artifactId>
            <version>0.11.5</version>
            <scope>runtime</scope>
        </dependency>

 分别是核心接口依赖、实现类和一个序列化依赖,三个依赖的作用分别如下:

jjwt-api:核心 API 依赖,包含 JWT 生成、解析、验证的接口和核心类(如JwtsClaims等),是编译期必须的依赖。

jjwt-impl:API 的实现类,包含具体的 JWT 处理逻辑,scope设为runtime表示仅在运行时需要,编译期无需暴露实现细节 

jjwt-jackson:提供 Jackson JSON 处理器,用于 JWT 中自定义 claims(载荷)的 JSON 序列化 / 反序列化(例如将对象存入 claims 时),解决复杂对象的序列化问题,同样仅在运行时依赖。

 

之所以会出现这个报错是因为在将生成的秘钥序列化存储时,会使用到jjwt-jackson,自然需要添加jjwt-jackson依赖

Logo

汇聚全球AI编程工具,助力开发者即刻编程。

更多推荐