Search in sources :

Example 1 with OkapiToken

use of org.folio.okapi.common.OkapiToken in project okapi by folio-org.

the class ProxyService method tenantHeader.

/**
 * Extract the tenant. Fix header to standard. Normalizes the Authorization
 * header to X-Okapi-Token, checks that both are not present. Checks if we
 * have X-Okapi-Tenant header, and if not, extracts from the X-Okapi-Token.
 * The tenant will be needed to find the pipeline to route to, and in most
 * cases the first thing that happens is that the auth module will verify the
 * tenant against what it has in the token, so even if a client puts up a bad
 * tenant, we should be safe.
 *
 * @param pc
 * @return null in case of errors, with the response already set in ctx. If
 * all went well, returns the tenantId for further processing.
 */
private String tenantHeader(ProxyContext pc) {
    RoutingContext ctx = pc.getCtx();
    String auth = ctx.request().getHeader(XOkapiHeaders.AUTHORIZATION);
    String tok = ctx.request().getHeader(XOkapiHeaders.TOKEN);
    if (auth != null) {
        // Grab anything after 'Bearer' and whitespace
        Pattern pattern = Pattern.compile("Bearer\\s+(.+)");
        Matcher matcher = pattern.matcher(auth);
        if (matcher.find() && matcher.groupCount() > 0) {
            auth = matcher.group(1);
        }
    }
    if (auth != null && tok != null && !auth.equals(tok)) {
        pc.responseText(400, "Different tokens in Authentication and X-Okapi-Token. " + "Use only one of them");
        return null;
    }
    if (tok == null && auth != null) {
        ctx.request().headers().add(XOkapiHeaders.TOKEN, auth);
        ctx.request().headers().remove(XOkapiHeaders.AUTHORIZATION);
        pc.debug("Okapi: Moved Authorization header to X-Okapi-Token");
    }
    String tenantId = ctx.request().getHeader(XOkapiHeaders.TENANT);
    if (tenantId == null) {
        try {
            tenantId = new OkapiToken(ctx).getTenant();
            if (tenantId != null && !tenantId.isEmpty()) {
                ctx.request().headers().add(XOkapiHeaders.TENANT, tenantId);
                pc.debug("Okapi: Recovered tenant from token: '" + tenantId + "'");
            }
        } catch (IllegalArgumentException e) {
            pc.responseText(400, "Invalid Token: " + e.getMessage());
            return null;
        }
    }
    if (tenantId == null) {
        logger.debug("No tenantId, defaulting to " + XOkapiHeaders.SUPERTENANT_ID);
        // without setting it in pc
        return XOkapiHeaders.SUPERTENANT_ID;
    }
    pc.setTenant(tenantId);
    return tenantId;
}
Also used : Pattern(java.util.regex.Pattern) RoutingContext(io.vertx.ext.web.RoutingContext) Matcher(java.util.regex.Matcher) OkapiToken(org.folio.okapi.common.OkapiToken)

Aggregations

RoutingContext (io.vertx.ext.web.RoutingContext)1 Matcher (java.util.regex.Matcher)1 Pattern (java.util.regex.Pattern)1 OkapiToken (org.folio.okapi.common.OkapiToken)1