Security禁用session

本文介绍如何在使用JWT的认证系统中禁用Session,包括调整Spring Security配置以实现STATELESS策略,避免session的创建,以及自定义的SessionAuthenticationStrategy实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Security禁用Seesion
  • 调用登录接口认证用户名及密码,成功后返回token(JWT),前端拿到这个token后根据前文的鉴权方式进行。
  • 服务端对后续请求在过滤链中(认证过滤器前的过滤器)新增JWT的验证,从JWT中提取用户名并生成userInfo然后利用下面的代码,security自然会认证通过,该实现原理和SecurityContextPersistenceFilter一样。点击查看原理
UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userInfo, null, userInfo.getAuthorities());		SecurityContextHolder.getContext().setAuthentication(authentication);
  • 上诉方式因为要使用的是token方式,不希望生成session。检查一下几个地方
一、security的session生成策略改为security不主动创建session即STALELESS
httpSecurity.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
二、检查代码中是否有调用request.getSession()

在我们的项目中,自定义了session策略,当检测到http头中使用了token便不调用sessionRegistry进行注册新会话。如下:

public class MySessionAuthenticationStrategy implements SessionAuthenticationStrategy {
    private final SessionRegistry sessionRegistry;

    public void onAuthentication(Authentication authentication, HttpServletRequest request,
            HttpServletResponse response) {
        if (request.getHeader("token") == null) {
            sessionRegistry.registerNewSession(request.getSession().getId(), authentication.getPrincipal());
    	}
    }
}
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值