若依框架api走jwt验证的实现流程
在若依框架前后端分离版开发中,如果需要实现不同的路由走不同的jwt验证逻辑,可以使用策略模式来实现:
- 定义一个策略接口 authenticationstrategy,用于定义认证逻辑。
- 创建具体策略实现 apiauthenticationstrategy 和 defaultauthenticationstrategy,后续有需要继续创建新的策略。
- 创建策略工厂 authenticationstrategyfactory,根据请求路径返回对应的策略实例。
- 修改 jwtauthenticationtokenfilter 类来使用策略模式。
- 编写策略实现和工厂类,后续添加策略时,仅需添加对应实现和工厂类的逻辑,其他部分无需修改。
示例代码:
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验证逻辑?的详细内容,更多请关注图灵教育其它相关文章!