springsecurity + session sharing + redis user login, permission verification,

Table of contents

1. Add relevant dependencies to pom.xml:

2. Add configuration to application.yml:

3. Test

4. Pitfall record: If the above configuration is good, you will encounter the following error


The relevant configuration of spring security is not listed here.

1. Add relevant dependencies to pom.xml:

Add two dependencies: dependence on redis and redis as session cache

    <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. Add configuration to 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. Test

In principle, just start the springboot startup class directly and you can use it normally.

1) postman test login:

2) Check the redis species and saved session records:

4. Pitfall record: If the above configuration is good, you will encounter the following error

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')
This is because of the possible new springboot version (my current version is 2.5.3 ), you need to add a statement on the main startup class: @EnableRedisHttpSession.

(In the previous version 2.1.4.RELEASE, it will take effect automatically if not added).

I configured the Session expiration time here to be 1 hour. The native server.session.timeout property no longer takes effect.

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

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


 

Guess you like

Origin blog.csdn.net/louis_lee7812/article/details/127436264