Redis校验Token

连接redis

package com.firefly.performance.core.config;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.connection.lettuce.LettucePoolingClientConfiguration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.time.Duration;

@Slf4j
@Configuration
public class RedisConfig {

    // Auth Redis 配置信息
    @Value("${spring.redis.auth.database}")
    private Integer authDatabase;

    @Value("${spring.redis.auth.host}")
    private String authHost;

    @Value("${spring.redis.auth.port}")
    private Integer authPort;

    @Value("${spring.redis.auth.password}")
    private String authPassword;

    // MPass Redis 配置信息
    @Value("${spring.redis.mpass.database}")
    private Integer mpassDatabase;

    @Value("${spring.redis.mpass.host:}")
    private String mpassHost;

    @Value("${spring.redis.mpass.port:}")
    private Integer mpassPort;

    @Value("${spring.redis.mpass.password:}")
    private String mpassPassword;

    /**
     * redisStandaloneConfiguration 单机版配置
     *
     * @param host
     * @param port
     * @param password
     * @param database
     * @return
     */
    public RedisTemplate<String, String> build(String host, int port, String password, int database) {
        RedisStandaloneConfiguration redisStandaloneConfiguration = new RedisStandaloneConfiguration(host, port);

        if (StringUtils.isNotBlank(password)) {
            redisStandaloneConfiguration.setPassword(password);
        }
        redisStandaloneConfiguration.setDatabase(database);

        LettucePoolingClientConfiguration clientConfig = LettucePoolingClientConfiguration.builder()
                .commandTimeout(Duration.ofMillis(5000l))
                .poolConfig(new GenericObjectPoolConfig())
                .build();
        LettuceConnectionFactory connectionFactory = new LettuceConnectionFactory(redisStandaloneConfiguration, clientConfig);
        //必须初始化实例
        connectionFactory.afterPropertiesSet();
        //如果要使pool参数生效,一定要关闭shareNativeConnection
        //lettuceConnectionFactory.setShareNativeConnection(false);

        RedisTemplate<String, String> commonRedisTemplate = new StringRedisTemplate();
        commonRedisTemplate.setConnectionFactory(connectionFactory);
        // key、hash的key 采用 String序列化方式 【可自行配置】
        commonRedisTemplate.setKeySerializer(new StringRedisSerializer());
        commonRedisTemplate.setHashKeySerializer(new StringRedisSerializer());
        // value、hash的value 采用 String 序列化方式
        commonRedisTemplate.setValueSerializer(new StringRedisSerializer());
        commonRedisTemplate.setHashValueSerializer(new StringRedisSerializer());
        commonRedisTemplate.afterPropertiesSet();
        return commonRedisTemplate;
    }


    @Bean(name = "redisAuthTemplate")
    public RedisTemplate<String, String> redisAuthTemplate() {
        return build(authHost, authPort, authPassword, authDatabase);
    }

    @Bean(name = "redisMpassTemplate")
    public RedisTemplate<String, String> redisMpassTemplate() {
        return build(mpassHost, mpassPort, mpassPassword, mpassDatabase);
    }




}

调用

package com.firefly.performance.core.common;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.stereotype.Component;

@Component
public class FFTokenUtil {
    private static final String TOKEN_PREFIX = "pig_oauth:access:";
    private static final String BEARER_PREFIX = "Bearer ";
    private static final StringRedisSerializer STRING_SERIALIZER = new StringRedisSerializer();
    private static final JdkSerializationRedisSerializer OBJECT_SERIALIZER = new JdkSerializationRedisSerializer();


    public static final String APP_ACCESS_TOKEN = "access_token_";

    @Autowired
    @Qualifier("redisAuthTemplate")
    private RedisTemplate<String, String> redisAuthTemplate;


    @Autowired
    @Qualifier("redisMpassTemplate")
    private RedisTemplate<String, String> redisMpassTemplate;

    /**
     * 通过token去redis取userId
     */
    public Integer getPcUserIdByToken(String token) {
        if (StringUtils.isEmpty(token)){
            return null;
        }
        byte[] key = STRING_SERIALIZER.serialize(TOKEN_PREFIX + token.replaceFirst(BEARER_PREFIX,""));
        byte[] bytes = redisAuthTemplate.execute(new RedisCallback<byte[]>() {
            @Override
            public byte[] doInRedis(RedisConnection connection) throws DataAccessException {
                return connection.get(key);
            }
        });

        OAuth2AccessToken accessToken = (OAuth2AccessToken) OBJECT_SERIALIZER.deserialize(bytes);
        return accessToken != null ? (Integer) accessToken.getAdditionalInformation().get("userId") : null;
    }


    public String getAppUserIdByToken(String token) {
        if (StringUtils.isEmpty(token)){
            return null;
        }
        return redisMpassTemplate.opsForValue().get(APP_ACCESS_TOKEN + token.replaceFirst(BEARER_PREFIX,""));
    }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在使用Redis实现token校验时,可以根据用户的使用情况动态调整token的过期时间。在生成token的同时,将创建token的时间戳存储在Redis中。每次请求被拦截器拦截并通过token验证成功后,将当前时间与存储在Redis中的token生成时间进行比较。如果当前时间距离创建时间快要到达设置的Redis过期时间,就重新设置token的过期时间,延长过期时间。如果用户在设置的Redis过期时间内没有进行任何操作(没有发请求),则token会在Redis中过期。具体的代码实现可以在Controller层生成token信息并存入Redis中,同时与用户登录态建立联系。生成token时,可以使用UUID生成唯一的token,并将token和用户登录态存入Redis中。设置token的过期时间,例如1小时。最后,将token返回给客户端。在拦截器中,通过获取客户端传过来的Authorization字段,尝试从Redis中获取对应的用户名。如果可以获取到用户名,则说明token正确;反之,说明token错误,返回鉴权失败。这样就实现了基于Redistoken校验。\[1\]\[2\]\[3\] #### 引用[.reference_title] - *1* *2* *3* [基于SpringBoot和Redis实现Token权限认证 & 基于redis实现token验证用户是否登陆](https://blog.csdn.net/weixin_38088772/article/details/111319039)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insert_down28v1,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值