当前位置: 首页 > 知识库问答 >
问题:

如何在Spring引导应用程序中获得具有Spring安全性和Redis的当前身份验证用户主体

陈马鲁
2023-03-14

我希望使用Spring Security性和Json Web令牌(JWT)保护我的服务,并使用spring会话将登录用户存储在redis中。所以,当用户发送登录请求时,我对用户进行身份验证,并将生成的令牌发送回,如下所示:

public ResponseEntity<?> createAuthenticationToken(@RequestBody JwtAuthenticationRequest authenticationRequest, Device device) throws AuthenticationException {

    // Perform the security
    final Authentication authentication = authenticationManager.authenticate(
            new UsernamePasswordAuthenticationToken(
                    authenticationRequest.getUsername(),
                    authenticationRequest.getPassword()
            )
    );
    SecurityContextHolder.getContext().setAuthentication(authentication);


    final UserDetails userDetails = userDetailsService.loadUserByUsername(authenticationRequest.getUsername());
    final String token = jwtTokenUtil.generateToken(userDetails, device);

    // Return the token
    return ResponseEntity.ok(new JwtAuthenticationResponse(token));
}

我还将该用户添加到会话(支持Redis会话):

HttpSession session = request.getSession(false);
    if (session != null) {
        session.setMaxInactiveInterval(30 * 600);
        JwtUser user = (JwtUser) authentication.getPrincipal();
        session.setAttribute("user", user);

    }

在我检查redis之后,我看到用户会话已经设置为redis。但当我收到来自用户的下一次尝试时,它变成了匿名用户,理想情况下它不应该这样做。

        Authentication auth = SecurityContextHolder.getContext().getAuthentication();

我看到调试屏幕主体返回匿名用户。

我还尝试如下:

@RequestMapping(value = "/username", method = RequestMethod.GET)
@ResponseBody
public String currentUserNameSimple(HttpServletRequest request) {
    Principal principal = request.getUserPrincipal();
    return principal.getName();
}

但是本金是无效的。

我的redis配置:

@Configuration
@EnableRedisHttpSession 
public class RedisConfig implements BeanClassLoaderAware {

private ClassLoader loader;


@Bean(name = { "defaultRedisSerializer", "springSessionDefaultRedisSerializer" })
public RedisSerializer<Object> springSessionDefaultRedisSerializer() {
    return new GenericJackson2JsonRedisSerializer(objectMapper());

}

@Bean
public HttpSessionStrategy httpSessionStrategy() {
        return new HeaderHttpSessionStrategy(); 
}

@Bean
JedisConnectionFactory jedisConnectionFactory() {
    JedisConnectionFactory jedisConFactory = new JedisConnectionFactory();
    jedisConFactory.setHostName("localhost");
    jedisConFactory.setPort(6379);
    return jedisConFactory;
}

ObjectMapper objectMapper() {
    ObjectMapper mapper = new ObjectMapper();
    mapper.registerModules(SecurityJackson2Modules.getModules(this.loader));
    return mapper;
}

public void setBeanClassLoader(ClassLoader classLoader) {
    this.loader = classLoader;
}

}

Maven依赖项:

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-tomcat</artifactId>
        <scope>provided</scope>
    </dependency>

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

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-mail</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-security</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-configuration-processor</artifactId>
        <optional>true</optional>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
        <version>1.4.3.RELEASE</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core -->




    <!-- Password Validation -->
    <dependency>
        <groupId>org.passay</groupId>
        <artifactId>passay</artifactId>
        <version>${passay.version}</version>
    </dependency>




    <dependency>
        <groupId>org.springframework.mobile</groupId>
        <artifactId>spring-mobile-device</artifactId>
        <version>1.1.4.RELEASE</version>
    </dependency>

    <!--JWT -->
    <dependency>
        <groupId>io.jsonwebtoken</groupId>
        <artifactId>jjwt</artifactId>
        <version>0.7.0</version>
    </dependency>

    <dependency>
        <groupId>az.com.cybernet.utilities</groupId>
        <artifactId>utilities</artifactId>
        <version>0.0.1</version>
        <scope>compile</scope>
    </dependency>
    <dependency>
        <groupId>az.com.cybernet.beans</groupId>
        <artifactId>disieibeans</artifactId>
        <version>0.0.1</version>
        <scope>compile</scope>
    </dependency>



    <!-- DB dependencies -->
    <dependency>
        <groupId>org.postgresql</groupId>
        <artifactId>postgresql</artifactId>
        <version>9.4-1200-jdbc41</version>
    </dependency>




    <dependency>
        <groupId>javax.el</groupId>
        <artifactId>el-api</artifactId>
        <version>2.2</version>
    </dependency>


    <dependency>
        <groupId>net.logstash.logback</groupId>
        <artifactId>logstash-logback-encoder</artifactId>
        <version>4.8</version>
    </dependency>



    <!-- REDIS -->
    <dependency>
        <groupId>org.springframework.session</groupId>
        <artifactId>spring-session-data-redis</artifactId>
        <version>2.0.0.BUILD-SNAPSHOT</version>
        <type>pom</type>
    </dependency>
        <dependency>
        <groupId>redis.clients</groupId>
        <artifactId>jedis</artifactId>
        <version>2.5.1</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-core</artifactId>
        <version>4.2.0.RELEASE</version>
    </dependency>




</dependencies>

没有Redis,一切都很好,但有了Redis,我无法获得当前经过身份验证的用户的主体

共有2个答案

潘英豪
2023-03-14

这里也有类似的问题。

使用auth key/sessionId调用redisOperationsSessionRepository。

希望有帮助:)

汝飞
2023-03-14

我刚刚将绝地武士的客户机改为莴苣客户机,如下所示,解决了问题:

     <dependency>
        <groupId>biz.paluch.redis</groupId>
        <artifactId>lettuce</artifactId>
        <version>3.5.0.Final</version>
    </dependency>

在spring之前,安全主体对象为null,因为名为“JSESSIONID”的cookie不是由Jedis客户端创建的。

@EnableRedisHttpSession
public class RedisConfig {
@Bean
public LettuceConnectionFactory connectionFactory() {
    return new LettuceConnectionFactory();
}

@Bean
public CookieSerializer cookieSerializer() {
    DefaultCookieSerializer serializer = new DefaultCookieSerializer();
    serializer.setCookieName("JSESSIONID"); // <1>
    serializer.setCookiePath("/"); // <2>
    serializer.setDomainNamePattern("^.+?\\.(\\w+\\.[a-z]+)$"); // <3>
    return serializer;
}
}
 类似资料:
  • 我想对post请求主体密钥-值对中的一个进行身份验证,但我想在拦截器/过滤器的帮助下进行同样的验证。我该怎么做?

  • 我正在尝试通过连接到LDAP使用Spring Security进行我的第一个演示。 我使用的Sping版本是:3.1.0.RELEASE 以下是我的security-integration.xml: 然而,每当我部署我的战争时,我都会遇到这个例外: HTTP状态500 - 类型异常报告 消息 描述服务器遇到一个内部错误(),该错误阻止它完成此请求。 例外情况 javax.servlet。Servl

  • 问题内容: 我想通过spring安全性和Json Web Token(JWT)保护我的服务,并通过Spring session将登录的用户存储在redis中。因此,当用户发送登录请求时,我对用户进行身份验证并将生成的令牌发送回如下所示: 我也将该用户添加到会话(支持Redis会话)中: 之后我检查Redis的,我看已经被设置为redis.But当我收到来自用户下一次尝试的用户会话成为 anonym

  • 我正在尝试让JDBC身份验证与我的小辅助项目一起工作,从表面上看,它应该可以工作,但它没有。所有的配置都遵循贝娄。 如果我切换到具有相同用户名/密码的inMemory身份验证,它就会非常工作。 这是我记录输出时得到的结果: