06-自定义认证授权过滤器-自定义资源授权过滤器

本文介绍了如何在SpringSecurity框架中创建和配置AuthenticationFilter,用于验证JWT令牌并根据角色权限进行授权,确保资源的安全性。通过设置过滤器执行顺序,该过滤器在用户认证流程中起到关键作用。
摘要由CSDN通过智能技术生成

授权实现流程

定义授权过滤器:新建com.itheima.security.filter.AuthenticationFilter

package com.itheima.security.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.itheima.security.utils.JwtTokenUtil;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 授权过滤器,相当于检票员
 */
public class AuthenticationFilter extends OncePerRequestFilter {//OncePerRequestFilter:对每个请求只会执行一次过滤
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String tokenStr = request.getHeader(JwtTokenUtil.TOKEN_HEADER);
        if (StringUtils.isBlank(tokenStr)) {
            filterChain.doFilter(request, response);
            return;
        }

        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        response.setCharacterEncoding("UTF-8");
        Claims claims = JwtTokenUtil.checkJWT(tokenStr);
        if(claims==null){
            Map<String,String> info = new HashMap<>();
            info.put("msg","票据无效");
            info.put("code","0");
            info.put("data","");
            response.getWriter().write(new ObjectMapper().writeValueAsString(info));
            return;
        }
        String username = JwtTokenUtil.getUsername(tokenStr);
        //["P5","ROLE_ADMIN"]
        String roles = JwtTokenUtil.getUserRole(tokenStr);
        //去除[]
        String strip = StringUtils.strip(roles, "[]");
        //把以逗号分隔的字符串转换成GrantedAuthority对象
        List<GrantedAuthority> authorities = AuthorityUtils.commaSeparatedStringToAuthorityList(strip);
        //null为密码,认证通过后security会将密码置为null
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, null, authorities);
        //把authenticationToken存入securityContext,以便后续过滤器使用
        //该上下文以线程为维度,当前访问结束,该线程被回收,上下文凭证也会被回收
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        //后续的过滤器发现上下文中存在token信息,会认为用户已经通过认证
        filterChain.doFilter(request, response);
    }
}

配置授权过滤器

在com.itheima.security.config.SecurityConfig中配置

  @Bean
    public AuthenticationFilter authenticationFilter() {
        return new AuthenticationFilter();
    }

配置授权过滤器的执行顺序,SecurityConfig中配置

@Override
    protected void configure(HttpSecurity http) throws Exception {
        http.formLogin().and().logout().permitAll().and().csrf().disable().
                authorizeRequests();
        //将自定义过滤器加入过滤器链并在默认过滤器的前面执行
        http.addFilterBefore(myUsernamePasswordAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);
        //配置授权过滤器,为了保证资源安全,给与最高优先级,在自定义认证过滤器之前执行
        http.addFilterBefore(authenticationFilter(), MyUsernamePasswordAuthenticationFilter.class);
    }

测试一下,携带token

不携带token访问

 跳到security的内置登录页面

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

敲代码的翠花

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值