Express Gateway - Authorization

I have a simple structure as shown in the image below that I have a gateway that manage all request, validate the token, add the loggedUser in the request, and repass it to the correct container. I have a question when the containers make requests with each other because the loggedUser exists only in the first container that received the request, he doesn't repass this property to the other containers.

I have tried creating interceptors in each container in order to add the loggdUser in all requests. But it is causing hard work and I believe it can be an anti-pattern.

Also, something very supernatural happens in some requests, it is keeping the last loggedUser value of the last request made. That is a user who in fact is not actually logged in at the moment. I've done some research and haven't found much material on this. Can you tell me the best approach for this scenario.

enter image description here

Router

  router.get('/load/account', expressRouterAdapter(loadAccountControllerFactory()))

expressRouterAdapter

export const expressRouterAdapter = (controller: Controller): any => {
  return async (req: Request & { loggedUser: any}, res: Response, next: NextFunction) => {
    const { body, params, headers, query } = req
    const interceptor = InterceptorAdapter.interceptRequest()
    interceptor.addHeader({Authorization: headers.authorization})
    const response = await controller.handle({ body, params, 
    headers, query })
    res.status(response.statusCode)
    if (response.statusCode === 200) {
    res.json(response.body)
    } else {
      res.json({
        error: response.body
      })
   }

}

}

Interceptor:

export class InterceptorAdapter implements AddRequestHeader {
  static request: AxiosInterceptorManager<AxiosRequestConfig>

  private constructor(
    expressRequest?: AxiosInterceptorManager<AxiosRequestConfig>
  ) {
    InterceptorAdapter.request = expressRequest
  }
  static interceptRequest(): InterceptorAdapter {
    axios.interceptors.request.clear()
    return new InterceptorAdapter(axios.interceptors.request)
  }

  addHeader(header: AddRequestHeader.Header) {
    InterceptorAdapter.request.use(req => {
      return { ...req, headers: { ...header } }
    }, error => error)
  }
}

gateway policies:

  - cors:    
  - log: 
      action:
        message: 'auth ${req.method}'

  - jwt:
      action:
        secretOrPublicKey: 'MY KEY'
        checkCredentialExistence: false
        
  - request-transformer:
      action:
        body: 
          add:
            loggedUser: req.user
  - proxy:
      - action:
          serviceEndpoint: svcap20Service
          changeOrigin: true

Upvotes: 0

Views: 83

Answers (0)

Related Questions