forked from kidgrow-microservices-platform

zhaoxiaohao
2021-03-11 0c9ff5198c54ec5d2f3bbb8c5a406d270df1e188
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
package com.kidgrow.oauth2.service.impl;
 
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.code.RandomValueAuthorizationCodeServices;
 
import java.util.concurrent.TimeUnit;
 
 
/**
 * 石家庄喜高科技有限责任公司 版权所有 © Copyright 2020<br>
 *
 * @Description: JdbcAuthorizationCodeServices替换<br>
 * @Project: <br>
 * @CreateDate: Created in 2020/2/20 09:19 <br>
 * @Author: <a href="4345453@kidgrow.com">liuke</a>
 */
public class RedisAuthorizationCodeServices extends RandomValueAuthorizationCodeServices {
 
    private RedisTemplate<String, Object> redisTemplate;
 
    public RedisTemplate<String, Object> getRedisTemplate() {
        return redisTemplate;
    }
 
    public void setRedisTemplate(RedisTemplate<String, Object> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }
 
    /**
     * 替换JdbcAuthorizationCodeServices的存储策略
     * 将存储code到redis,并设置过期时间,10分钟
     */
    @Override
    protected void store(String code, OAuth2Authentication authentication) {
        redisTemplate.opsForValue().set(redisKey(code), authentication, 10, TimeUnit.MINUTES);
    }
 
    @Override
    protected OAuth2Authentication remove(final String code) {
        String codeKey = redisKey(code);
        OAuth2Authentication token = (OAuth2Authentication) redisTemplate.opsForValue().get(codeKey);
        this.redisTemplate.delete(codeKey);
        return token;
    }
 
    /**
     * redis中 code key的前缀
     *
     * @param code
     * @return
     */
    private String redisKey(String code) {
        return "oauth:code:" + code;
    }
}