org.apache.oltu.oauth2.client.request.OAuthClientRequest Java Examples

The following examples show how to use org.apache.oltu.oauth2.client.request.OAuthClientRequest. 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: OAuth.java    From docusign-java-client with MIT License 6 votes vote down vote up
public OAuth(Client client, OAuthFlow flow, String authorizationUrl, String tokenUrl, String scopes) {
	this(client, OAuthClientRequest.tokenLocation(tokenUrl).setScope(scopes), OAuthClientRequest.authorizationLocation(authorizationUrl).setScope(scopes));

	switch (flow) {
	case accessCode:
		tokenRequestBuilder.setGrantType(GrantType.AUTHORIZATION_CODE);
		authenticationRequestBuilder.setResponseType(OAuth.CODE);
		break;
	case implicit:
		tokenRequestBuilder.setGrantType(GrantType.IMPLICIT);
		authenticationRequestBuilder.setResponseType(OAuth.TOKEN);
		break;
	case password:
		tokenRequestBuilder.setGrantType(GrantType.PASSWORD);
		break;
	case application:
		tokenRequestBuilder.setGrantType(GrantType.CLIENT_CREDENTIALS);
		break;
	default:
		break;
	}
}
 
Example #2
Source File: RetryingOAuth.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
/**
@param tokenUrl The token URL to be used for this OAuth2 flow.
    Applicable to the following OAuth2 flows: "password", "clientCredentials" and "authorizationCode".
    The value must be an absolute URL.
@param clientId The OAuth2 client ID for the "clientCredentials" flow.
@param clientSecret The OAuth2 client secret for the "clientCredentials" flow.
*/
public RetryingOAuth(
        String tokenUrl,
        String clientId,
        OAuthFlow flow,
        String clientSecret,
        Map<String, String> parameters
) {
    this(OAuthClientRequest.tokenLocation(tokenUrl)
            .setClientId(clientId)
            .setClientSecret(clientSecret));
    setFlow(flow);
    if (parameters != null) {
        for (String paramName : parameters.keySet()) {
            tokenRequestBuilder.setParameter(paramName, parameters.get(paramName));
        }
    }
}
 
Example #3
Source File: OidcHelper.java    From entando-components with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Builds an request url that the browser needs to be redirected to for OAuth.
 * @param req
 * @return
 * @throws OAuthSystemException
 */
public String buildOauthRequestString(HttpServletRequest req) throws OAuthSystemException {
    OAuthClientRequest.AuthenticationRequestBuilder requestBuilder = OAuthClientRequest
            .authorizationLocation(this.oidcConfiguration.getOidcAuthLocation())
            .setClientId(this.oidcConfiguration.getOidcClientId())
            .setParameter("response_mode", "form_post")
            .setParameter("response_type", "code");
    if (identityProviderExtractor.hasIdentityProvider(req)) {
        requestBuilder = requestBuilder.setParameter("kc_idp_hint", identityProviderExtractor.getIdentityProviderName(req))
                .setRedirectURI(identityProviderExtractor.getRedirectUri(req));
    } else if (StringUtils.isNotEmpty(this.oidcConfiguration.getDefaultIdentityProvider())) {
        requestBuilder = requestBuilder.setParameter("kc_idp_hint", this.oidcConfiguration.getDefaultIdentityProvider())
                .setRedirectURI(identityProviderExtractor.getRedirectUri(req));
    } else {
        requestBuilder = requestBuilder.setRedirectURI(buildRedirectURI(req));
    }
    OAuthClientRequest oauthRequest = requestBuilder
            .buildQueryMessage();
    return oauthRequest.getLocationUri();
}
 
Example #4
Source File: RetryingOAuth.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
/**
@param tokenUrl The token URL to be used for this OAuth2 flow.
    Applicable to the following OAuth2 flows: "password", "clientCredentials" and "authorizationCode".
    The value must be an absolute URL.
@param clientId The OAuth2 client ID for the "clientCredentials" flow.
@param clientSecret The OAuth2 client secret for the "clientCredentials" flow.
*/
public RetryingOAuth(
        String tokenUrl,
        String clientId,
        OAuthFlow flow,
        String clientSecret,
        Map<String, String> parameters
) {
    this(OAuthClientRequest.tokenLocation(tokenUrl)
            .setClientId(clientId)
            .setClientSecret(clientSecret));
    setFlow(flow);
    if (parameters != null) {
        for (String paramName : parameters.keySet()) {
            tokenRequestBuilder.setParameter(paramName, parameters.get(paramName));
        }
    }
}
 
Example #5
Source File: OpenIDConnectAuthenticator.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
private OAuthClientRequest getAccessRequest(String tokenEndPoint, String clientId, String code, String clientSecret,
                                            String callbackurl)
        throws AuthenticationFailedException {

    OAuthClientRequest accessRequest = null;
    try {
        accessRequest = OAuthClientRequest.tokenLocation(tokenEndPoint)
                .setGrantType(GrantType.AUTHORIZATION_CODE).setClientId(clientId)
                .setClientSecret(clientSecret).setRedirectURI(callbackurl).setCode(code)
                .buildBodyMessage();

    } catch (OAuthSystemException e) {
        if (log.isDebugEnabled()) {
            log.debug("Exception while building request for request access token", e);
        }
        throw new AuthenticationFailedException(e.getMessage(), e);
    }
    return accessRequest;
}
 
Example #6
Source File: Oauth2ImplicitClient.java    From components with Apache License 2.0 6 votes vote down vote up
private String getAuthorizationCode() {
    try {
        AuthenticationRequestBuilder builder = OAuthClientRequest.authorizationLocation(authorizationLocation.toString())
                .setClientId(clientID).setRedirectURI(callbackURL.toString());
        if (responseType != null) {
            builder.setResponseType(responseType);
        }
        OAuthClientRequest request = builder.buildQueryMessage();

        // FIXME : remove those Syso when the studio activate the INFO log by default
        System.out.println(messages.getMessage("msg.info.showAuthorizUrl"));
        System.out.println(request.getLocationUri());
        // --
        logger.info(messages.getMessage("msg.info.showAuthorizUrl"));
        logger.info(request.getLocationUri());
        OAuth2ImplicitGrantServer service = new OAuth2ImplicitGrantServer(callbackURL.getHost(), callbackURL.getPort(),
                10 * 60 * 1000);
        service.run();// <--- this method wait for 10 minutes maximum to grab authorization code
        String code = service.getAuthorizationCode();
        service.stop();
        return code;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example #7
Source File: LibFilter.java    From liferay-oidc-plugin with Apache License 2.0 6 votes vote down vote up
protected void redirectToLogin(HttpServletRequest request, HttpServletResponse response, String clientId) throws
        IOException {
    OIDCConfiguration oidcConfiguration = liferay.getOIDCConfiguration(liferay.getCompanyId(request));

    try {
        OAuthClientRequest oAuthRequest = OAuthClientRequest
                .authorizationLocation(oidcConfiguration.authorizationLocation())
                .setClientId(clientId)
                .setRedirectURI(getRedirectUri(request))
                .setResponseType("code")
                .setScope(oidcConfiguration.scope())
                .setState(generateStateParam(request))
                .buildQueryMessage();
        liferay.debug("Redirecting to URL: " + oAuthRequest.getLocationUri());
        response.sendRedirect(oAuthRequest.getLocationUri());
    } catch (OAuthSystemException e) {
        throw new IOException("While redirecting to OP for SSO login", e);
    }
}
 
Example #8
Source File: OAuthServiceImpl.java    From BIMserver with GNU Affero General Public License v3.0 6 votes vote down vote up
public SOAuthServer registerRemoteApplication(String redirectUrl, String name, String description) throws UserException {
	try {
		OAuthClientRequest request = OAuthClientRegistrationRequest.location(getBimServer().getServerSettingsCache().getServerSettings().getSiteAddress() + "/oauth/register/", 
				OAuthRegistration.Type.PUSH).setName(name).setUrl(redirectUrl).setDescription(description)
				.setRedirectURL(redirectUrl).buildJSONMessage();
		OAuthRegistrationClient oauthclient = new OAuthRegistrationClient(new org.bimserver.webservices.impl.URLConnectionClient());
		OAuthClientRegistrationResponse response = oauthclient.clientInfo(request);
		
		SOAuthServer server = new SOAuthServer();
		server.setClientId(response.getClientId());
		server.setClientSecret(response.getClientSecret());
		return server;
	} catch (Exception e) {
		throw new UserException(e);
	}
}
 
Example #9
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 #10
Source File: OAuth.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
public OAuth(Client client, OAuthFlow flow, String authorizationUrl, String tokenUrl, String scopes) {
    this(client, OAuthClientRequest.tokenLocation(tokenUrl).setScope(scopes));

    switch(flow) {
    case accessCode:
    case implicit:
        tokenRequestBuilder.setGrantType(GrantType.AUTHORIZATION_CODE);
        break;
    case password:
        tokenRequestBuilder.setGrantType(GrantType.PASSWORD);
        break;
    case application:
        tokenRequestBuilder.setGrantType(GrantType.CLIENT_CREDENTIALS);
        break;
    default:
        break;
    }
    authenticationRequestBuilder = OAuthClientRequest.authorizationLocation(authorizationUrl);
}
 
Example #11
Source File: OidcHelperTest.java    From entando-components with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Test
public void testBuildOauthTokenRequest() throws Exception{
    HttpServletRequest request = mock(HttpServletRequest.class);
    when(request.getRequestURL()).thenReturn(new StringBuffer("http://some.domain.com:9090/somecontext/page?some_param=value"));
    this.oidcConfiguration.setOidcClientId("test.client.id");
    this.oidcConfiguration.setOidcTokenLocation("http://keycloak.some.domain.com:7070/token/path");
    this.oidcConfiguration.setOidcAuthLocation("http://keycloak.some.domain.com:7070/auth/path");
    OAuthClientRequest clientRequest = oidcUserExtractor.buildOauthRequest(request,"some_code");
    assertThat(clientRequest.getLocationUri(),is(equalTo("http://keycloak.some.domain.com:7070/token/path")));
    assertThat(clientRequest.getBody(),is(equalTo("code=some_code&grant_type=authorization_code&redirect_uri=http%3A%2F%2Fsome.domain.com%3A9090%2Fsomecontext%2Fpage%3Fsome_param%3Dvalue&client_id=test.client.id&response_mode=form_post")));
}
 
Example #12
Source File: OidcHelper.java    From entando-components with GNU Lesser General Public License v3.0 5 votes vote down vote up
public OAuthClientRequest buildOauthRequest(HttpServletRequest request, String code) throws OAuthSystemException {
    return OAuthClientRequest
            .tokenLocation(this.oidcConfiguration.getOidcTokenLocation())
            //.tokenProvider(OAuthProviderType.MICROSOFT)
            .setGrantType(GrantType.AUTHORIZATION_CODE)
            .setClientId(this.oidcConfiguration.getOidcClientId())
            //.setClientSecret("your-facebook-application-client-secret")
            .setRedirectURI(buildRedirectURI(request))
            .setCode(code)
            .setParameter("response_mode", "form_post")
            .buildBodyMessage();

}
 
Example #13
Source File: OidcAuthenticator.java    From entando-components with GNU Lesser General Public License v3.0 5 votes vote down vote up
private void fetchAndProcessToken(HttpServletRequest req, String code) throws
        OAuthSystemException, OAuthProblemException, ApsSystemException {
    OAuthClient oAuthClient = new OAuthClient(new URLConnectionClient());
    OAuthClientRequest oAuthClientRequest = this.oidcHelper.buildOauthRequest(req, code);
    OAuthJSONAccessTokenResponse oAuthResponse = oAuthClient.resource(oAuthClientRequest, OAuth.HttpMethod.POST, OAuthJSONAccessTokenResponse.class);

    _logger.info("----------------------TOKEN------------------- ");
    String accessToken = oAuthResponse.getAccessToken();
    _logger.info("accessToken -> " + accessToken);
    UserDetails cdpUser = this.oidcHelper.getOidcUser(oAuthResponse.getAccessToken());
    HttpSession session = req.getSession();
    session.setAttribute(SystemConstants.SESSIONPARAM_CURRENT_USER, cdpUser);
}
 
Example #14
Source File: FacebookAuthenticator.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
private OAuthClientRequest buidTokenRequest(
        String tokenEndPoint, String clientId, String clientSecret, String callbackurl, String code)
        throws ApplicationAuthenticatorException {
    OAuthClientRequest tokenRequest = null;
    try {
        tokenRequest =
                OAuthClientRequest.tokenLocation(tokenEndPoint).setClientId(clientId)
                        .setClientSecret(clientSecret)
                        .setRedirectURI(callbackurl).setCode(code)
                        .buildQueryMessage();
    } catch (OAuthSystemException e) {
        throw new ApplicationAuthenticatorException("Exception while building access token request.", e);
    }
    return tokenRequest;
}
 
Example #15
Source File: OAuthOkHttpClient.java    From eve-esi with Apache License 2.0 5 votes vote down vote up
@Override
public <T extends OAuthClientResponse> T execute(OAuthClientRequest request, Map<String, String> headers,
        String requestMethod, Class<T> responseClass) throws OAuthSystemException, OAuthProblemException {

    MediaType mediaType = MediaType.parse("application/json");
    Request.Builder requestBuilder = new Request.Builder().url(request.getLocationUri());

    if (headers != null) {
        for (Entry<String, String> entry : headers.entrySet()) {
            if (entry.getKey().equalsIgnoreCase("Content-Type")) {
                mediaType = MediaType.parse(entry.getValue());
            } else {
                requestBuilder.addHeader(entry.getKey(), entry.getValue());
            }
        }
    }

    RequestBody body = request.getBody() != null ? RequestBody.create(mediaType, request.getBody()) : null;
    requestBuilder.method(requestMethod, body);

    try {
        Response response = client.newCall(requestBuilder.build()).execute();
        return OAuthClientResponseFactory.createCustomResponse(response.body().string(), response.body()
                .contentType().toString(), response.code(), responseClass);
    } catch (IOException e) {
        throw new OAuthSystemException(e);
    }
}
 
Example #16
Source File: RetryingOAuth.java    From eve-esi with Apache License 2.0 5 votes vote down vote up
/**
 * @param tokenUrl
 *            The token URL to be used for this OAuth2 flow. Applicable to
 *            the following OAuth2 flows: "password", "clientCredentials"
 *            and "authorizationCode". The value must be an absolute URL.
 * @param clientId
 *            The OAuth2 client ID for the "clientCredentials" flow.
 * @param clientSecret
 *            The OAuth2 client secret for the "clientCredentials" flow.
 */
public RetryingOAuth(String tokenUrl, String clientId, OAuthFlow flow, String clientSecret,
        Map<String, String> parameters) {
    this(OAuthClientRequest.tokenLocation(tokenUrl).setClientId(clientId).setClientSecret(clientSecret));
    setFlow(flow);
    if (parameters != null) {
        for (String paramName : parameters.keySet()) {
            tokenRequestBuilder.setParameter(paramName, parameters.get(paramName));
        }
    }
}
 
Example #17
Source File: OAuth.java    From rapidoid with Apache License 2.0 5 votes vote down vote up
public static String getLoginURL(Req req, OAuthProvider provider, String oauthDomain) {

		if (OAUTH.isEmpty()) {
			Log.warn("OAuth is not configured!");
		}

		String name = provider.getName().toLowerCase();

		Config providerConfig = OAUTH.sub(name);
		Value<String> clientId = providerConfig.entry("clientId").str();
		Value<String> clientSecret = providerConfig.entry("clientSecret").str();

		String callbackPath = Msc.specialUri(name + "OauthCallback");

		boolean popup = req.param("popup", null) != null;

		String redirectUrl = U.notEmpty(oauthDomain) ? oauthDomain + callbackPath : HttpUtils.constructUrl(req,
			callbackPath);

		String statePrefix = popup ? "P" : "N";
		String state = statePrefix + STATE_CHECK.generateState(clientSecret, req.sessionId());

		try {
			OAuthClientRequest request = OAuthClientRequest.authorizationLocation(provider.getAuthEndpoint())
				.setClientId(clientId.str().get()).setRedirectURI(redirectUrl).setScope(provider.getEmailScope())
				.setState(state).setResponseType("code").buildQueryMessage();
			return request.getLocationUri();
		} catch (OAuthSystemException e) {
			throw U.rte(e);
		}
	}
 
Example #18
Source File: OAuthClient.java    From orion.server with Eclipse Public License 1.0 5 votes vote down vote up
public <T extends OAuthAccessTokenResponse> T accessToken(
    OAuthClientRequest request, String requestMethod, Class<T> responseClass)
    throws OAuthSystemException, OAuthProblemException {

    Map<String, String> headers = new HashMap<String, String>();
    headers.put(OAuth.HeaderType.CONTENT_TYPE, OAuth.ContentType.URL_ENCODED);

    return httpClient.execute(request, headers, requestMethod, responseClass);
}
 
Example #19
Source File: OAuthClient.java    From orion.server with Eclipse Public License 1.0 5 votes vote down vote up
public <T extends OAuthAccessTokenResponse> T accessToken(
    OAuthClientRequest request,
    Class<T> responseClass)
    throws OAuthSystemException, OAuthProblemException {

    return accessToken(request, OAuth.HttpMethod.POST, responseClass);
}
 
Example #20
Source File: OAuthOkHttpClient.java    From android with MIT License 5 votes vote down vote up
public <T extends OAuthClientResponse> T execute(OAuthClientRequest request, Map<String, String> headers,
        String requestMethod, Class<T> responseClass)
                throws OAuthSystemException, OAuthProblemException {

    MediaType mediaType = MediaType.parse("application/json");
    Request.Builder requestBuilder = new Request.Builder().url(request.getLocationUri());

    if(headers != null) {
        for (Entry<String, String> entry : headers.entrySet()) {
            if (entry.getKey().equalsIgnoreCase("Content-Type")) {
                mediaType = MediaType.parse(entry.getValue());
            } else {
                requestBuilder.addHeader(entry.getKey(), entry.getValue());
            }
        }
    }

    RequestBody body = request.getBody() != null ? RequestBody.create(mediaType, request.getBody()) : null;
    requestBuilder.method(requestMethod, body);

    try {
        Response response = client.newCall(requestBuilder.build()).execute();
        return OAuthClientResponseFactory.createCustomResponse(
                response.body().string(), 
                response.body().contentType().toString(),
                response.code(),
                response.headers().toMultimap(),
                responseClass);
    } catch (IOException e) {
        throw new OAuthSystemException(e);
    }
}
 
Example #21
Source File: OAuthOkHttpClient.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
public <T extends OAuthClientResponse> T execute(OAuthClientRequest request, Map<String, String> headers,
        String requestMethod, Class<T> responseClass)
                throws OAuthSystemException, OAuthProblemException {

    MediaType mediaType = MediaType.parse("application/json");
    Request.Builder requestBuilder = new Request.Builder().url(request.getLocationUri());

    if(headers != null) {
        for (Entry<String, String> entry : headers.entrySet()) {
            if (entry.getKey().equalsIgnoreCase("Content-Type")) {
                mediaType = MediaType.parse(entry.getValue());
            } else {
                requestBuilder.addHeader(entry.getKey(), entry.getValue());
            }
        }
    }

    RequestBody body = request.getBody() != null ? RequestBody.create(mediaType, request.getBody()) : null;
    requestBuilder.method(requestMethod, body);

    try {
        Response response = client.newCall(requestBuilder.build()).execute();
        return OAuthClientResponseFactory.createCustomResponse(
                response.body().string(), 
                response.body().contentType().toString(),
                response.code(),
                responseClass);
    } catch (IOException e) {
        throw new OAuthSystemException(e);
    }
}
 
Example #22
Source File: OAuthOkHttpClient.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
@Override
public <T extends OAuthClientResponse> T execute(OAuthClientRequest request, Map<String, String> headers,
                                                 String requestMethod, Class<T> responseClass)
        throws OAuthSystemException, OAuthProblemException {

    MediaType mediaType = MediaType.parse("application/json");
    Request.Builder requestBuilder = new Request.Builder().url(request.getLocationUri());

    if(headers != null) {
        for (Entry<String, String> entry : headers.entrySet()) {
            if (entry.getKey().equalsIgnoreCase("Content-Type")) {
                mediaType = MediaType.parse(entry.getValue());
            } else {
                requestBuilder.addHeader(entry.getKey(), entry.getValue());
            }
        }
    }

    RequestBody body = request.getBody() != null ? RequestBody.create(mediaType, request.getBody()) : null;
    requestBuilder.method(requestMethod, body);

    try {
        Response response = client.newCall(requestBuilder.build()).execute();
        return OAuthClientResponseFactory.createCustomResponse(
                response.body().string(),
                response.body().contentType().toString(),
                response.code(),
                responseClass);
    } catch (IOException e) {
        throw new OAuthSystemException(e);
    }
}
 
Example #23
Source File: OAuthOkHttpClient.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
public <T extends OAuthClientResponse> T execute(OAuthClientRequest request, Map<String, String> headers,
        String requestMethod, Class<T> responseClass)
                throws OAuthSystemException, OAuthProblemException {

    MediaType mediaType = MediaType.parse("application/json");
    Request.Builder requestBuilder = new Request.Builder().url(request.getLocationUri());

    if(headers != null) {
        for (Entry<String, String> entry : headers.entrySet()) {
            if (entry.getKey().equalsIgnoreCase("Content-Type")) {
                mediaType = MediaType.parse(entry.getValue());
            } else {
                requestBuilder.addHeader(entry.getKey(), entry.getValue());
            }
        }
    }

    RequestBody body = request.getBody() != null ? RequestBody.create(mediaType, request.getBody()) : null;
    requestBuilder.method(requestMethod, body);

    try {
        Response response = client.newCall(requestBuilder.build()).execute();
        return OAuthClientResponseFactory.createCustomResponse(
                response.body().string(), 
                response.body().contentType().toString(),
                response.code(),
                responseClass);
    } catch (IOException e) {
        throw new OAuthSystemException(e);
    }
}
 
Example #24
Source File: OAuthServiceImpl.java    From BIMserver with GNU Affero General Public License v3.0 5 votes vote down vote up
public String generateForwardUrl(String registrationEndpoint, String authorizeUrl, String returnUrl) throws ServerException, UserException {
	try (DatabaseSession session = getBimServer().getDatabase().createSession(OperationType.READ_ONLY)) {
		OAuthServer oAuthServer = session.querySingle(StorePackage.eINSTANCE.getOAuthServer_RegistrationEndpoint(), registrationEndpoint);
		if (oAuthServer == null) {
			throw new UserException("Application not registered");
		}
		OAuthClientRequest request2 = OAuthClientRequest.authorizationLocation(authorizeUrl).setParameter("auth_type", "service").setClientId(oAuthServer.getClientId()).setRedirectURI(returnUrl).setResponseType(ResponseType.CODE.toString()).setState("state").buildQueryMessage();
		return request2.getLocationUri();
	} catch (Exception e) {
		return handleException(e);
	}
}
 
Example #25
Source File: OAuthOkHttpClient.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
@Override
public <T extends OAuthClientResponse> T execute(OAuthClientRequest request, Map<String, String> headers,
                                                 String requestMethod, Class<T> responseClass)
        throws OAuthSystemException, OAuthProblemException {

    MediaType mediaType = MediaType.parse("application/json");
    Request.Builder requestBuilder = new Request.Builder().url(request.getLocationUri());

    if(headers != null) {
        for (Entry<String, String> entry : headers.entrySet()) {
            if (entry.getKey().equalsIgnoreCase("Content-Type")) {
                mediaType = MediaType.parse(entry.getValue());
            } else {
                requestBuilder.addHeader(entry.getKey(), entry.getValue());
            }
        }
    }

    RequestBody body = request.getBody() != null ? RequestBody.create(mediaType, request.getBody()) : null;
    requestBuilder.method(requestMethod, body);

    try {
        Response response = client.newCall(requestBuilder.build()).execute();
        return OAuthClientResponseFactory.createCustomResponse(
                response.body().string(),
                response.body().contentType().toString(),
                response.code(),
                responseClass);
    } catch (IOException e) {
        throw new OAuthSystemException(e);
    }
}
 
Example #26
Source File: OAuthOkHttpClient.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
public <T extends OAuthClientResponse> T execute(OAuthClientRequest request, Map<String, String> headers,
        String requestMethod, Class<T> responseClass)
                throws OAuthSystemException, OAuthProblemException {

    MediaType mediaType = MediaType.parse("application/json");
    Request.Builder requestBuilder = new Request.Builder().url(request.getLocationUri());

    if(headers != null) {
        for (Entry<String, String> entry : headers.entrySet()) {
            if (entry.getKey().equalsIgnoreCase("Content-Type")) {
                mediaType = MediaType.parse(entry.getValue());
            } else {
                requestBuilder.addHeader(entry.getKey(), entry.getValue());
            }
        }
    }

    RequestBody body = request.getBody() != null ? RequestBody.create(mediaType, request.getBody()) : null;
    requestBuilder.method(requestMethod, body);

    try {
        Response response = client.newCall(requestBuilder.build()).execute();
        return OAuthClientResponseFactory.createCustomResponse(
                response.body().string(), 
                response.body().contentType().toString(),
                response.code(),
                responseClass);
    } catch (IOException e) {
        throw new OAuthSystemException(e);
    }
}
 
Example #27
Source File: OAuthTokenHandler.java    From rapidoid with Apache License 2.0 4 votes vote down vote up
@Override
public Object execute(Req req) throws Exception {
	String code = req.param("code");
	String state = req.param("state");

	Log.debug("Received OAuth code", "code", code, "state", state);

	if (code != null && !U.isEmpty(state)) {

		String id = clientId.str().get();
		String secret = clientSecret.str().get();

		char statePrefix = state.charAt(0);
		U.must(statePrefix == 'P' || statePrefix == 'N', "Invalid OAuth state prefix!");
		state = state.substring(1);

		U.must(stateCheck.isValidState(state, secret, req.sessionId()), "Invalid OAuth state!");

		boolean popup = statePrefix == 'P';
		Log.debug("OAuth validated", "popup", popup);

		String domain = oauthDomain.getOrNull();
		String redirectUrl = U.notEmpty(domain) ? domain + callbackPath : HttpUtils.constructUrl(req, callbackPath);

		TokenRequestBuilder reqBuilder = OAuthClientRequest.tokenLocation(provider.getTokenEndpoint())
			.setGrantType(GrantType.AUTHORIZATION_CODE)
			.setClientId(id)
			.setClientSecret(secret)
			.setRedirectURI(redirectUrl)
			.setCode(code);

		OAuthClientRequest request = paramsInBody() ? reqBuilder.buildBodyMessage() : reqBuilder.buildBodyMessage();

		OAuthClient oAuthClient = new OAuthClient(new URLConnectionClient());

		String accessToken = token(request, oAuthClient);

		String profileUrl = Msc.fillIn(provider.getProfileEndpoint(), "token", accessToken);

		OAuthClientRequest bearerClientRequest = new OAuthBearerClientRequest(profileUrl).setAccessToken(
			accessToken).buildQueryMessage();

		OAuthResourceResponse res = oAuthClient.resource(bearerClientRequest,
			org.apache.oltu.oauth2.common.OAuth.HttpMethod.GET, OAuthResourceResponse.class);

		U.must(res.getResponseCode() == 200, "OAuth response error!");

		Map<String, Object> auth = JSON.parseMap(res.getBody());

		String email = (String) U.or(auth.get("email"), auth.get("emailAddress"));
		String firstName = (String) U.or(auth.get("firstName"), U.or(auth.get("first_name"), auth.get("given_name")));
		String lastName = (String) U.or(auth.get("lastName"), U.or(auth.get("last_name"), auth.get("family_name")));
		String name = U.or((String) auth.get("name"), firstName + " " + lastName);

		String username = email;
		Set<String> roles = customization.rolesProvider().getRolesForUser(req, username);

		UserInfo user = new UserInfo(username, roles);
		user.name = name;
		user.email = email;
		user.oauthProvider = provider.getName();
		user.oauthId = String.valueOf(auth.get("id"));

		req.response().authorize(user);

		return req.response().redirect("/");

	} else {
		String error = req.param("error");
		if (error != null) {
			Log.warn("OAuth error", "error", error);
			throw U.rte("OAuth error!");
		}
	}

	throw U.rte("Invalid OAuth request!");
}
 
Example #28
Source File: OAuthServiceImpl.java    From BIMserver with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
public Long registerApplication(String registrationEndpoint, String apiUrl, String redirectUrl) throws UserException, ServerException {
       try {
       	try (DatabaseSession session = getBimServer().getDatabase().createSession(OperationType.POSSIBLY_WRITE)) {
       		OAuthServer oAuthServer = session.querySingle(StorePackage.eINSTANCE.getOAuthServer_RegistrationEndpoint(), registrationEndpoint);
       		
       		if (oAuthServer != null) {
       			return oAuthServer.getOid();
       		}
       		
       		ServerSettings serverSettings = getBimServer().getServerSettingsCache().getServerSettings();
       		
			OAuthClientRequest request = OAuthClientRegistrationRequest
			    .location(registrationEndpoint, OAuthRegistration.Type.PUSH)
			    .setName(serverSettings.getName())
			    .setUrl(redirectUrl)
			    .setDescription(serverSettings.getDescription())
			    .setIcon(serverSettings.getIcon())
			    .setRedirectURL(redirectUrl)
			    .buildJSONMessage();
			OAuthRegistrationClient oauthclient = new OAuthRegistrationClient(new URLConnectionClient());
			OAuthClientRegistrationResponse response = oauthclient.clientInfo(request);

			oAuthServer = session.create(OAuthServer.class);
			oAuthServer.setApiUrl(apiUrl);
			oAuthServer.setClientId(response.getClientId());
			oAuthServer.setClientSecret(response.getClientSecret());
			
			oAuthServer.setIssuedAt(new Date(Long.parseLong(response.getIssuedAt())));
			
			GregorianCalendar expiresAt = new GregorianCalendar();
			expiresAt.setTimeInMillis(new GregorianCalendar().getTimeInMillis() + response.getExpiresIn());
			
			oAuthServer.setExpiresAt(expiresAt.getTime());
			oAuthServer.setRegistrationEndpoint(registrationEndpoint);
			oAuthServer.setClientDescription(serverSettings.getDescription());
			oAuthServer.setClientName(serverSettings.getName());
			
			if (serverSettings.getIcon() != null) {
				byte[] icon = NetUtils.getContentAsBytes(new URL(serverSettings.getIcon()), 500);
				oAuthServer.setClientIcon(icon);
			}
			
			oAuthServer.setIncoming(false);
			oAuthServer.setRedirectUrl(redirectUrl);
			
			session.commit();
			return oAuthServer.getOid();
		}
	} catch (Exception e) {
		return handleException(e);
	}
}
 
Example #29
Source File: OAuthClient.java    From orion.server with Eclipse Public License 1.0 4 votes vote down vote up
public  <T extends OAuthClientResponse> T resource(OAuthClientRequest request, String requestMethod,Class<T> responseClass) throws OAuthSystemException, OAuthProblemException{
    return httpClient.execute(request, null, requestMethod, responseClass);
}
 
Example #30
Source File: OAuthClient.java    From orion.server with Eclipse Public License 1.0 4 votes vote down vote up
public OAuthJSONAccessTokenResponse accessToken(
    OAuthClientRequest request, String requestMethod)
    throws OAuthSystemException, OAuthProblemException {
    return accessToken(request, requestMethod, OAuthJSONAccessTokenResponse.class);
}