springsecurity + session共享 + redis的用户登录,权限校验,

目录

1、pom.xml添加相关依赖:

2、application.yml添加配置:

3、测试

4、踩坑记录:如果上述配置好,遇到如下错误


spring security的相关配置这里不在列出

1、pom.xml添加相关依赖:

添加两个依赖:对redis以及redis作为session缓存的依赖

    <dependencies>
        ...
        <!-- redis -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        <!-- 引用SpringSession,同时使用Redis存储缓存数据 -->
        <dependency>
            <groupId>org.springframework.session</groupId>
            <artifactId>spring-session-data-redis</artifactId>
        </dependency>
    </dependencies>

2、application.yml添加配置:

server:
    session:
      cookie:
        name: MYJSESSIONID #可以修改自己定义session名
spring:
  session:
    store-type: redis #使用使用Redis缓存session数据
  redis: #Redis服务器相关配置
    host: 127.0.0.1
    port: 6379
    database: 0
    timeout: 1800000
    lettuce:
      pool:
        max-active: 20
        max-wait: -1
        max-idle: 8
        min-idle: 0

3、测试

原则上,直接启动springboot的启动类,就可以正常使用了

1)postman测试登录:

2)查看redis种,保存的session记录:

4、踩坑记录:如果上述配置好,遇到如下错误

Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘org.springframework.boot.autoconfigure.session.SessionAutoConfiguration$ServletSessionRepositoryValidator’: Invocation of init method failed; nested exception is org.springframework.boot.autoconfigure.session.SessionRepositoryUnavailableException: No session repository could be auto-configured, check your configuration (session store type is ‘redis’)
这是因为可能新的springboot版本(我的当前版本是2.5.3),需要在主启动类上添加声明:@EnableRedisHttpSession。

(在之前的2.1.4.RELEASE这个版本时,不加也会自动生效)。

我这里配置了Session过期时间为1小时。原生的server.session.timeout 属性不再生效。

@SpringBootApplication
@EnableRedisHttpSession(maxInactiveIntervalInSeconds = 1800 * 2 )
public class AuthApplication {

    public static void main(String[] args) {
        SpringApplication.run(AuthApplication.class,args);
    }
}


 

猜你喜欢

转载自blog.csdn.net/louis_lee7812/article/details/127436264