我想在集群环境中部署我的 REST API。为此,我需要将我的 OAuth 2.0 token 存储在共享 token 存储中。目前我正在使用 Spring Security 的 InMemoryTokenStore,它不能在多节点集群上共享。我打算使用 Redis 存储 token 。
我发现最新版本的 Spring-Security OAuth 即 2.8.0 也提供了 RedisTokenStore。我对此有一些疑问:
在现有的 spring-security xml 配置中使用 RedisTokenStore 需要进行哪些更改。目前我正在使用 InMemoryTokenStore。
如何使 RedisTokenStore 可与集群中的所有节点共享。
我可以使用 Redis 集群来存储 token 吗?如果可以,如何?
请您参考如下方法:
关于第一个问题:
首先给大家一个关于redis token store的spring-security xml例子供大家引用
<!--Use Redis Token Store-->
<beans:bean id="tokenStore"
class="org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore">
<beans:constructor-arg name="connectionFactory" ref="redisConnectionFactory"/>
</beans:bean>
<!--create redis connection factory and set db 1-->
<beans:bean id="redisConnectionFactory"
class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
<beans:property name="hostName" value="localhost"/>
<beans:property name="port" value="6379"/>
<beans:property name="password" value=""/>
<beans:property name="database" value="1"/>
</beans:bean>
其次,您需要将 spring data redis 和 jedis jar 添加到您的项目中,我使用 gradle,在依赖项中添加项目,例如:
......
compile 'org.springframework.data:spring-data-redis:1.6.2.RELEASE'
compile 'redis.clients:jedis:2.8.0'
......
关于第二个问题:
如果您的一个集群的所有节点都使用一个 reids 服务器或集群,您的访问 token 将在所有节点之间共享。您可以检查您的 redis 数据库数据,并跟踪访问过程以验证这一点。所以你不用担心。