Zuul reverse proxy with Keycloak server

后端 未结 2 894
一个人的身影
一个人的身影 2021-02-04 18:26

I\'m configuring a Spring Cloud (Angel.SR6) application using the Zuul reverse proxy utility, in order to hide the internal service ports. My zuul (edge) service is published in

相关标签:
2条回答
  • 2021-02-04 18:27

    Recently I've had the same problem. I've solved it by:

    1. Add to application.properties in Zuul

      zuul.sensitive-headers=Cookie,Set-Cookie

    2. Introduce KeycloakFilterRoute in Zuul

      class KeycloakFilterRoute extends ZuulFilter {
      
      private static final String AUTHORIZATION_HEADER = "authorization";
      
      @Override
      public String filterType() {
          return "route";
      }
      
      @Override
      public int filterOrder() {
          return 0;
      }
      
      @Override
      public boolean shouldFilter() {
          return true;
      }
      
      @Override
      public Object run() {
          RequestContext ctx = RequestContext.getCurrentContext();
          if (ctx.getRequest().getHeader(AUTHORIZATION_HEADER) == null) {
              addKeycloakTokenToHeader(ctx);
          }
          return null;
      }
      
      private void addKeycloakTokenToHeader(RequestContext ctx) {
          RefreshableKeycloakSecurityContext securityContext = getRefreshableKeycloakSecurityContext(ctx);
          if (securityContext != null) {
              ctx.addZuulRequestHeader(AUTHORIZATION_HEADER, buildBearerToken(securityContext));
          }
      }
      
      private RefreshableKeycloakSecurityContext getRefreshableKeycloakSecurityContext(RequestContext ctx) {
          if (ctx.getRequest().getUserPrincipal() instanceof KeycloakAuthenticationToken) {
              KeycloakAuthenticationToken token = (KeycloakAuthenticationToken) ctx.getRequest().getUserPrincipal();
              return (RefreshableKeycloakSecurityContext) token.getCredentials();
          }
          return null;
      }
      
      private String buildBearerToken(RefreshableKeycloakSecurityContext securityContext) {
          return "Bearer " + securityContext.getTokenString();
      }
      

      }

    0 讨论(0)
  • 2021-02-04 18:52

    (Migrated from comment to answer)

    I ended up making a Github project in order to explain my problem to the keycloak team, and got a pull request from one of the development team members trying to help me out. Following their recommendations, I came into the conclusion that zuul is good to hide stateless services (bearer only ones), but not the ones that user directly interacts with. Here it is the whole thread in the mailing list.

    0 讨论(0)
提交回复
热议问题