在Spring Boot RESTful应用程序中,如何防止已登录的用户再次登录?

问题描述 投票:0回答:2

我使用 springboot 创建了一个简单的 Restful 应用程序。它只有两个api,登录和注册。用户登录后,它返回一个jwt。这是我的配置

protected void configure(HttpSecurity http) throws Exception {
        http.cors().and().csrf().disable()
                .exceptionHandling()
                    .authenticationEntryPoint(unauthorizedHandler)
                    .and()
                .sessionManagement()
                    .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                    .and()
                .authorizeRequests()
                    .antMatchers(HttpMethod.GET, "/api/**").permitAll()
                    .antMatchers(HttpMethod.POST, "/api/auth/**").permitAll()
                    .antMatchers(HttpMethod.GET, "/api/users/checkUsernameAvailability", "/api/users/checkEmailAvailability").permitAll()
                .anyRequest().authenticated();

        http.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
    }

问题是,我注意到经过身份验证的用户可以再次调用 /login api,并返回新的 jwt 令牌。

有没有办法只为未经身份验证的用户配置一些API?喜欢

.antMatchers(HttpMethod.POST, "/api/auth/**").unauthenticatedOnly()

如果没有配置,我想到的解决方法是向用户表添加一个

is_authenticated
列,并且仅对具有
is_authentiacted = false
的用户进行身份验证。有什么好办法吗

spring spring-boot rest spring-security restful-authentication
2个回答
1
投票

如果你想在服务器端验证jwt令牌的出现,我认为令牌必须保存在Redis等存储中,并通过Filter检查它(在Spring Security中设置)。

如果您想通过 Spring 安全性本身来控制它(无需额外的工作),一个可能的简单解决方案是使用 Spring 会话。

Spring Session 类似于 HttpSession,但由 Redis、Mongo 等支持,因此您可以使用 Spring Security 中提供的会话并发策略来确保只有一个用户身份验证有效。您必须在后端切换到Stateful

就我个人而言,我在几个项目中使用了Spring session(保护RESTful API),我认为它很好。这里是使用Spring session(Reactive stack)的例子但是我没有配置会话控制规则)。这是一个微服务示例(Servlet 堆栈)


0
投票

@豆豆 SecurityWebFilterChain filterChain(ServerHttpSecurity http) { http // ... .sessionManagement((会话) -> 会话 .concurrentSessions((并发) -> 并发 .maximumSessions(SessionLimit.of(1)) ) ); 返回 http.build(); }

在 Spring Security 6.3 中已经支持,但是当 AuthenProvider 的自定义 userDetail -> 时它不起作用

© www.soinside.com 2019 - 2024. All rights reserved.