Extract a Fernet token from an X-Authorization header.

@param request a REST request which may or may not include an X-Authorization header.
@return a Fernet token or null if no X-Authorization header is provided.
188895
public Token getXAuthorizationToken(final ContainerRequest request) {
        final String xAuthorizationString = request.getHeaderString("X-Authorization");
        if (xAuthorizationString != null && !"".equals(xAuthorizationString)) {
            return Token.fromString(xAuthorizationString.trim());
        }
        return null;
    }
1298078
private String parseLayerId(HttpServletRequest request) {
		StringTokenizer tokenizer = new StringTokenizer(request.getRequestURI(), "/");
		String token = "";
		while (tokenizer.hasMoreTokens()) {
			token = tokenizer.nextToken();
		}
		return token;
	}
1365043
@Nullable
  public static String getHttpUserAgentStringFromRequest (@Nonnull final HttpServletRequest aHttpRequest)
  {
    // Use non-standard headers first
    String sUserAgent = aHttpRequest.getHeader (CHttpHeader.UA);
    if (sUserAgent == null)
    {
      sUserAgent = aHttpRequest.getHeader (CHttpHeader.X_DEVICE_USER_AGENT);
      if (sUserAgent == null)
        sUserAgent = aHttpRequest.getHeader (CHttpHeader.USER_AGENT);
    }
    return sUserAgent;
  }
1138330
protected OAuthToken getOAuthTokenFromRequest(final HttpServletRequest request) {
        val token = getOAuthConfigurationContext().getTicketRegistry().getTicket(getOAuthParameter(request), OAuthToken.class);
        if (token == null || token.isExpired()) {
            LOGGER.error("OAuth token indicated by parameter [{}] has expired or not found: [{}]", getOAuthParameter(request), token);
            if (token != null) {
                getOAuthConfigurationContext().getTicketRegistry().deleteTicket(token.getId());
            }
            return null;
        }
        return token;
    }
458532
private AuthToken parseAuthorizationToken(String authHeader) {
        try {
            String tokenEncoded = authHeader.substring(11);
            return AuthTokenUtil.consumeToken(tokenEncoded);
        } catch (IllegalArgumentException e) {
            // TODO log this error
            return null;
        }
    }
697373
private function fetchToken(ServerRequestInterface $request): string
    {
        /* Check for token in header. */
        $header = $request->getHeaderLine($this->options["header"]);

        if (false === empty($header)) {
            if (preg_match($this->options["regexp"], $header, $matches)) {
                $this->log(LogLevel::DEBUG, "Using token from request header");
                return $matches[1];
            }
        }

        /* Token not found in header try a cookie. */
        $cookieParams = $request->getCookieParams();

        if (isset($cookieParams[$this->options["cookie"]])) {
            $this->log(LogLevel::DEBUG, "Using token from cookie");
            return $cookieParams[$this->options["cookie"]];
        };

        /* If everything fails log and throw. */
        $this->log(LogLevel::WARNING, "Token not found");
        throw new RuntimeException("Token not found.");
    }
999068
public CreateTimeOnetimeTokenResult createTimeOnetimeToken(CreateTimeOnetimeTokenRequest request) {

		ObjectNode body = JsonNodeFactory.instance.objectNode()
				.put("scriptName", request.getScriptName());

		HttpPost post = createHttpPost(
				Gs2Constant.ENDPOINT_HOST + "/onetime/time/token",
				credential,
				ENDPOINT,
				CreateTimeOnetimeTokenRequest.Constant.MODULE,
				CreateTimeOnetimeTokenRequest.Constant.FUNCTION,
				body.toString());
        if(request.getRequestId() != null) {
            post.setHeader("X-GS2-REQUEST-ID", request.getRequestId());
        }


		return doRequest(post, CreateTimeOnetimeTokenResult.class);

	}
802450
protected function getRequestToken(Request $request)
    {
        /** @var TokenExtractorInterface $tokenExtractor */
        foreach ($this->tokenExtractors as $tokenExtractor) {
            if (($token = $tokenExtractor->extract($request))) {
                return $token;
            }
        }
    }
986529
private String getAuthHeader(HttpServletRequest request, String authType)
      throws HttpAuthenticationException {
    String authHeader = request.getHeader(HttpAuthUtils.AUTHORIZATION);
    // Each http request must have an Authorization header
    if (authHeader == null || authHeader.isEmpty()) {
      throw new HttpAuthenticationException("Authorization header received " +
          "from the client is empty.");
    }

    String authHeaderBase64String;
    int beginIndex;
    if (isKerberosAuthMode(authType)) {
      beginIndex = (HttpAuthUtils.NEGOTIATE + " ").length();
    }
    else {
      beginIndex = (HttpAuthUtils.BASIC + " ").length();
    }
    authHeaderBase64String = authHeader.substring(beginIndex);
    // Authorization header must have a payload
    if (authHeaderBase64String == null || authHeaderBase64String.isEmpty()) {
      throw new HttpAuthenticationException("Authorization header received " +
          "from the client does not contain any data.");
    }
    return authHeaderBase64String;
  }
1210001
protected boolean requestRequiresAuthentication(final HttpServletRequest request, final HttpServletResponse response) {
        val accessTokenRequest = isAccessTokenRequest(request, response);
        if (!accessTokenRequest) {
            val extractor = extractAccessTokenGrantRequest(request);
            if (extractor.isPresent()) {
                val ext = extractor.get();
                return ext.requestMustBeAuthenticated();
            }
        } else {
            val extractor = extractAccessTokenGrantRequest(request);
            if (extractor.isPresent()) {
                val ext = extractor.get();
                return ext.getResponseType() != OAuth20ResponseTypes.DEVICE_CODE;
            }
        }
        return false;
    }
771295
protected SecurityToken getSecurityTokenFromRequest(final HttpServletRequest request) {
        val cookieValue = wsFederationRequestConfigurationContext.getTicketGrantingTicketCookieGenerator().retrieveCookieValue(request);
        if (StringUtils.isNotBlank(cookieValue)) {
            val tgt = wsFederationRequestConfigurationContext.getTicketRegistry().getTicket(cookieValue, TicketGrantingTicket.class);
            if (tgt != null) {
                val sts = tgt.getDescendantTickets().stream()
                    .filter(t -> t.startsWith(SecurityTokenTicket.PREFIX))
                    .findFirst()
                    .orElse(null);
                if (StringUtils.isNotBlank(sts)) {
                    val stt = wsFederationRequestConfigurationContext.getTicketRegistry().getTicket(sts, SecurityTokenTicket.class);
                    if (stt == null || stt.isExpired()) {
                        LOGGER.warn("Security token ticket [{}] is not found or has expired", sts);
                        return null;
                    }
                    if (stt.getSecurityToken().isExpired()) {
                        LOGGER.warn("Security token linked to ticket [{}] has expired", sts);
                        return null;
                    }
                    return stt.getSecurityToken();
                }
            }
        }
        return null;
    }
252396
def get_token_from_header(request):
    
    token = None

    if 'Authorization' in request.headers:
        split_header = request.headers.get('Authorization').split()
        if len(split_header) == 2 and split_header[0] == 'Bearer':
            token = split_header[1]
    else:
        token = request.access_token

    return token
659214
def get_jwt(self, request):
        
        try:
            authorization = request.authorization
        except ValueError:
            return None
        if authorization is None:
            return None
        authtype, token = authorization
        if authtype.lower() != self.auth_header_prefix.lower():
            return None
        return token
624777
private function getTokenFromRequestBody(ServerRequestInterface $request): ?string
    {
        try {
            $parameters = RequestBodyParser::parseFormUrlEncoded($request);

            return $this->getAccessTokenFromParameters($parameters);
        } catch (\Exception $e) {
            return null;
        }
    }
1256930
public String DoPut(Request request) throws Exception {

        Unirest.setHttpClient(getHttpClient());

        if (request.client == null) {
            throw new Exception("client must NOT null");
        }

        String buf = "";
        if (request.client.GetEnableCrypto()) {
            buf = request.crypto.signAndEncrypt(request.body.toString().getBytes());
        } else {
            buf = request.body.toString();
        }

        Map<String, String> mapHeader = Utils.JsonToMap(request.header);
        mapHeader.put(Headers.APIKeyHeader, request.client.GetApiKey());

        if (request.client.GetRouteTag() != "") {
            mapHeader.put(Headers.FabioRouteTagHeader, request.client.GetRouteTag());
            mapHeader.put(Headers.RouteTagHeader, request.client.GetRouteTag());
        }

        HttpResponse<String> res = Unirest.put(request.url).headers(mapHeader).body(buf).asString();

        String respData = res.getBody();

        System.out.println("Got remote cipher response: " + respData);

        String oriData = "";
        if (request.client.GetEnableCrypto()) {
            oriData = request.crypto.decryptAndVerify(respData.getBytes());
        } else {
            oriData = respData;
        }
        return oriData;

    }
712274
function getTokenFromHeader(request) {
  if (!request.headers || !request.headers.has('authorization')) {
    throw new UnauthorizedError('No authorization header present');
  }

  const parts = request.headers.get('authorization').split(" ");

  if (parts.length === 2) {
    const scheme = parts[0];
    const credentials = parts[1];

    if (/^Bearer$/i.test(scheme)) {
      return credentials;
    } else {
      throw new UnauthorizedError('Bad Authorization header format. Format is "Authorization: Bearer token"');
    }
  } else {
    throw new UnauthorizedError('Bad Authorization header format. Format is "Authorization: Bearer token"');
  }
}
1232719
def _get_token(request):
    
    token = request.headers.get('Authorization')
    if not token:
        message = 'Token not in Authorization header'
        logging.warning(message)
        raise HTTPError(401, message)
    return token