首页 > Java > 正文

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

PHPz
发布: 2024-02-09 22:30:08
转载
611人浏览过

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

问题内容

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

我的配置:

@enablewebsecurity
@enablemethodsecurity
@configuration
@requiredargsconstructor
public 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);
}
登录后复制

和身份验证服务:

@override
public 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。

微信 WeLM
微信 WeLM

WeLM不是一个直接的对话机器人,而是一个补全用户输入信息的生成模型。

微信 WeLM33
查看详情 微信 WeLM

我的第一个问题是:为什么这些 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 base64
m2mwndhlywutowy3my00zgy1lwewmdktymrmodayywuzn2nhcg==
登录后复制
echo 'M2MwNDhlYWUtOWY3My00ZGY1LWEwMDktYmRmODAyYWUzN2NhCg==' | openssl base64 -d
3c048eae-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中获取会话信息?的详细内容,更多请关注php中文网其它相关文章!

最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:stackoverflow网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号