Java Code Examples for org.elasticsearch.rest.RestRequest#header()

The following examples show how to use org.elasticsearch.rest.RestRequest#header() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: AbstractHTTPJwtAuthenticator.java    From deprecated-security-advanced-modules with Apache License 2.0 6 votes vote down vote up
protected String getJwtTokenString(RestRequest request) {
    String jwtToken = request.header(jwtHeaderName);

    if (jwtUrlParameter != null) {
        if (jwtToken == null || jwtToken.isEmpty()) {
            jwtToken = request.param(jwtUrlParameter);
        } else {
            // just consume to avoid "contains unrecognized parameter"
            request.param(jwtUrlParameter);
        }
    }

    if (jwtToken == null) {
        return null;
    }

    int index;

    if ((index = jwtToken.toLowerCase().indexOf(BEARER)) > -1) { // detect Bearer
        jwtToken = jwtToken.substring(index + BEARER.length());
    }

    return jwtToken;
}
 
Example 2
Source File: AuthService.java    From elasticsearch-auth with Apache License 2.0 6 votes vote down vote up
public String getToken(final RestRequest request) {
    String token = request.param(tokenKey);
    //   cookie
    if (token == null && cookieToken) {
        final String cookieString = request
                .header(HttpHeaders.Names.COOKIE);
        if (cookieString != null) {
            final Set<Cookie> cookies = ServerCookieDecoder.LAX.decode(cookieString);
            for (final Cookie cookie : cookies) {
                if (cookieTokenName.equals(cookie.name())) {
                    token = cookie.value();
                    break;
                }
            }
        }
    }
    return token;
}
 
Example 3
Source File: RestActions.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
public static long parseVersion(RestRequest request) {
    if (request.hasParam("version")) {
        return request.paramAsLong("version", Versions.MATCH_ANY);
    }
    String ifMatch = request.header("If-Match");
    if (ifMatch != null) {
        return Long.parseLong(ifMatch);
    }
    return Versions.MATCH_ANY;
}
 
Example 4
Source File: FileAuthenticationBackend.java    From openshift-elasticsearch-plugin with Apache License 2.0 5 votes vote down vote up
@Override
public AuthCredentials extractCredentials(RestRequest request, ThreadContext context) throws ElasticsearchSecurityException {
    final String authorizationHeader = request.header("Authorization");
    if (authorizationHeader != null) {
        if (authorizationHeader.trim().toLowerCase().startsWith("basic ")) {
            final String decoded = new String(DatatypeConverter.parseBase64Binary(authorizationHeader.split(" ")[1]),
                    StandardCharsets.UTF_8);

            //username:password
            //Assume password is all chars from the last : to the end
            //this is the only way to send service accounts
           
            final int delimiter = decoded.lastIndexOf(':');

            String username = null;
            String password = null;

            if (delimiter > 0) {
                username = decoded.substring(0, delimiter);
                
                if(decoded.length() - 1 != delimiter) {
                    password = decoded.substring(delimiter + 1).trim();
                }
            }
            if (username != null && StringUtils.isNotEmpty(password)) {
                return new AuthCredentials(username, password.getBytes(StandardCharsets.UTF_8)).markComplete();
            }
        }
    }
    return null;
}
 
Example 5
Source File: RequestUtils.java    From openshift-elasticsearch-plugin with Apache License 2.0 5 votes vote down vote up
public String getBearerToken(RestRequest request) {
    String token = request.header(X_FORWARDED_ACCESS_TOKEN);
    if(token == null) {
        if (request.header(AUTHORIZATION_HEADER) != null) {
            final String[] auth = StringUtils.defaultIfEmpty(request.header(AUTHORIZATION_HEADER), "").split(" ");
            if (auth.length >= 2 && "Bearer".equals(auth[0])) {
                token = auth[1];
            }
        }
    }
    return  StringUtils.defaultIfEmpty(token, "");
}
 
Example 6
Source File: RestDataAction.java    From elasticsearch-dataformat with Apache License 2.0 5 votes vote down vote up
public RestChannelConsumer prepareRequest(final RestRequest request,
        final NodeClient client) throws IOException {
    SearchRequest searchRequest = new SearchRequest();
    request.withContentOrSourceParamParserOrNull(
            parser -> RestSearchAction.parseSearchRequest(searchRequest,
                    request, parser,
                    size -> searchRequest.source().size(size)));

    if (request.paramAsInt("size", -1) == -1) {
        searchRequest.source().size(100);
    }

    final String file = request.param("file");

    final long limitBytes;
    String limitParamStr = request.param("limit");
    if (Strings.isNullOrEmpty(limitParamStr)) {
        limitBytes = defaultLimit;
    } else {
        if (limitParamStr.endsWith("%")) {
            limitParamStr = limitParamStr.substring(0,
                    limitParamStr.length() - 1);
        }
        limitBytes = (long) (maxMemory
                * (Float.parseFloat(limitParamStr) / 100F));
    }

    final ContentType contentType = getContentType(request);
    if (contentType == null) {
        final String msg = "Unknown content type:"
                + request.header("Content-Type");
        throw new IllegalArgumentException(msg);
    }
    final DataContent dataContent = contentType.dataContent(client,
            request);

    return channel -> client.search(searchRequest, new SearchResponseListener(
            channel, file, limitBytes, dataContent));
}
 
Example 7
Source File: LoginUserContext.java    From Elasticsearch with Apache License 2.0 4 votes vote down vote up
public LoginUserContext(RestRequest request, ClusterService clusterService) {
    authenticated = false;
    // get username and password
    String auth = request.header("Authorization");
    if (request.param(USERNAME_KEY) != null) {
        loginUsername = request.param(USERNAME_KEY);
        password = request.param(PASSWORD_KEY);
        if (request.hasParam(AUTHENTICATED_KEY)) {
            authenticated = Boolean.parseBoolean(request.param(AUTHENTICATED_KEY));
        }
    } else if ((auth != null) && (auth.length() > BASIC_LENGTH)) {
        auth = auth.substring(BASIC_LENGTH);
        String decodedAuth = new String(Base64.decodeBase64(auth));
        String[] nameAndPass = decodedAuth.split(":");
        if (nameAndPass.length > 0) {
            loginUsername = nameAndPass[0];
        }
        if (nameAndPass.length > 1) {
            password = nameAndPass[1];
        }
    }
    
    if (Strings.isNullOrEmpty(loginUsername)) {
        throw new NoPermissionException(RestStatus.UNAUTHORIZED.getStatus(), "could not parse username from http header or url");
    }
    
    MetaData metaData = clusterService.state().metaData();
    if (UserProperty.getUsernameWithoutTenantFromFullUsername(loginUsername).equalsIgnoreCase(UserProperty.ROOT_NAME)) {
        userProperty = metaData.getUserMetadata().getUserProperties().get(UserProperty.ROOT_NAME);
        UserProperty.Builder userBuilder = new UserProperty.Builder(userProperty);
        userBuilder.changeUsername(UserProperty.ROOT_NAME, UserProperty.getTenantIdFromLoginUserName(loginUsername, metaData.tenantMetadata()));
        userProperty = userBuilder.build();
    } else {
        userProperty = metaData.getUserMetadata().getUserPropertyFromLoginUser(loginUsername, metaData.tenantMetadata());
    }
    if (userProperty == null) {
        throw new NoPermissionException(RestStatus.UNAUTHORIZED.getStatus(), "could not find user " + loginUsername);
    }
    tenantId = userProperty.getTenantId();
    fullUsername = userProperty.getUsernameWithTenant();
    // get sourceAddrs and proxyAddrs
    InetSocketAddress addrs = (InetSocketAddress) request.getRemoteAddress();
    String forwardAddrsList = request.header("X-Forwarded-For");
    if (forwardAddrsList != null && forwardAddrsList.length() > 0) {
        proxyAddrs = addrs.getAddress().getHostAddress();
        sourceAddrs = forwardAddrsList.split(",")[0];
    } else {
        sourceAddrs = addrs.getAddress().getHostAddress();
    }
}
 
Example 8
Source File: RequestUtils.java    From openshift-elasticsearch-plugin with Apache License 2.0 4 votes vote down vote up
/**
 * Modify the request of needed
 * @param request the original request
 * @param context the Openshift context
 * @param channel the channel that is processing the request
 * 
 * @return The modified request
 */
public RestRequest modifyRequest(final RestRequest request, OpenshiftRequestContext context, RestChannel channel) {
    
    final String uri = getUri(request, context);
    final BytesReference content = getContent(request, context);
    if(!getUser(request).equals(context.getUser()) || !uri.equals(request.uri()) || content != request.content()) {
        LOGGER.debug("Modifying header '{}' to be '{}'", proxyUserHeader, context.getUser());
        final Map<String, List<String>> modifiedHeaders = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
        modifiedHeaders.putAll(request.getHeaders());
        modifiedHeaders.put(proxyUserHeader, Arrays.asList(context.getUser()));
        if(request.header("Content-Type") != null && request.header("Content-Type").toLowerCase().endsWith("json")){
            modifiedHeaders.put("Content-Type", Arrays.asList("application/json"));
        }
        RestRequest modified = new RestRequest(request.getXContentRegistry(), uri, modifiedHeaders) {

            @Override
            public Method method() {
                return request.method();
            }

            @Override
            public String uri() {
                return uri;
            }

            @Override
            public boolean hasContent() {
                return content.length() > 0;
            }

            @Override
            public BytesReference content() {
                return content;
            }
            
            @Override
            public SocketAddress getRemoteAddress() {
                return request.getRemoteAddress();
            }

            /**
             * Returns the local address where this request channel is bound to.  The returned
             * {@link SocketAddress} is supposed to be down-cast into more concrete
             * type such as {@link java.net.InetSocketAddress} to retrieve the detailed
             * information.
             */
            @Override
            public SocketAddress getLocalAddress() {
                return request.getRemoteAddress();
            }

            @SuppressWarnings("unused")
            public Channel getChannel() {
                return (Channel) channel;
            }
            
        };
        modified.params().putAll(request.params());
        //HACK - only need to do if we modify the kibana index
        if (uri.contains(defaultKibanaIndex)) {
            modified.params().put("index", context.getKibanaIndex());
        }

        return modified;
    }
    return request;
}