带有预取 JWT 令牌的 OAuth2RestTemplate

OAuth2RestTemplate with prefetched JWT token

JWT OAuth2 令牌从 Spring Auth 服务器预取并存储在 Redis 存储中。

我不想在 OAuth2RestTemplate 中请求访问令牌,我想将我的 JWT 令牌用于请求。

我可以使用 OAuth2RestTemplate 还是我应该使用通常的 RestTemplate

spring-security-oauth 的文档在这里很有用,基本上是两个部分:JWT 令牌和访问受保护的资源:

JWT Tokens

To use JWT tokens you need a JwtTokenStore in your Authorization Server. The Resource Server also needs to be able to decode the tokens so the JwtTokenStore has a dependency on a JwtAccessTokenConverter, and the same implementation is needed by both the Authorization Server and the Resource Server. The tokens are signed by default, and the Resource Server also has to be able to verify the signature, so it either needs the same symmetric (signing) key as the Authorization Server (shared secret, or symmetric key), or it needs the public key (verifier key) that matches the private key (signing key) in the Authorization Server (public-private or asymmetric key). The public key (if available) is exposed by the Authorization Server on the /oauth/token_key endpoint, which is secure by default with access rule "denyAll()". You can open it up by injecting a standard SpEL expression into the AuthorizationServerSecurityConfigurer (e.g. "permitAll()" is probably adequate since it is a public key).

To use the JwtTokenStore you need "spring-security-jwt" on your classpath (you can find it in the same github repository as Spring OAuth but with a different release cycle).

Accessing Protected Resources

Once you've supplied all the configuration for the resources, you can now access those resources. The suggested method for accessing those resources is by using the RestTemplate introduced in Spring 3. OAuth for Spring Security has provided an extension of RestTemplate that only needs to be supplied an instance of OAuth2ProtectedResourceDetails.

这对我来说基本上意味着您将在授权服务器和资源服务器中使用相同的 spring-security-jwt JwtAccessTokenConverter class,并且每个服务器中的令牌服务都需要使用 JwtTokenStore() 进行设置。他们所指的 RestTemplate class 的扩展是来自 spring-security-oauth2 的 OAuth2RestTemplate。您可以在资源服务器中使用它,它的 JWT 智能由等效的令牌识别器提供。

因为 spring-security-oauth2 代码已经设置为处理 JWT 令牌,您只需要提供一些关键部分并让框架完成检查令牌和将每个受保护资源的安全范围。

碰巧的是,有人发布了一个很好的例子,其中详细介绍了这一点:baeldung spring-security-oauth-jwt example and here: github project of the same 包括如何提供更个性化的 JWT (claims/payload)。