org.eclipse.jetty.util.Fields Java Examples

The following examples show how to use org.eclipse.jetty.util.Fields. 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: OAuthConnector.java    From smarthome with Eclipse Public License 2.0 6 votes vote down vote up
private void setAuthentication(@Nullable String clientId, @Nullable String clientSecret, Request request,
        Fields fields, boolean supportsBasicAuth) {
    logger.debug("Setting authentication for clientId {}. Using basic auth {}", clientId, supportsBasicAuth);
    if (supportsBasicAuth && clientSecret != null) {
        String authString = clientId + ":" + clientSecret;
        request.header(HttpHeader.AUTHORIZATION,
                "Basic " + Base64.getEncoder().encodeToString(authString.getBytes(StandardCharsets.UTF_8)));
    } else {
        if (clientId != null) {
            fields.add(CLIENT_ID, clientId);
        }
        if (clientSecret != null) {
            fields.add(CLIENT_SECRET, clientSecret);
        }
    }
}
 
Example #2
Source File: OAuthConnector.java    From openhab-core with Eclipse Public License 2.0 6 votes vote down vote up
private void setAuthentication(@Nullable String clientId, @Nullable String clientSecret, Request request,
        Fields fields, boolean supportsBasicAuth) {
    logger.debug("Setting authentication for clientId {}. Using basic auth {}", clientId, supportsBasicAuth);
    if (supportsBasicAuth && clientSecret != null) {
        String authString = clientId + ":" + clientSecret;
        request.header(HttpHeader.AUTHORIZATION,
                "Basic " + Base64.getEncoder().encodeToString(authString.getBytes(StandardCharsets.UTF_8)));
    } else {
        if (clientId != null) {
            fields.add(CLIENT_ID, clientId);
        }
        if (clientSecret != null) {
            fields.add(CLIENT_SECRET, clientSecret);
        }
    }
}
 
Example #3
Source File: RestClient.java    From app-runner with MIT License 5 votes vote down vote up
public ContentResponse updateApp(String gitUrl, String appName) throws Exception {
    Fields fields = new Fields();
    fields.add("gitUrl", gitUrl);
    return client.newRequest(appRunnerUrl + "/api/v1/apps/" + appName)
        .method("PUT")
        .content(new FormContentProvider(fields)).send();
}
 
Example #4
Source File: OAuthConnector.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
private Fields initFields(String... parameters) {
    Fields fields = new Fields();

    for (int i = 0; i < parameters.length; i += 2) {
        if (i + 1 < parameters.length && parameters[i] != null && parameters[i + 1] != null) {
            logger.debug("Oauth request parameter {}, value {}", parameters[i], parameters[i + 1]);
            fields.add(parameters[i], parameters[i + 1]);
        }
    }
    return fields;
}
 
Example #5
Source File: HttpOperatorFactory.java    From digdag with Apache License 2.0 5 votes vote down vote up
private static Fields formFields(ObjectNode content)
{
    Fields fields = new Fields();
    content.fields().forEachRemaining(f -> {
        if (f.getValue().isContainerNode()) {
            throw new ConfigException("Invalid form content field value: " + f.getValue().toString());
        }
        fields.add(f.getKey(), f.getValue().asText());
    });
    return fields;
}
 
Example #6
Source File: OAuthConnector.java    From openhab-core with Eclipse Public License 2.0 5 votes vote down vote up
private Fields initFields(String... parameters) {
    Fields fields = new Fields();

    for (int i = 0; i < parameters.length; i += 2) {
        if (i + 1 < parameters.length && parameters[i] != null && parameters[i + 1] != null) {
            logger.debug("Oauth request parameter {}, value {}", parameters[i], parameters[i + 1]);
            fields.add(parameters[i], parameters[i + 1]);
        }
    }
    return fields;
}
 
Example #7
Source File: RestClient.java    From app-runner with MIT License 5 votes vote down vote up
public ContentResponse createApp(String gitUrl, String appName) throws Exception {
    Fields fields = new Fields();
    fields.add("gitUrl", gitUrl);
    if (appName != null) {
        fields.add("appName", appName);
    }
    return client.POST(appRunnerUrl + "/api/v1/apps")
        .content(new FormContentProvider(fields)).send();
}
 
Example #8
Source File: OAuthConnector.java    From openhab-core with Eclipse Public License 2.0 4 votes vote down vote up
/**
 * Client Credentials Grant
 *
 * @see <a href="https://tools.ietf.org/html/rfc6749#section-4.4">rfc6749 section-4.4</a>
 *
 * @param tokenUrl URL of the oauth provider that accepts access token requests.
 * @param clientId The client identifier issued to the client during the registration process
 * @param clientSecret The client secret. The client MAY omit the parameter if the client secret is an empty string.
 * @param scope Access Token Scope.
 * @param supportsBasicAuth Determines whether the oauth client should use HTTP Authorization header to the oauth
 *            provider
 * @return Access Token
 * @throws IOException IO/ network exceptions
 * @throws OAuthException Other exceptions
 * @throws OAuthErrorException Error codes given by authorization provider, as in RFC 6749 section 5.2 Error
 *             Response
 */
public AccessTokenResponse grantTypeClientCredentials(String tokenUrl, String clientId,
        @Nullable String clientSecret, @Nullable String scope, boolean supportsBasicAuth)
        throws OAuthResponseException, OAuthException, IOException {
    HttpClient httpClient = null;
    try {
        httpClient = createHttpClient(tokenUrl);
        Request request = getMethod(httpClient, tokenUrl);
        Fields fields = initFields(GRANT_TYPE, CLIENT_CREDENTIALS, SCOPE, scope);

        setAuthentication(clientId, clientSecret, request, fields, supportsBasicAuth);
        return doRequest(CLIENT_CREDENTIALS, httpClient, request, fields);
    } finally {
        shutdownQuietly(httpClient);
    }
}
 
Example #9
Source File: OAuthConnector.java    From openhab-core with Eclipse Public License 2.0 4 votes vote down vote up
/**
 * Authorization Code Grant - part (E)
 *
 * @see <a href="https://tools.ietf.org/html/rfc6749#section-4.1.3">rfc6749 section-4.1.3</a>
 *
 * @param tokenUrl URL of the oauth provider that accepts access token requests.
 * @param authorizationCode to be used to trade with the oauth provider for access token
 * @param clientId The client identifier issued to the client during the registration process
 * @param clientSecret The client secret. The client MAY omit the parameter if the client secret is an empty string.
 * @param redirectUrl is the http request parameter which tells the oauth provider the URI to redirect the
 *            user-agent. This may/ may not be present as per agreement with the oauth provider.
 * @param supportsBasicAuth Determines whether the oauth client should use HTTP Authorization header to the oauth
 *            provider
 * @return Access Token
 * @throws IOException IO/ network exceptions
 * @throws OAuthException Other exceptions
 * @throws OAuthErrorException Error codes given by authorization provider, as in RFC 6749 section 5.2 Error
 *             Response
 */
public AccessTokenResponse grantTypeAuthorizationCode(String tokenUrl, String authorizationCode, String clientId,
        @Nullable String clientSecret, @Nullable String redirectUrl, boolean supportsBasicAuth)
        throws OAuthResponseException, OAuthException, IOException {
    HttpClient httpClient = null;
    try {
        httpClient = createHttpClient(tokenUrl);
        Request request = getMethod(httpClient, tokenUrl);
        Fields fields = initFields(GRANT_TYPE, AUTHORIZATION_CODE, CODE, authorizationCode, REDIRECT_URI,
                redirectUrl);

        setAuthentication(clientId, clientSecret, request, fields, supportsBasicAuth);
        return doRequest(AUTHORIZATION_CODE, httpClient, request, fields);
    } finally {
        shutdownQuietly(httpClient);
    }
}
 
Example #10
Source File: OAuthConnector.java    From openhab-core with Eclipse Public License 2.0 4 votes vote down vote up
private AccessTokenResponse doRequest(final String grantType, HttpClient httpClient, final Request request,
        Fields fields) throws OAuthResponseException, OAuthException, IOException {
    int statusCode = 0;
    String content = "";
    try {
        final FormContentProvider entity = new FormContentProvider(fields);
        final ContentResponse response = AccessController
                .doPrivileged((PrivilegedExceptionAction<ContentResponse>) () -> {
                    Request requestWithContent = request.content(entity);
                    return requestWithContent.send();
                });

        statusCode = response.getStatus();
        content = response.getContentAsString();

        if (statusCode == HttpStatus.OK_200) {
            AccessTokenResponse jsonResponse = gson.fromJson(content, AccessTokenResponse.class);
            jsonResponse.setCreatedOn(LocalDateTime.now()); // this is not supplied by the response
            logger.debug("grant type {} to URL {} success", grantType, request.getURI());
            return jsonResponse;
        } else if (statusCode == HttpStatus.BAD_REQUEST_400) {
            OAuthResponseException errorResponse = gson.fromJson(content, OAuthResponseException.class);
            logger.error("grant type {} to URL {} failed with error code {}, description {}", grantType,
                    request.getURI(), errorResponse.getError(), errorResponse.getErrorDescription());

            throw errorResponse;
        } else {
            logger.error("grant type {} to URL {} failed with HTTP response code {}", grantType, request.getURI(),
                    statusCode);
            throw new OAuthException("Bad http response, http code " + statusCode);
        }
    } catch (PrivilegedActionException pae) {
        Exception underlyingException = pae.getException();
        if (underlyingException instanceof InterruptedException || underlyingException instanceof TimeoutException
                || underlyingException instanceof ExecutionException) {
            throw new IOException("Exception in oauth communication, grant type " + grantType, underlyingException);
        }
        // Dont know what exception it is, wrap it up and throw it out
        throw new OAuthException("Exception in oauth communication, grant type " + grantType, underlyingException);
    } catch (JsonSyntaxException e) {
        throw new OAuthException(String.format(
                "Unable to deserialize json into AccessTokenResponse/ OAuthResponseException. httpCode: %i json: %s",
                statusCode, content), e);
    }
}
 
Example #11
Source File: OAuthConnector.java    From openhab-core with Eclipse Public License 2.0 4 votes vote down vote up
/**
 * Refresh Token
 *
 * @see <a href="https://tools.ietf.org/html/rfc6749#section-6">rfc6749 section-6</a>
 *
 * @param tokenUrl URL of the oauth provider that accepts access token requests.
 * @param refreshToken The refresh token, which can be used to obtain new access tokens using authorization grant
 * @param clientId The client identifier issued to the client during the registration process
 * @param clientSecret The client secret. The client MAY omit the parameter if the client secret is an empty string.
 * @param scope Access Token Scope.
 * @param supportsBasicAuth Determines whether the oauth client should use HTTP Authorization header to the oauth
 *            provider.
 * @return Access Token
 * @throws IOException IO/ network exceptions
 * @throws OAuthException Other exceptions
 * @throws OAuthErrorException Error codes given by authorization provider, as in RFC 6749 section 5.2 Error
 *             Response
 */
public AccessTokenResponse grantTypeRefreshToken(String tokenUrl, String refreshToken, @Nullable String clientId,
        @Nullable String clientSecret, @Nullable String scope, boolean supportsBasicAuth)
        throws OAuthResponseException, OAuthException, IOException {
    HttpClient httpClient = null;
    try {
        httpClient = createHttpClient(tokenUrl);
        Request request = getMethod(httpClient, tokenUrl);
        Fields fields = initFields(GRANT_TYPE, REFRESH_TOKEN, REFRESH_TOKEN, refreshToken, SCOPE, scope);

        setAuthentication(clientId, clientSecret, request, fields, supportsBasicAuth);
        return doRequest(REFRESH_TOKEN, httpClient, request, fields);
    } finally {
        shutdownQuietly(httpClient);
    }
}
 
Example #12
Source File: OAuthConnector.java    From smarthome with Eclipse Public License 2.0 4 votes vote down vote up
/**
 * Resource Owner Password Credentials Grant
 *
 * @see <a href="https://tools.ietf.org/html/rfc6749#section-4.3">rfc6749 section-4.3</a>
 *
 * @param tokenUrl URL of the oauth provider that accepts access token requests.
 * @param username The resource owner username.
 * @param password The resource owner password.
 * @param clientId The client identifier issued to the client during the registration process
 * @param clientSecret The client secret. The client MAY omit the parameter if the client secret is an empty string.
 * @param scope Access Token Scope.
 * @param supportsBasicAuth Determines whether the oauth client should use HTTP Authorization header to the oauth
 *            provider.
 * @return Access Token
 * @throws IOException IO/ network exceptions
 * @throws OAuthException Other exceptions
 * @throws OAuthErrorException Error codes given by authorization provider, as in RFC 6749 section 5.2 Error
 *             Response
 */
public AccessTokenResponse grantTypePassword(String tokenUrl, String username, String password,
        @Nullable String clientId, @Nullable String clientSecret, @Nullable String scope, boolean supportsBasicAuth)
        throws OAuthResponseException, OAuthException, IOException {

    HttpClient httpClient = null;
    try {
        httpClient = createHttpClient(tokenUrl);
        Request request = getMethod(httpClient, tokenUrl);
        Fields fields = initFields(GRANT_TYPE, PASSWORD, USERNAME, username, PASSWORD, password, SCOPE, scope);

        setAuthentication(clientId, clientSecret, request, fields, supportsBasicAuth);
        return doRequest(PASSWORD, httpClient, request, fields);
    } finally {
        shutdownQuietly(httpClient);
    }
}
 
Example #13
Source File: OAuthConnector.java    From smarthome with Eclipse Public License 2.0 4 votes vote down vote up
/**
 * Refresh Token
 *
 * @see <a href="https://tools.ietf.org/html/rfc6749#section-6">rfc6749 section-6</a>
 *
 * @param tokenUrl URL of the oauth provider that accepts access token requests.
 * @param refreshToken The refresh token, which can be used to obtain new access tokens using authorization grant
 * @param clientId The client identifier issued to the client during the registration process
 * @param clientSecret The client secret. The client MAY omit the parameter if the client secret is an empty string.
 * @param scope Access Token Scope.
 * @param supportsBasicAuth Determines whether the oauth client should use HTTP Authorization header to the oauth
 *            provider.
 * @return Access Token
 * @throws IOException IO/ network exceptions
 * @throws OAuthException Other exceptions
 * @throws OAuthErrorException Error codes given by authorization provider, as in RFC 6749 section 5.2 Error
 *             Response
 */
public AccessTokenResponse grantTypeRefreshToken(String tokenUrl, String refreshToken, @Nullable String clientId,
        @Nullable String clientSecret, @Nullable String scope, boolean supportsBasicAuth)
        throws OAuthResponseException, OAuthException, IOException {

    HttpClient httpClient = null;
    try {
        httpClient = createHttpClient(tokenUrl);
        Request request = getMethod(httpClient, tokenUrl);
        Fields fields = initFields(GRANT_TYPE, REFRESH_TOKEN, REFRESH_TOKEN, refreshToken, SCOPE, scope);

        setAuthentication(clientId, clientSecret, request, fields, supportsBasicAuth);
        return doRequest(REFRESH_TOKEN, httpClient, request, fields);
    } finally {
        shutdownQuietly(httpClient);
    }
}
 
Example #14
Source File: OAuthConnector.java    From smarthome with Eclipse Public License 2.0 4 votes vote down vote up
/**
 * Authorization Code Grant - part (E)
 *
 * @see <a href="https://tools.ietf.org/html/rfc6749#section-4.1.3">rfc6749 section-4.1.3</a>
 *
 * @param tokenUrl URL of the oauth provider that accepts access token requests.
 * @param authorizationCode to be used to trade with the oauth provider for access token
 * @param clientId The client identifier issued to the client during the registration process
 * @param clientSecret The client secret. The client MAY omit the parameter if the client secret is an empty string.
 * @param redirectUrl is the http request parameter which tells the oauth provider the URI to redirect the
 *            user-agent. This may/ may not be present as per agreement with the oauth provider.
 * @param supportsBasicAuth Determines whether the oauth client should use HTTP Authorization header to the oauth
 *            provider
 * @return Access Token
 * @throws IOException IO/ network exceptions
 * @throws OAuthException Other exceptions
 * @throws OAuthErrorException Error codes given by authorization provider, as in RFC 6749 section 5.2 Error
 *             Response
 */
public AccessTokenResponse grantTypeAuthorizationCode(String tokenUrl, String authorizationCode, String clientId,
        @Nullable String clientSecret, String redirectUrl, boolean supportsBasicAuth)
        throws OAuthResponseException, OAuthException, IOException {
    HttpClient httpClient = null;
    try {
        httpClient = createHttpClient(tokenUrl);
        Request request = getMethod(httpClient, tokenUrl);
        Fields fields = initFields(GRANT_TYPE, AUTHORIZATION_CODE, CODE, authorizationCode, REDIRECT_URI,
                redirectUrl);

        setAuthentication(clientId, clientSecret, request, fields, supportsBasicAuth);
        return doRequest(AUTHORIZATION_CODE, httpClient, request, fields);
    } finally {
        shutdownQuietly(httpClient);
    }
}
 
Example #15
Source File: OAuthConnector.java    From smarthome with Eclipse Public License 2.0 4 votes vote down vote up
/**
 * Client Credentials Grant
 *
 * @see <a href="https://tools.ietf.org/html/rfc6749#section-4.4">rfc6749 section-4.4</a>
 *
 * @param tokenUrl URL of the oauth provider that accepts access token requests.
 * @param clientId The client identifier issued to the client during the registration process
 * @param clientSecret The client secret. The client MAY omit the parameter if the client secret is an empty string.
 * @param scope Access Token Scope.
 * @param supportsBasicAuth Determines whether the oauth client should use HTTP Authorization header to the oauth
 *            provider
 * @return Access Token
 * @throws IOException IO/ network exceptions
 * @throws OAuthException Other exceptions
 * @throws OAuthErrorException Error codes given by authorization provider, as in RFC 6749 section 5.2 Error
 *             Response
 */
public AccessTokenResponse grantTypeClientCredentials(String tokenUrl, String clientId,
        @Nullable String clientSecret, @Nullable String scope, boolean supportsBasicAuth)
        throws OAuthResponseException, OAuthException, IOException {

    HttpClient httpClient = null;
    try {
        httpClient = createHttpClient(tokenUrl);
        Request request = getMethod(httpClient, tokenUrl);
        Fields fields = initFields(GRANT_TYPE, CLIENT_CREDENTIALS, SCOPE, scope);

        setAuthentication(clientId, clientSecret, request, fields, supportsBasicAuth);
        return doRequest(CLIENT_CREDENTIALS, httpClient, request, fields);
    } finally {
        shutdownQuietly(httpClient);
    }
}
 
Example #16
Source File: OAuthConnector.java    From openhab-core with Eclipse Public License 2.0 4 votes vote down vote up
/**
 * Resource Owner Password Credentials Grant
 *
 * @see <a href="https://tools.ietf.org/html/rfc6749#section-4.3">rfc6749 section-4.3</a>
 *
 * @param tokenUrl URL of the oauth provider that accepts access token requests.
 * @param username The resource owner username.
 * @param password The resource owner password.
 * @param clientId The client identifier issued to the client during the registration process
 * @param clientSecret The client secret. The client MAY omit the parameter if the client secret is an empty string.
 * @param scope Access Token Scope.
 * @param supportsBasicAuth Determines whether the oauth client should use HTTP Authorization header to the oauth
 *            provider.
 * @return Access Token
 * @throws IOException IO/ network exceptions
 * @throws OAuthException Other exceptions
 * @throws OAuthErrorException Error codes given by authorization provider, as in RFC 6749 section 5.2 Error
 *             Response
 */
public AccessTokenResponse grantTypePassword(String tokenUrl, String username, String password,
        @Nullable String clientId, @Nullable String clientSecret, @Nullable String scope, boolean supportsBasicAuth)
        throws OAuthResponseException, OAuthException, IOException {
    HttpClient httpClient = null;
    try {
        httpClient = createHttpClient(tokenUrl);
        Request request = getMethod(httpClient, tokenUrl);
        Fields fields = initFields(GRANT_TYPE, PASSWORD, USERNAME, username, PASSWORD, password, SCOPE, scope);

        setAuthentication(clientId, clientSecret, request, fields, supportsBasicAuth);
        return doRequest(PASSWORD, httpClient, request, fields);
    } finally {
        shutdownQuietly(httpClient);
    }
}
 
Example #17
Source File: OAuthConnector.java    From smarthome with Eclipse Public License 2.0 4 votes vote down vote up
private AccessTokenResponse doRequest(final String grantType, HttpClient httpClient, final Request request,
        Fields fields) throws OAuthResponseException, OAuthException, IOException {

    int statusCode = 0;
    String content = "";
    try {
        final FormContentProvider entity = new FormContentProvider(fields);
        final ContentResponse response = AccessController
                .doPrivileged((PrivilegedExceptionAction<ContentResponse>) () -> {
                    Request requestWithContent = request.content(entity);
                    return requestWithContent.send();
                });

        statusCode = response.getStatus();
        content = response.getContentAsString();

        if (statusCode == HttpStatus.OK_200) {
            AccessTokenResponse jsonResponse = gson.fromJson(content, AccessTokenResponse.class);
            jsonResponse.setCreatedOn(LocalDateTime.now()); // this is not supplied by the response
            logger.info("grant type {} to URL {} success", grantType, request.getURI());
            return jsonResponse;
        } else if (statusCode == HttpStatus.BAD_REQUEST_400) {
            OAuthResponseException errorResponse = gson.fromJson(content, OAuthResponseException.class);
            logger.error("grant type {} to URL {} failed with error code {}, description {}", grantType,
                    request.getURI(), errorResponse.getError(), errorResponse.getErrorDescription());

            throw errorResponse;
        } else {
            logger.error("grant type {} to URL {} failed with HTTP response code {}", grantType, request.getURI(),
                    statusCode);
            throw new OAuthException("Bad http response, http code " + statusCode);
        }
    } catch (PrivilegedActionException pae) {
        Exception underlyingException = pae.getException();
        if (underlyingException instanceof InterruptedException || underlyingException instanceof TimeoutException
                || underlyingException instanceof ExecutionException) {
            throw new IOException("Exception in oauth communication, grant type " + grantType, underlyingException);
        }
        // Dont know what exception it is, wrap it up and throw it out
        throw new OAuthException("Exception in oauth communication, grant type " + grantType, underlyingException);
    } catch (JsonSyntaxException e) {
        throw new OAuthException(String.format(
                "Unable to deserialize json into AccessTokenResponse/ OAuthResponseException. httpCode: %i json: %s",
                statusCode, content), e);
    }
}
 
Example #18
Source File: CapturingRequest.java    From cougar with Apache License 2.0 4 votes vote down vote up
@Override
public Fields getParams() {
    return null;  //To change body of implemented methods use File | Settings | File Templates.
}