private Response getAuthenticationToken()

in gateway-service-knoxsso/src/main/java/org/apache/knox/gateway/service/knoxsso/WebSSOResource.java [235:348]


  private Response getAuthenticationToken(int statusCode) {
    if (!enableSession) {
      // invalidate the session to avoid autologin
      // Coverity CID 1352857
      HttpSession session = request.getSession(false);
      if (session != null) {
        session.invalidate();
      }
    }
    GatewayServices services =
                (GatewayServices) request.getServletContext().getAttribute(GatewayServices.GATEWAY_SERVICES_ATTRIBUTE);
    boolean removeOriginalUrlCookie = true;
    List<Cookie> originalUrlCookies = CookieUtils.getCookiesForName(request, ORIGINAL_URL_COOKIE_NAME);
    String original;
    if (originalUrlCookies.isEmpty()) {
      // in the case where there are no SAML redirects done before here
      // we need to get it from the request parameters
      removeOriginalUrlCookie = false;
      original = getOriginalUrlFromQueryParams();
      if (original.isEmpty()) {
        LOGGER.originalURLNotFound();
        throw new WebApplicationException("Original URL not found in the request.", Response.Status.BAD_REQUEST);
      }

      boolean validRedirect = true;

      // If there is a whitelist defined, then the original URL must be validated against it.
      // If there is no whitelist, then everything is valid.
      if (whitelist != null) {
        try {
          validRedirect = RegExUtils.checkBaseUrlAgainstWhitelist(whitelist, original);
        } catch (MalformedURLException e) {
          throw new WebApplicationException("Malformed original URL: " + original,
                  Response.Status.BAD_REQUEST);
        }
      }

      if (!validRedirect) {
        LOGGER.whiteListMatchFail(Log4jAuditor.maskTokenFromURL(original), whitelist);
        throw new WebApplicationException("Original URL not valid according to the configured whitelist.",
                                          Response.Status.BAD_REQUEST);
      }
    } else {
      // There should only be one original url cookie for the given path
      original = originalUrlCookies.get(0).getValue();
    }

    Principal p = request.getUserPrincipal();
    ConcurrentSessionVerifier verifier = services.getService(ServiceType.CONCURRENT_SESSION_VERIFIER);
    if (!verifier.verifySessionForUser(p.getName())) {
      throw new WebApplicationException("Too many sessions for user: " + request.getUserPrincipal().getName(), Response.Status.FORBIDDEN);
    }

    AliasService as = services.getService(ServiceType.ALIAS_SERVICE);
    JWTokenAuthority tokenAuthority = services.getService(ServiceType.TOKEN_SERVICE);

    try {
      String signingKeystoreName = context.getInitParameter(SSO_SIGNINGKEY_KEYSTORE_NAME);
      String signingKeystoreAlias = context.getInitParameter(SSO_SIGNINGKEY_KEYSTORE_ALIAS);
      String signingKeystorePassphraseAlias = context.getInitParameter(SSO_SIGNINGKEY_KEYSTORE_PASSPHRASE_ALIAS);
      char[] signingKeystorePassphrase = null;
      if(signingKeystorePassphraseAlias != null) {
        signingKeystorePassphrase = as.getPasswordFromAliasForCluster(clusterName, signingKeystorePassphraseAlias);
      }

      final JWTokenAttributes jwtAttributes = new JWTokenAttributesBuilder()
              .setIssuer(tokenIssuer)
              .setUserName(p.getName())
              .setAudiences(targetAudiences)
              .setAlgorithm(signatureAlgorithm)
              .setExpires(getExpiry())
              .setSigningKeystoreName(signingKeystoreName)
              .setSigningKeystoreAlias(signingKeystoreAlias)
              .setSigningKeystorePassphrase(signingKeystorePassphrase)
              .setManaged(tokenStateService != null)
              .build();
      JWT token = tokenAuthority.issueToken(jwtAttributes);

      // Coverity CID 1327959
      if (token != null) {
        if (!verifier.registerToken(p.getName(), token)) {
          throw new WebApplicationException("Too many sessions for user: " + request.getUserPrincipal().getName(), Response.Status.FORBIDDEN);
        }
        saveToken(token);
        addJWTHadoopCookie(original, token);
      }

      if (removeOriginalUrlCookie) {
        removeOriginalUrlCookie(response);
      }

      LOGGER.aboutToRedirectToOriginal(Log4jAuditor.maskTokenFromURL(original));
      response.setStatus(statusCode);
      response.setHeader("Location", original);
      try {
        response.getOutputStream().close();
      } catch (IOException e) {
        LOGGER.unableToCloseOutputStream(e.getMessage(), Arrays.toString(e.getStackTrace()));
      }
    } catch (TokenServiceException| AliasServiceException e) {
      LOGGER.unableToIssueToken(e);
    }
    URI location = null;
    try {
      location = new URI(original);
    }
    catch(URISyntaxException urise) {
      // todo log return error response
    }



    return Response.seeOther(location).entity("{ \"redirectTo\" : " + original + " }").build();
  }