ARTICLE DETAIL

建站实战干货

来自一线的建站与推广经验沉淀,每一条都经过真实交付验证。

第11讲实现JWT认证过滤器

2026/9/17 17:03:54 拓冰建站 浏览量
第11讲实现JWT认证过滤器

router配置,加下首页路由

{path: '/',name: '首页',component: () => import('../layout')
},

在这里插入图片描述
测试按钮

<template>
<el-button type="danger" @click="testHandler">测试接口</el-button>
</template><script setup>
import requestUtil from '@/util/request'const testHandler=async ()=>{let result=await requestUtil.get("test/user/list");}
</script><style scoped></style>

由于做了前后端分离配置,通过jwt生成token,所以我们要搞一个jwt自定义认证过滤器,来实现jwt token认证;

/*** jwt认证自定义过滤器* @author java1234_小锋 (公众号:java1234)* @site www.java1234.vip* @company 南通小锋网络科技有限公司*/
public class JwtAuthenticationFilter extends BasicAuthenticationFilter {@Autowiredprivate SysUserService sysUserService;@Autowiredprivate MyUserDetailServiceImpl myUserDetailService;private static final String URL_WHITELIST[] ={"/login","/logout","/captcha","/password","/image/**"} ;public JwtAuthenticationFilter(AuthenticationManager authenticationManager) {super(authenticationManager);}@Overrideprotected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {String token=request.getHeader("token");System.out.println("请求url:"+request.getRequestURI());// 如果token是空或者url在白名单里 则放行 让后面的springsecurity认证过滤器去认证if(StringUtil.isEmpty(token)|| new ArrayList<String>(Arrays.asList(URL_WHITELIST)).contains(request.getRequestURI())){chain.doFilter(request,response);return;}CheckResult checkResult = JwtUtils.validateJWT(token);if(!checkResult.isSuccess()){switch (checkResult.getErrCode()){case JwtConstant.JWT_ERRCODE_NULL: throw new JwtException("Token不存在");case JwtConstant.JWT_ERRCODE_FAIL: throw new JwtException("Token验证不通过");case JwtConstant.JWT_ERRCODE_EXPIRE: throw new JwtException("Token过期");}}Claims claims=JwtUtils.parseJWT(token);String username=claims.getSubject();SysUser sysUser = sysUserService.getByUsername(username);UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken=new UsernamePasswordAuthenticationToken(username,null,myUserDetailService.getUserAuthority(sysUser.getId()));SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);chain.doFilter(request,response);}
}

SecurityConfig配置

@Bean
JwtAuthenticationFilter jwtAuthenticationFilter() throws Exception {JwtAuthenticationFilter jwtAuthenticationFilter=new JwtAuthenticationFilter(authenticationManager());return jwtAuthenticationFilter;
}

在这里插入图片描述