
若依框架api走jwt验证的实现流程
在若依框架前后端分离版开发中,如果需要实现不同的路由走不同的jwt验证逻辑,可以使用策略模式来实现:
定义一个策略接口 authenticationstrategy,用于定义认证逻辑。创建具体策略实现 apiauthenticationstrategy 和 defaultauthenticationstrategy,后续有需要继续创建新的策略。创建策略工厂 authenticationstrategyfactory,根据请求路径返回对应的策略实例。修改 jwtauthenticationtokenfilter 类来使用策略模式。编写策略实现和工厂类,后续添加策略时,仅需添加对应实现和工厂类的逻辑,其他部分无需修改。
示例代码:
AI图像编辑器
使用文本提示编辑、变换和增强照片
46 查看详情
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter { private final AuthenticationStrategyFactory factory; public JwtAuthenticationTokenFilter(AuthenticationStrategyFactory factory) { this.factory = factory; } @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException { AuthenticationStrategy strategy = factory.createStrategy(request); strategy.authenticate(request); chain.doFilter(request, response); } interface AuthenticationStrategy { void authenticate(HttpServletRequest request) throws ServletException, IOException; } static class ApiAuthenticationStrategy implements AuthenticationStrategy { private final ApiTokenService apiTokenService; ApiAuthenticationStrategy(ApiTokenService apiTokenService) { this.apiTokenService = apiTokenService; } @Override public void authenticate(HttpServletRequest request) { // 根据API路由做具体JWT验证逻辑 } } static class DefaultAuthenticationStrategy implements AuthenticationStrategy { private final TokenService tokenService; DefaultAuthenticationStrategy(TokenService tokenService) { this.tokenService = tokenService; } @Override public void authenticate(HttpServletRequest request) { // 根据其他路由做具体JWT验证逻辑 } } @Component static class AuthenticationStrategyFactory { private final ApiAuthenticationStrategy apiStrategy; private final DefaultAuthenticationStrategy defaultStrategy; public AuthenticationStrategyFactory(ApiTokenService apiTokenService, TokenService tokenService) { this.apiStrategy = new ApiAuthenticationStrategy(apiTokenService); this.defaultStrategy = new DefaultAuthenticationStrategy(tokenService); } public AuthenticationStrategy createStrategy(HttpServletRequest request) { String requestURI = request.getRequestURI(); if (requestURI.startsWith("/api")) { return apiStrategy; } else { return defaultStrategy; } } }}
通过这种方式,可以实现不同的路由走不同的jwt验证逻辑,满足不同业务场景的需求。
以上就是若依框架中如何实现不同路由使用不同JWT验证逻辑?的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/372431.html
微信扫一扫
支付宝扫一扫