org.apache.oltu.oauth2.common.utils.OAuthUtils Java Examples

The following examples show how to use org.apache.oltu.oauth2.common.utils.OAuthUtils. 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: QueryParameterApplier.java    From orion.server with Eclipse Public License 1.0 6 votes vote down vote up
public OAuthMessage applyOAuthParameters(OAuthMessage message, Map<String, Object> params) {

        String messageUrl = message.getLocationUri();
        if (messageUrl != null) {
            boolean containsQuestionMark = messageUrl.contains("?");
            StringBuffer url = new StringBuffer(messageUrl);
 
            StringBuffer query = new StringBuffer(OAuthUtils.format(params.entrySet(), "UTF-8"));
  
            if (!OAuthUtils.isEmpty(query.toString())) {
                if (containsQuestionMark) {
                    url.append("&").append(query);
                } else {
                    url.append("?").append(query);
                }
            }   
            message.setLocationUri(url.toString());
        }
        return message;
    }
 
Example #2
Source File: URLConnectionClient.java    From BIMserver with GNU Affero General Public License v3.0 6 votes vote down vote up
private void setRequestBody(OAuthClientRequest request, String requestMethod, HttpURLConnection httpURLConnection)
        throws IOException {
    String requestBody = request.getBody();
    if (OAuthUtils.isEmpty(requestBody)) {
        return;
    }

    if (OAuth.HttpMethod.POST.equals(requestMethod) || OAuth.HttpMethod.PUT.equals(requestMethod)) {
        httpURLConnection.setDoOutput(true);
        OutputStream ost = httpURLConnection.getOutputStream();
        PrintWriter pw = new PrintWriter(ost);
        pw.print(requestBody);
        pw.flush();
        pw.close();
    }
}
 
Example #3
Source File: CarbonOAuthAuthzRequest.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
protected OAuthValidator<HttpServletRequest> initValidator() throws OAuthProblemException, OAuthSystemException {

        String responseTypeValue = getParam(OAuth.OAUTH_RESPONSE_TYPE);
        if (OAuthUtils.isEmpty(responseTypeValue)) {
            throw OAuthUtils.handleOAuthProblemException("Missing response_type parameter value");
        }

        Class<? extends OAuthValidator<HttpServletRequest>> clazz = OAuthServerConfiguration
                .getInstance().getSupportedResponseTypeValidators().get(responseTypeValue);

        if (clazz == null) {
            if (log.isDebugEnabled()) {
                //Do not change this log format as these logs use by external applications
                log.debug("Unsupported Response Type : " + responseTypeValue +
                        " for client id : " + getClientId());
            }
            throw OAuthUtils.handleOAuthProblemException("Invalid response_type parameter value");
        }

        return OAuthUtils.instantiateClass(clazz);
    }
 
Example #4
Source File: CarbonOAuthTokenRequest.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
/**
 * Initialize a grant type validator
 *
 * @return an instance of OAuthValidator
 * @throws OAuthProblemException
 * @throws OAuthSystemException
 */
@Override
protected OAuthValidator<HttpServletRequest> initValidator() throws OAuthProblemException, OAuthSystemException {

    String requestTypeValue = getParam(OAuth.OAUTH_GRANT_TYPE);
    if (OAuthUtils.isEmpty(requestTypeValue)) {
        throw OAuthUtils.handleOAuthProblemException("Missing grant_type parameter value");
    }

    Class<? extends OAuthValidator<HttpServletRequest>> clazz = OAuthServerConfiguration
            .getInstance().getSupportedGrantTypeValidators().get(requestTypeValue);

    if (clazz == null) {
        if (log.isDebugEnabled()) {
            //Do not change this log format as these logs use by external applications
            log.debug("Unsupported Grant Type : " + requestTypeValue +
                    " for client id : " + getClientId());
        }
        throw OAuthUtils.handleOAuthProblemException("Invalid grant_type parameter value");
    }

    return OAuthUtils.instantiateClass(clazz);
}
 
Example #5
Source File: AbstractValidator.java    From orion.server with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public void validateClientAuthenticationCredentials(T request) throws OAuthProblemException {
    if (enforceClientAuthentication) {
        Set<String> missingParameters = new HashSet<String>();
        String clientAuthHeader = request.getHeader(OAuth.HeaderType.AUTHORIZATION);
        String[] clientCreds = OAuthUtils.decodeClientAuthenticationHeader(clientAuthHeader);

        // Only fallback to params if the auth header is not correct. Don't allow a mix of auth header vs params
        if (clientCreds == null || OAuthUtils.isEmpty(clientCreds[0]) || OAuthUtils.isEmpty(clientCreds[1])) {

            if (OAuthUtils.isEmpty(request.getParameter(OAuth.OAUTH_CLIENT_ID))) {
                missingParameters.add(OAuth.OAUTH_CLIENT_ID);
            }
            if (OAuthUtils.isEmpty(request.getParameter(OAuth.OAUTH_CLIENT_SECRET))) {
                missingParameters.add(OAuth.OAUTH_CLIENT_SECRET);
            }
        }

        if (!missingParameters.isEmpty()) {
            throw OAuthUtils.handleMissingParameters(missingParameters);
        }
    }
}
 
Example #6
Source File: AbstractValidator.java    From orion.server with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public void validateOptionalParameters(T request) throws OAuthProblemException {
    final Set<String> missingParameters = new HashSet<String>();

    for (Map.Entry<String, String[]> requiredParam : optionalParams.entrySet()) {
        final String paramName = requiredParam.getKey();
        String val = request.getParameter(paramName);
        if (!OAuthUtils.isEmpty(val)) {
            String[] dependentParams = requiredParam.getValue();
            if (!OAuthUtils.hasEmptyValues(dependentParams)) {
                for (String dependentParam : dependentParams) {
                    val = request.getParameter(dependentParam);
                    if (OAuthUtils.isEmpty(val)) {
                        missingParameters.add(dependentParam);
                    }
                }
            }
        }
    }

    if (!missingParameters.isEmpty()) {
        throw OAuthUtils.handleMissingParameters(missingParameters);
    }
}
 
Example #7
Source File: FragmentParametersApplier.java    From orion.server with Eclipse Public License 1.0 6 votes vote down vote up
public OAuthMessage applyOAuthParameters(OAuthMessage message, Map<String, Object> params) throws OAuthSystemException {

        String messageUrl = message.getLocationUri();
        if (messageUrl != null) {
            StringBuilder url = new StringBuilder(messageUrl);

            if (params.containsKey(OAuth.OAUTH_REFRESH_TOKEN)) {
                params.remove(OAuth.OAUTH_REFRESH_TOKEN);
            }

            String fragmentQuery = OAuthUtils.format(params.entrySet(), "UTF-8");

            if (!OAuthUtils.isEmpty(fragmentQuery)) {
                if (params.size() > 0) {
                        url.append("#").append(fragmentQuery);
                }
            }
            message.setLocationUri(url.toString());
        }
        return message;
    }
 
Example #8
Source File: OAuthHelper.java    From orion.server with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Prepared javascript to send to the user to link the oauth consumer to the current user.
 * @param req The request of to the server.
 * @param resp The response from the server.
 * @param oauthConsumer The current authorized oauth consumer.
 * @throws IOException Thrown if there is a problem access the response writer.
 * @throws OAuthException Thrown if the authentication response is not sufficient.
 */
public static void handleReturnAndLinkAccount(HttpServletRequest req, HttpServletResponse resp, OAuthConsumer oauthConsumer) throws IOException, OAuthException {
	if (oauthConsumer != null) {
		String id = oauthConsumer.getIdentifier();
		if (OAuthUtils.isEmpty(id)) {
			throw new OAuthException("Authentication response is not sufficient");
		}

		PrintWriter out = resp.getWriter();
		resp.setHeader("Cache-Control", "no-cache"); //$NON-NLS-1$ //$NON-NLS-2$
		resp.setContentType("text/html; charset=UTF-8");
		out.println("<html><head></head>"); //$NON-NLS-1$
		// TODO: send a message using
		// window.eclipseMessage.postImmediate(otherWindow, message) from
		// /org.eclipse.e4.webide/web/js/message.js
		out.println("<body onload=\"window.opener.handleOAuthResponse('" + id + "');window.close();\">"); //$NON-NLS-1$  //$NON-NLS-2$
		out.println("</body>"); //$NON-NLS-1$
		out.println("</html>"); //$NON-NLS-1$

		out.close();
		return;
	}
}
 
Example #9
Source File: OAuthClientValidator.java    From orion.server with Eclipse Public License 1.0 6 votes vote down vote up
public void validateRequiredParameters(OAuthClientResponse response) throws OAuthProblemException {
    Set<String> missingParameters = new HashSet<String>();

    for (Map.Entry<String, String[]> requiredParam : requiredParams.entrySet()) {
        String paramName = requiredParam.getKey();
        String val = response.getParam(paramName);
        if (OAuthUtils.isEmpty(val)) {
            missingParameters.add(paramName);
        } else {
            String[] dependentParams = requiredParam.getValue();
            if (!OAuthUtils.hasEmptyValues(dependentParams)) {
                for (String dependentParam : dependentParams) {
                    val = response.getParam(dependentParam);
                    if (OAuthUtils.isEmpty(val)) {
                        missingParameters.add(dependentParam);
                    }
                }
            }
        }
    }

    if (!missingParameters.isEmpty()) {
        throw OAuthUtils.handleMissingParameters(missingParameters);
    }
}
 
Example #10
Source File: BodyURLEncodedParametersApplier.java    From orion.server with Eclipse Public License 1.0 5 votes vote down vote up
public OAuthMessage applyOAuthParameters(OAuthMessage message, Map<String, Object> params)
    throws OAuthSystemException {

    String body = OAuthUtils.format(params.entrySet(), "UTF-8");
    message.setBody(body);
    return message;

}
 
Example #11
Source File: OAuthClientValidator.java    From orion.server with Eclipse Public License 1.0 5 votes vote down vote up
public void validateErrorResponse(OAuthClientResponse response) throws OAuthProblemException {
    String error = response.getParam(OAuthError.OAUTH_ERROR);
    if (!OAuthUtils.isEmpty(error)) {
        String errorDesc = response.getParam(OAuthError.OAUTH_ERROR_DESCRIPTION);
        String errorUri = response.getParam(OAuthError.OAUTH_ERROR_URI);
        String state = response.getParam(OAuth.OAUTH_STATE);
        throw OAuthProblemException.error(error).description(errorDesc).uri(errorUri).state(state);
    }
}
 
Example #12
Source File: OAuthAuthzResponse.java    From orion.server with Eclipse Public License 1.0 5 votes vote down vote up
protected OAuthAuthzResponse(HttpServletRequest request, OAuthClientValidator validator) {
    this.request = request;
    Map<String, String[]> params = request.getParameterMap();
    for (Map.Entry<String, String[]> entry : params.entrySet()) {
        String key = entry.getKey();
        String[] values = entry.getValue();
        if (!OAuthUtils.hasEmptyValues(values)) {
            parameters.put(key, values[0]);
        }
    }
    this.validator = validator;
}
 
Example #13
Source File: OAuthProblemException.java    From orion.server with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public String getMessage() {
    StringBuilder b = new StringBuilder();
    if (!OAuthUtils.isEmpty(error)) {
        b.append(error);
    }

    if (!OAuthUtils.isEmpty(description)) {
        b.append(", ").append(description);
    }


    if (!OAuthUtils.isEmpty(uri)) {
        b.append(", ").append(uri);
    }


    if (!OAuthUtils.isEmpty(state)) {
        b.append(", ").append(state);
    }

    if (!OAuthUtils.isEmpty(scope)) {
        b.append(", ").append(scope);
    }

    return b.toString();
}
 
Example #14
Source File: AbstractValidator.java    From orion.server with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void validateContentType(T request) throws OAuthProblemException {
    String contentType = request.getContentType();
    final String expectedContentType = OAuth.ContentType.URL_ENCODED;
    if (!OAuthUtils.hasContentType(contentType, expectedContentType)) {
        throw OAuthUtils.handleBadContentTypeException(expectedContentType);
    }
}
 
Example #15
Source File: AbstractValidator.java    From orion.server with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void validateRequiredParameters(T request) throws OAuthProblemException {
    final Set<String> missingParameters = new HashSet<String>();
    for (String requiredParam : requiredParams) {
        String val = request.getParameter(requiredParam);
        if (OAuthUtils.isEmpty(val)) {
            missingParameters.add(requiredParam);
        }
    }
    if (!missingParameters.isEmpty()) {
        throw OAuthUtils.handleMissingParameters(missingParameters);
    }
}
 
Example #16
Source File: AbstractValidator.java    From orion.server with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void validateNotAllowedParameters(T request) throws OAuthProblemException {
    List<String> notAllowedParameters = new ArrayList<String>();
    for (String requiredParam : notAllowedParams) {
        String val = request.getParameter(requiredParam);
        if (!OAuthUtils.isEmpty(val)) {
            notAllowedParameters.add(requiredParam);
        }
    }
    if (!notAllowedParameters.isEmpty()) {
        throw OAuthUtils.handleNotAllowedParametersOAuthException(notAllowedParameters);
    }
}
 
Example #17
Source File: OAuthClientResponseFactory.java    From orion.server with Eclipse Public License 1.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public static <T extends OAuthClientResponse> T createCustomResponse(String body, String contentType,
                                                                        int responseCode,
                                                                        Class<T> clazz)
       throws OAuthSystemException, OAuthProblemException {

       OAuthClientResponse resp = (OAuthClientResponse)OAuthUtils
           .instantiateClassWithParameters(clazz, null, null);

       resp.init(body, contentType, responseCode);

       return (T)resp;
   }
 
Example #18
Source File: ClientHeaderParametersApplier.java    From orion.server with Eclipse Public License 1.0 5 votes vote down vote up
public OAuthMessage applyOAuthParameters(OAuthMessage message, Map<String, Object> params)
    throws OAuthSystemException {

    String header = OAuthUtils.encodeAuthorizationBearerHeader(params);
    message.addHeader(OAuth.HeaderType.AUTHORIZATION, header);
    return message;

}
 
Example #19
Source File: OAuthClientValidator.java    From orion.server with Eclipse Public License 1.0 5 votes vote down vote up
public void validateNotAllowedParameters(OAuthClientResponse response) throws OAuthProblemException {
    List<String> notAllowedParameters = new ArrayList<String>();
    for (String requiredParam : notAllowedParams) {
        String val = response.getParam(requiredParam);
        if (!OAuthUtils.isEmpty(val)) {
            notAllowedParameters.add(requiredParam);
        }
    }
    if (!notAllowedParameters.isEmpty()) {
        throw OAuthUtils.handleNotAllowedParametersOAuthException(notAllowedParameters);
    }
}
 
Example #20
Source File: OAuthHelper.java    From orion.server with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Method to try and authenticate an oauth consumer.
 * @param req The request of to the server.
 * @param resp The response from the server.
 * @param oauthConsumer The current authorized oauth consumer.
 * @throws OAuthException Thrown if there is a problem authenticating the user.
 * @throws IOException Throw if there is a problem sending the redirect.
 */
public static void handleLogin(HttpServletRequest req, HttpServletResponse resp, OAuthConsumer oauthConsumer) throws OAuthException, IOException {
	if (oauthConsumer == null || OAuthUtils.isEmpty(oauthConsumer.getIdentifier())) {
		throw new OAuthException("There is no Orion account associated with this Id. Please register or contact your system administrator for assistance.");
	}
	String redirect = oauthConsumer.getRedirect();
	UserInfo userInfo = getUser(oauthConsumer);
	if (userInfo == null) {
		if (!FormAuthHelper.canAddUsers()) {
			throw new OAuthException("There is no Orion account associated with this Id. Please register or contact your system administrator for assistance.");
		}
		String url = "/mixloginstatic/LoginWindow.html";
		url += "?oauth=create&email=" + oauthConsumer.getEmail();
		url += "&username=" + oauthConsumer.getUsername();
		url += "&identifier=" + oauthConsumer.getIdentifier();
		if (redirect != null)
			url += "&redirect=" + redirect;
		resp.sendRedirect(url);
		return;
	}

	String login = userInfo.getUniqueId();
	req.getSession().setAttribute("user", login); //$NON-NLS-1$
	Logger logger = LoggerFactory.getLogger("org.eclipse.orion.server.login"); //$NON-NLS-1$
	if (logger.isInfoEnabled()) {
		logger.info("Login success: " + login + " oauth " + oauthConsumer.getIdentifier()); //$NON-NLS-1$ 
	}

	try {
		// try to store the login timestamp in the user profile
		userInfo.setProperty(UserConstants.LAST_LOGIN_TIMESTAMP, new Long(System.currentTimeMillis()).toString());
		OrionConfiguration.getMetaStore().updateUser(userInfo);
	} catch (CoreException e) {
		// just log that the login timestamp was not stored
		LogHelper.log(e);
	}

	if (redirect != null) {
		resp.sendRedirect(redirect);
		return;
	} else {
		resp.sendRedirect("/index.html");
	}

	return;
}
 
Example #21
Source File: WWWAuthHeaderParametersApplier.java    From orion.server with Eclipse Public License 1.0 4 votes vote down vote up
public OAuthMessage applyOAuthParameters(OAuthMessage message, Map<String, Object> params)
    throws OAuthSystemException {
    String header = OAuthUtils.encodeOAuthHeader(params);
    message.addHeader(OAuth.HeaderType.WWW_AUTHENTICATE, header);
    return message;
}
 
Example #22
Source File: AbstractValidator.java    From orion.server with Eclipse Public License 1.0 4 votes vote down vote up
@Override
public void validateMethod(T request) throws OAuthProblemException {
    if (!request.getMethod().equals(OAuth.HttpMethod.POST)) {
        throw OAuthUtils.handleOAuthProblemException("Method not set to POST.");
    }
}
 
Example #23
Source File: GitHubTokenResponse.java    From orion.server with Eclipse Public License 1.0 4 votes vote down vote up
protected void setBody(String body) {
    this.body = body;
    parameters = OAuthUtils.decodeForm(body);
}