在应用程序中为多个服务调用相同的方法

发布于 2025-01-24 15:53:03 字数 1954 浏览 1 评论 0原文

我的应用程序由多个服务组成。我们现在有一个要求,对于我们申请的每个请求,我们都需要验证令牌。

我的应用程序的当前体系结构使每个微服务都有自己的ServiceInterceptor类,在该类中,我正在用Prehandle方法编写逻辑,以验证在请求中收到的令牌。

服务拦截器类。

 @Component
 public class ServiceInterceptor implements HandlerInterceptor {
 private static final ApplicationLogger logger = ApplicationLogger.getInstance();

 @Autowired
 TokenInfoServiceImpl tokenInfoServiceImpl;

@Override
@CrossOrigin(origins = "*", maxAge = 3600)
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
        throws Exception {      
    String requestPath = request.getRequestURL().toString();
    String authToken = request.getHeader("authToken");
    String bearerToken = request.getHeader("Authorization");
    String userId = request.getHeader("userId");
    
    if (deviceId.equals("web")) {
        if (bearerToken.startsWith("Bearer ")){
            bearerToken = bearerToken.substring(7, bearerToken.length());
        } else {
           response.sendError(400, "Expected bearer prefix to Authorization header value.");
        }
        boolean isTokenValid = tokenInfoServiceImpl.validateToken(bearerToken);
        return isTokenValid;
        
    }
    return true;
}

@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
        ModelAndView modelAndView) throws Exception {
    System.out.println("Post Handle method is Calling");
}

@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
        Exception exception) throws Exception {
    System.out.println("Request and Response is completed");
}
}

我担心的是,由于我们有不同的服务,每个服务都有其Interceptor类,因此在每项服务中,我都必须创建方法validatekoken(在该服务的请求时验证令牌),这显然不是理想的方法。 有没有一种方法可以在一个地方编写valitatoken方法,并且可以使用所有服务(例如Userervice,Paymentservice等)访问的方法,或者可以使用一个拦截器来拦截所有个人微服务的请求,而不是拥有每个服务的单独拦截器。

我知道这可以使用API​​网关完成,但是现在我们的团队需要快速解决此.API网关以后实现。

My application consists of multiple services.We had a requirement now that for every request coming in to our application we need to validate the token.

Current architecture of my application is such that every microservice has its own ServiceInterceptor class and in that class I am writing the logic in prehandle method to validate token recieved in request.

Service Interceptor Class.

 @Component
 public class ServiceInterceptor implements HandlerInterceptor {
 private static final ApplicationLogger logger = ApplicationLogger.getInstance();

 @Autowired
 TokenInfoServiceImpl tokenInfoServiceImpl;

@Override
@CrossOrigin(origins = "*", maxAge = 3600)
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
        throws Exception {      
    String requestPath = request.getRequestURL().toString();
    String authToken = request.getHeader("authToken");
    String bearerToken = request.getHeader("Authorization");
    String userId = request.getHeader("userId");
    
    if (deviceId.equals("web")) {
        if (bearerToken.startsWith("Bearer ")){
            bearerToken = bearerToken.substring(7, bearerToken.length());
        } else {
           response.sendError(400, "Expected bearer prefix to Authorization header value.");
        }
        boolean isTokenValid = tokenInfoServiceImpl.validateToken(bearerToken);
        return isTokenValid;
        
    }
    return true;
}

@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
        ModelAndView modelAndView) throws Exception {
    System.out.println("Post Handle method is Calling");
}

@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
        Exception exception) throws Exception {
    System.out.println("Request and Response is completed");
}
}

My concern is since we have different services,every service has its interceptor class , so in every service will I have to create method validateToken(to validate the token when a request comes to that service) which is obviously not at all an ideal approach.
Is there a way that I could write validateToken method in one place and that could be accessed by all the services(like UserService,PaymentService,etc..) or rather one Interceptor could be used to intercept request for all the individual microservices instead of having separate interceptor for each service .

I know this can be done using API Gateway but right now our team want a quick solution to this .API Gateway will implement later.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

隔岸观火 2025-01-31 15:53:03

如果我理解您的问题&注释您可以在下面尝试:

  1. 创建配置bean实现 webmvcccconfigurer

  2. 使用service Interspector ins addintecteptor &amp&amp& amp; amp; amp; amp; amp;提及端点或根上下文,如果所有端点都需要此配置:

      @configuration
     公共类ConfigClass实现WebMvcconFigurer {
     @Override
         public void addinterceptors(interceptorRegistry注册表){
             registry.addinterceptor(new ServiceInterceptor())。addPathPatterns(“/contextroot/**”); 
         }
     }
     

您也可以直接使用service Interceptor而无需使用component注释它。

If I understand your question & comments you can try below :

  1. Create Configuration bean which implements WebMvcConfigurer

  2. Use your ServiceInterceptor inside addInteceptor & mention endpoints or root context if all endpoints needed this config :

    @Configuration
     public class ConfigClass implements WebMvcConfigurer{
     @Override
         public void addInterceptors(InterceptorRegistry registry) {
             registry.addInterceptor(new ServiceInterceptor ()).addPathPatterns("/contextroot/**"); 
         }
     }
    

Also you may directly use your ServiceInterceptor without annotating it with Component.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文