Spring Session(Redis) | X-Auth-Token | 自动刷新 Token

  |   0 评论   |   0 浏览

Spring Session (Redis) | X-Auth-Token | 自动刷新 Token

pom and yml

pom.xml

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
	<groupId>org.springframework.session</groupId>
	<artifactId>spring-session-data-redis</artifactId>
</dependency>

application.yml

spring.application.name: x-auth-token
server.port: 80

spring.session.store-type: redis
server.servlet.session.timeout:
spring.session.redis.flush-mode: on_save
spring.session.redis.namespace: spring:session

spring.redis.host: 192.168.1.18
spring.redis.port: 6379
#spring.redis.password:

Java Class

HttpSessionConfig


package com.lab.token.session;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession;
import org.springframework.session.web.http.HeaderHttpSessionIdResolver;
import org.springframework.session.web.http.HttpSessionIdResolver;

@Configuration
@EnableRedisHttpSession
public class HttpSessionConfig {

    @Bean
    public HttpSessionIdResolver httpSessionIdResolver() {
        return HeaderHttpSessionIdResolver.xAuthToken();
    }

}

SessionInitializer


package com.lab.token.session;

import org.springframework.session.web.context.AbstractHttpSessionApplicationInitializer;

public class SessionInitializer extends AbstractHttpSessionApplicationInitializer {
    public SessionInitializer() {
        super(new Class[] { HttpSessionConfig.class });
    }
}

说明

  • Spring Session 默认通过Cookie传递 SESSIONID
  • 在前后端分离情况,可以通过Header传值,header key 默认为 X-Auth-Token
  • new HeaderHttpSessionIdResolver("X-Auth-Token"); 改变构造函数参数可改变header key
  • 前端发起登录认证后,后端查用户信息返回给前端,同时前端从Header取值X-Auth-Token存sessionStorage
  • 退出 前端清除sessionStorage,后端session.invalidate();后端Spring Session自动会返回一个空的X-Auth-Token
  • 需要认证的请求还是创建拦截器,里面判断session是否已经登录认证过

标题:Spring Session(Redis) | X-Auth-Token | 自动刷新 Token
作者:uid1024
地址:http://javadaily.cn/articles/2021/01/05/1609825538893.html