使用自定义过滤器时如何创建 Spring Session?

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

我正在使用 Spring Boot 3.1.1。

我创建了一个自定义过滤器,允许用户使用对路径“/login”的 POST 请求以及包含其凭据的 JSON 正文进行身份验证。

我希望 Spring 会话能够收到身份验证成功的通知并创建相关会话。但它不会创建任何会话(甚至不是匿名会话)。

这是我的过滤器:

public class JsonUsernamePasswordAuthenticationFilter extends AbstractAuthenticationProcessingFilter {

    record LoginRequest(String username, String password) {
    }

    public JsonUsernamePasswordAuthenticationFilter(AuthenticationManager authenticationManager) {
        super(new AntPathRequestMatcher("/login", "POST"), authenticationManager);
        setAuthenticationSuccessHandler(new OkAuthenticationSuccessHandler());
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        try {
            var inputStream = StreamUtils.copyToByteArray(request.getInputStream());
            var loginRequest = new ObjectMapper().readValue(inputStream, LoginRequest.class);

            var authRequest = new UsernamePasswordAuthenticationToken(loginRequest.username(), loginRequest.password());

            return this.getAuthenticationManager().authenticate(authRequest);
        } catch (IOException e) {
            throw new AuthenticationServiceException(e.getMessage(), e);
        }
    }
}

这是成功处理程序:

public class OkAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException {
        response.setStatus(200);
        String body = new ObjectMapper().writeValueAsString(new UserCtrl.DisplayUser(authentication.getName()));
        response.getWriter().print(body);
    }
}

在我的

build.gradle.kts
中,我有

implementation("org.springframework.session:spring-session-core")
implementation("org.springframework.session:spring-session-jdbc")

根据 Spring 文档,这应该是所需的一切:https://docs.spring.io/spring-session/reference/guides/boot-jdbc.html。不过,我确实尝试添加注释

@EnableJdbcHttpSession
或属性
spring.session.store-type=jdbc

在尝试 Spring Session 时,我能够获得一个会话,但是一个匿名会话,数据库中的principal_name 列为空,并且请求将被验证为匿名用户。 另外,我可以在数据库日志中看到每分钟左右运行一次的请求:

DELETE FROM SPRING_SESSION WHERE EXPIRY_TIME < $1
spring spring-boot spring-session
1个回答
-1
投票

查看这两个视频: https://www.youtube.com/watch?v=cpFfzE9eGT0&ab_channel=SeleniumExpresshttps://www.youtube.com/watch?v=ezty6XhOpF8&ab_channel=SeleniumExpress

它很可能至少会帮助您了解底层内容,因为它是 spring 2.x,可能有些事情应该改变。我有

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