spring-security过滤器是否从redis中获取会话信息?

php小编子墨在这里解答关于spring security过滤器是否从redis中获取会话信息的问题。spring security是一个强大的安全框架,它提供了一套完整的身份验证和授权机制。在默认情况下,spring security使用httpsession来管理用户的会话信息。然而,通过配置,我们可以将会话信息存储在redis等外部存储中。这样做的好处是可以实现分布式会话管理,提高系统的可伸缩性。因此,spring security过滤器是可以从redis中获取会话信息的。

问题内容

我正在尝试使用 spring-boot、spring-security 和 spring-session 实现登录系统,并使用 redis 作为会话的存储。

我的配置:

@enablewebsecurity@enablemethodsecurity@configuration@requiredargsconstructorpublic class securityconfig {    private final userdetailsservice detailsservice;    @bean    public passwordencoder passwordencoder() {        return new bcryptpasswordencoder();    }    @bean    public authenticationprovider authenticationprovider(passwordencoder passwordencoder) {        daoauthenticationprovider provider = new daoauthenticationprovider();        provider.setpasswordencoder(passwordencoder);        provider.setuserdetailsservice(this.detailsservice);        return provider;    }    @bean    public authenticationmanager authenticationmanager(authenticationprovider authenticationprovider) {        return new providermanager(authenticationprovider);    }    @bean    public securityfilterchain filterchain(httpsecurity http) throws exception {        return http                .csrf().disable()                .cors(customizer.withdefaults())                .authorizehttprequests(auth -> {                    auth.requestmatchers("/api/v1/auth/register/**", "/api/v1/auth/login").permitall();                    auth.anyrequest().authenticated();                })                .sessionmanagement(sessionmanagement -> sessionmanagement                        .sessioncreationpolicy(if_required) //                        .sessionfixation(sessionmanagementconfigurer.sessionfixationconfigurer::newsession) //                        .maximumsessions(100000) //                        //.sessionregistry(sessionregistry())                )                //.exceptionhandling((ex) -> ex.authenticationentrypoint(this.authentrypoint))                .logout(out -> out                        .logouturl("/api/v1/auth/logout")                        .invalidatehttpsession(true) // invalidate all sessions after logout                        .deletecookies("jsessionid")                        .logoutsuccesshandler((request, response, authentication) ->                                securitycontextholder.clearcontext()                        )                )                .build();    }    @bean    public securitycontextrepository securitycontextrepository() {        return new httpsessionsecuritycontextrepository();    }}

登录后复制

我的登录控制器:

@postmapping("/login")public void login(@requestbody loginform form, httpservletrequest request, httpservletresponse response) {    string ip = httprequestutil.getip(request);    string device = httprequestutil.getdevice(request);    loginformwrapper loginformwrapper = new loginformwrapper(form.email(), form.password(), ip, device);    authenticationservice.login(loginformwrapper, request, response);}

登录后复制

和身份验证服务:

@overridepublic void login(loginformwrapper form, httpservletrequest request, httpservletresponse response) {    authentication authentication = authenticationmanager.authenticate(usernamepasswordauthenticationtoken.unauthenticated(            form.email().trim(), form.password()));    // create a new context    securitycontext context = securitycontextholder.createemptycontext();    context.setauthentication(authentication);    // update securitycontextholder and strategy    this.securitycontextholderstrategy.setcontext(context);    this.securitycontextrepository.savecontext(context, request, response);}

登录后复制

如果我理解正确的话

this.securitycontextholderstrategy.setcontext(context); 应该将身份验证保存在应用程序的内存中,例如在 threadlocal 上下文中

`this.securitycontextrepository.savecontext(context, request, response);`

登录后复制

应该将会话信息保存到redis中。

现在,当我登录时,我看到数据已保存到 redis 中:

但是,当检查我的登录请求返回的内容时,我看到:

完全不同的会话 id。

我的第一个问题是:为什么这些 id 不匹配? spring 如何知道要寻找哪个键?

另一个问题是:什么过滤器从redis中获取数据?我尝试调试过滤器链中的所有过滤器:

[org.springframework.security.web.session.DisableEncodeUrlFilter@2fedae96,org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter@4945cd1f,org.springframework.security.web.context.SecurityContextHolderFilter@72499396,org.springframework.security.web.header.HeaderWriterFilter@7048d039,org.springframework.web.filter.CorsFilter@2dbfcbe4,org.springframework.security.web.authentication.logout.LogoutFilter@5d5a77de,org.springframework.security.web.session.ConcurrentSessionFilter@1f8e1096,org.springframework.security.web.savedrequest.RequestCacheAwareFilter@651bec9a,org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter@76d4e1af,org.springframework.security.web.authentication.AnonymousAuthenticationFilter@6f13ed1,org.springframework.security.web.session.SessionManagementFilter@642693c2,org.springframework.security.web.access.ExceptionTranslationFilter@2199e1a4,org.springframework.security.web.access.intercept.AuthorizationFilter@48c584c]

登录后复制

但它似乎以某种方式从 httpservletrequest 读取会话信息 – 但是,如果我从 redis 中删除密钥,则需要它的端点的身份验证失败。

我错过了什么吗?是否在我的 fitler 开始之前检索来自 redis 的会话信息并将其存储在 httpservlerrequest 中?或者说它是如何读取redis数据的?

感谢您的帮助。

解决方法

会话cookie中的值是base64编码的:

echo '3c048eae-9f73-4df5-a009-bdf802ae37ca' | openssl base64m2mwndhlywutowy3my00zgy1lwewmdktymrmodayywuzn2nhcg==

登录后复制

echo 'M2MwNDhlYWUtOWY3My00ZGY1LWEwMDktYmRmODAyYWUzN2NhCg==' | openssl base64 -d3c048eae-9f73-4df5-a009-bdf802ae37ca

登录后复制

因此,当进行 base64 解码时,cookie 的会话 id 与存储在 redis 中的会话 id 相匹配。

如果您还没有阅读过它,我会推荐此文档:https://www.php.cn/link/e27c71957d1e6c223e0d48a165da2ee1

特别是“了解会话管理的组件”部分:https://www.php.cn/link/e27c71957d1e6c223e0d48a165da2ee1#understanding-session-management-components

您没有提到您正在使用哪个版本的 spring security,但我猜测您正在使用 spring security 6。在该部分中,有这样一句话与 sessionauthentication 相关:

以上就是spring-security过滤器是否从redis中获取会话信息?的详细内容,更多请关注【创想鸟】其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至253000106@qq.com举报,一经查实,本站将立刻删除。

发布者:PHP中文网,转转请注明出处:https://www.chuangxiangniao.com/p/2621946.html

(0)
上一篇 2025年3月6日 23:41:01
下一篇 2025年3月6日 23:41:08

AD推荐 黄金广告位招租... 更多推荐

相关推荐

发表回复

登录后才能评论