自定义Spring Security过滤器 JwtAuthenticationTokenFilter

自定义Spring Security过滤器 JwtAuthenticationTokenFilter

闪送平台项目filter包下JwtAuthenticationTokenFilter

在spring-security原本的FilterChain中, 添加 jwt认证用的Filter :JwtAuthenticationTokenFilter。

放在所有过滤器前面,检查浏览器携带的token是否合法

@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
    @Autowired
    StringRedisTemplate stringRedisTemplate;
    
    // 用于在线程本地存储用户的ID信息。这样,同一线程中的其他组件,比如其他过滤器或拦截器,都能够方便地获取到用户的ID信息。
    public static ThreadLocal<Long> threadLocal = new ThreadLocal<>();

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //获取token
        String accessToken = request.getHeader(KeyProperties.TOKEN_HEADER);
        if (StringUtils.isEmpty(accessToken)) {
            filterChain.doFilter(request, response);
            //加return为了返回时第二次经过过滤器不再执行下面的代码
            return;
        }
        if (accessToken.startsWith("Bearer ")) {
            accessToken = accessToken.substring(7);
        }
        //解析token
        String userId = "";
        Claims claims = null;
        try {
            claims = JwtUtil.parseJWT(accessToken);
        } catch (Exception e) {
            throw new BizException(ErrorCode.TOKEN_PARSE_ERROR);
        }
        userId = claims.getSubject();
        //从redis获取用户信息
        String key = KeyProperties.TOKEN_PREFIX + userId;
        String userInfo = stringRedisTemplate.opsForValue().get(key);
        UserPermission userPermission = JSONObject.parseObject(userInfo, UserPermission.class);
        if (userPermission == null) {
            throw new BizException(ErrorCode.TOKEN_PARSE_ERROR);
        }
        //存入SecurityContextHolder
        // 获取权限信息封装到authticationToken中
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(userPermission, null, null);
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        //存入ThreadLocal
        threadLocal.set(Long.valueOf(userId));
        //放行
        filterChain.doFilter(request, response);
    }
}

这个过滤器的作用是在请求到达时验证 JWT,并将用户信息存储到 Spring Security 的上下文和 ThreadLocal 中,方便后续的权限验证和用户信息获取。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Security 6中自定义权限过滤器的步骤如下: 1.创建一个类并实现`org.springframework.web.filter.OncePerRequestFilter`接口。 2.覆盖`doFilterInternal`方法,该方法接收`HttpServletRequest`和`HttpServletResponse`对象作为参数,并在其中编写自定义过滤器的逻辑。 3.使用`@Component`注释将自定义过滤器类标记为Spring组件。 4.在Spring Security配置类中使用`http.addFilterBefore()`方法将自定义过滤器添加到过滤器链中。 下面是一个示例代码,演示如何在Spring Security 6中创建自定义权限过滤器: ```java import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import org.springframework.stereotype.Component; import org.springframework.web.filter.OncePerRequestFilter; @Component public class CustomAuthorizationFilter extends OncePerRequestFilter { @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { // 在这里编写自定义过滤器的逻辑 // 检查用户是否有足够的权限访问请求的资源 // 如果没有权限,可以返回HTTP 403 Forbidden响应 // 如果有权限,可以继续处理请求 filterChain.doFilter(request, response); } } ``` 在Spring Security配置类中添加以下代码: ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private CustomAuthorizationFilter customAuthorizationFilter; @Override protected void configure(HttpSecurity http) throws Exception { http.addFilterBefore(customAuthorizationFilter, UsernamePasswordAuthenticationFilter.class) .authorizeRequests() .antMatchers("/admin/**").hasRole("ADMIN") .antMatchers("/user/**").hasRole("USER") .anyRequest().authenticated() .and() .formLogin() .and() .httpBasic(); } } ``` 在上面的示例中,我们创建了一个名为`CustomAuthorizationFilter`的自定义过滤器,并将其添加到Spring Security过滤器链中。在Spring Security配置类中,我们使用`http.addFilterBefore()`方法将自定义过滤器添加到过滤器链中,并使用`authorizeRequests()`方法配置了请求的授权规则。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值