Search in sources :

Example 1 with URLConnectionClient

use of org.apache.oltu.oauth2.client.URLConnectionClient in project incubator-gobblin by apache.

the class SalesforceRestWriter method onConnect.

/**
 * Retrieve access token, if needed, retrieve instance url, and set server host URL
 * {@inheritDoc}
 * @see org.apache.gobblin.writer.http.HttpWriter#onConnect(org.apache.http.HttpHost)
 */
@Override
public void onConnect(URI serverHost) throws IOException {
    if (!StringUtils.isEmpty(accessToken)) {
        // No need to be called if accessToken is active.
        return;
    }
    try {
        getLog().info("Getting Oauth2 access token.");
        OAuthClientRequest request = OAuthClientRequest.tokenLocation(serverHost.toString()).setGrantType(GrantType.PASSWORD).setClientId(clientId).setClientSecret(clientSecret).setUsername(userId).setPassword(password + securityToken).buildQueryMessage();
        OAuthClient client = new OAuthClient(new URLConnectionClient());
        OAuthJSONAccessTokenResponse response = client.accessToken(request, OAuth.HttpMethod.POST);
        accessToken = response.getAccessToken();
        setCurServerHost(new URI(response.getParam("instance_url")));
    } catch (OAuthProblemException e) {
        throw new NonTransientException("Error while authenticating with Oauth2", e);
    } catch (OAuthSystemException e) {
        throw new RuntimeException("Failed getting access token", e);
    } catch (URISyntaxException e) {
        throw new RuntimeException("Failed due to invalid instance url", e);
    }
}
Also used : OAuthProblemException(org.apache.oltu.oauth2.common.exception.OAuthProblemException) NonTransientException(org.apache.gobblin.exception.NonTransientException) URLConnectionClient(org.apache.oltu.oauth2.client.URLConnectionClient) OAuthClient(org.apache.oltu.oauth2.client.OAuthClient) OAuthSystemException(org.apache.oltu.oauth2.common.exception.OAuthSystemException) OAuthJSONAccessTokenResponse(org.apache.oltu.oauth2.client.response.OAuthJSONAccessTokenResponse) URISyntaxException(java.net.URISyntaxException) OAuthClientRequest(org.apache.oltu.oauth2.client.request.OAuthClientRequest) URI(java.net.URI)

Example 2 with URLConnectionClient

use of org.apache.oltu.oauth2.client.URLConnectionClient in project airavata by apache.

the class AuthResponse method authenticate.

public static AuthResponse authenticate(String username, String password) throws AuthenticationException {
    try {
        OAuthClientRequest request = OAuthClientRequest.tokenLocation(hostName + "/oauth2/token").setClientId(clientId).setClientSecret(clientSecret).setGrantType(GrantType.PASSWORD).setRedirectURI("").setUsername(username).setPassword(password).setScope("openid").buildBodyMessage();
        URLConnectionClient ucc = new URLConnectionClient();
        org.apache.oltu.oauth2.client.OAuthClient oAuthClient = new org.apache.oltu.oauth2.client.OAuthClient(ucc);
        OAuthResourceResponse resp = oAuthClient.resource(request, OAuth.HttpMethod.POST, OAuthResourceResponse.class);
        // converting JSON to object
        ObjectMapper mapper = new ObjectMapper();
        AuthResponse authResponse;
        try {
            authResponse = mapper.readValue(resp.getBody(), AuthResponse.class);
        } catch (Exception e) {
            return null;
        }
        String accessToken = authResponse.getAccess_token();
        if (accessToken != null && !accessToken.isEmpty()) {
            request = new OAuthBearerClientRequest(hostName + "/oauth2/userinfo?schema=openid").buildQueryMessage();
            ucc = new URLConnectionClient();
            request.setHeader("Authorization", "Bearer " + accessToken);
            oAuthClient = new org.apache.oltu.oauth2.client.OAuthClient(ucc);
            resp = oAuthClient.resource(request, OAuth.HttpMethod.GET, OAuthResourceResponse.class);
            Map<String, String> profile = mapper.readValue(resp.getBody(), Map.class);
            return authResponse;
        }
    } catch (Exception ex) {
        throw new AuthenticationException(ex.getMessage());
    }
    return null;
}
Also used : OAuthResourceResponse(org.apache.oltu.oauth2.client.response.OAuthResourceResponse) DefaultOAuthClient(org.apache.airavata.service.security.oauth.DefaultOAuthClient) AuthenticationException(org.apache.airavata.model.error.AuthenticationException) AuthenticationException(org.apache.airavata.model.error.AuthenticationException) AiravataSecurityException(org.apache.airavata.security.AiravataSecurityException) OAuthBearerClientRequest(org.apache.oltu.oauth2.client.request.OAuthBearerClientRequest) URLConnectionClient(org.apache.oltu.oauth2.client.URLConnectionClient) OAuthClientRequest(org.apache.oltu.oauth2.client.request.OAuthClientRequest) ObjectMapper(org.codehaus.jackson.map.ObjectMapper)

Example 3 with URLConnectionClient

use of org.apache.oltu.oauth2.client.URLConnectionClient in project structr by structr.

the class StructrOAuthClient method getUserResponse.

protected OAuthResourceResponse getUserResponse(final HttpServletRequest request) {
    if (userResponse != null) {
        return userResponse;
    }
    try {
        String accessToken = getAccessToken(request);
        if (accessToken != null) {
            final String accessTokenParameterKey = this.getAccessTokenParameterKey();
            OAuthClientRequest clientReq = new OAuthBearerClientRequest(getUserResourceUri()) {

                @Override
                public OAuthBearerClientRequest setAccessToken(String accessToken) {
                    this.parameters.put(accessTokenParameterKey, accessToken);
                    return this;
                }
            }.setAccessToken(accessToken).buildQueryMessage();
            // needed for LinkedIn
            clientReq.setHeader("x-li-format", "json");
            logger.info("User info request: {}", clientReq.getLocationUri());
            OAuthClient oAuthClient = new OAuthClient(new URLConnectionClient());
            userResponse = oAuthClient.resource(clientReq, "GET", OAuthResourceResponse.class);
            logger.info("User info response: {}", userResponse);
            return userResponse;
        }
    } catch (Throwable t) {
        logger.error("Could not get user response", t);
    }
    return null;
}
Also used : OAuthBearerClientRequest(org.apache.oltu.oauth2.client.request.OAuthBearerClientRequest) URLConnectionClient(org.apache.oltu.oauth2.client.URLConnectionClient) OAuthResourceResponse(org.apache.oltu.oauth2.client.response.OAuthResourceResponse) OAuthClient(org.apache.oltu.oauth2.client.OAuthClient) OAuthClientRequest(org.apache.oltu.oauth2.client.request.OAuthClientRequest)

Example 4 with URLConnectionClient

use of org.apache.oltu.oauth2.client.URLConnectionClient in project BIMserver by opensourceBIM.

the class OAuthServiceImpl method registerApplication.

@Override
public Long registerApplication(String registrationEndpoint, String apiUrl, String redirectUrl) throws UserException, ServerException {
    try {
        try (DatabaseSession session = getBimServer().getDatabase().createSession()) {
            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);
    }
}
Also used : OAuthRegistrationClient(org.apache.oltu.oauth2.ext.dynamicreg.client.OAuthRegistrationClient) DatabaseSession(org.bimserver.database.DatabaseSession) OAuthClientRegistrationResponse(org.apache.oltu.oauth2.ext.dynamicreg.client.response.OAuthClientRegistrationResponse) ServerSettings(org.bimserver.models.store.ServerSettings) GregorianCalendar(java.util.GregorianCalendar) OAuthClientRequest(org.apache.oltu.oauth2.client.request.OAuthClientRequest) SOAuthServer(org.bimserver.interfaces.objects.SOAuthServer) OAuthServer(org.bimserver.models.store.OAuthServer) Date(java.util.Date) URL(java.net.URL) UserException(org.bimserver.shared.exceptions.UserException) ServerException(org.bimserver.shared.exceptions.ServerException) BimserverDatabaseException(org.bimserver.BimserverDatabaseException)

Example 5 with URLConnectionClient

use of org.apache.oltu.oauth2.client.URLConnectionClient in project components by Talend.

the class Oauth2ImplicitClient method getToken.

public <T extends OAuthAccessTokenResponse> T getToken(Class<T> tokenResponseClass) {
    try {
        TokenRequestBuilder builder = // 
        OAuthClientRequest.tokenLocation(// 
        tokenLocation.toString()).setGrantType(// 
        grantType).setClientId(// 
        clientID).setClientSecret(clientSecret);
        if (GrantType.AUTHORIZATION_CODE == grantType) {
            builder = // 
            builder.setRedirectURI(callbackURL.toString()).setCode(getAuthorizationCode());
        } else if (GrantType.REFRESH_TOKEN == grantType) {
            builder = builder.setRefreshToken(refreshToken);
        }
        OAuthClientRequest request = builder.buildQueryMessage();
        OAuthClient oauthClient = new OAuthClient(new URLConnectionClient());
        return oauthClient.accessToken(request, tokenResponseClass);
    } catch (OAuthSystemException e) {
        throw new RuntimeException(e);
    } catch (OAuthProblemException e) {
        throw new RuntimeException(e);
    }
}
Also used : TokenRequestBuilder(org.apache.oltu.oauth2.client.request.OAuthClientRequest.TokenRequestBuilder) OAuthProblemException(org.apache.oltu.oauth2.common.exception.OAuthProblemException) URLConnectionClient(org.apache.oltu.oauth2.client.URLConnectionClient) OAuthClient(org.apache.oltu.oauth2.client.OAuthClient) OAuthSystemException(org.apache.oltu.oauth2.common.exception.OAuthSystemException) OAuthClientRequest(org.apache.oltu.oauth2.client.request.OAuthClientRequest)

Aggregations

OAuthClientRequest (org.apache.oltu.oauth2.client.request.OAuthClientRequest)7 URLConnectionClient (org.apache.oltu.oauth2.client.URLConnectionClient)6 OAuthClient (org.apache.oltu.oauth2.client.OAuthClient)5 URI (java.net.URI)2 OAuthBearerClientRequest (org.apache.oltu.oauth2.client.request.OAuthBearerClientRequest)2 OAuthJSONAccessTokenResponse (org.apache.oltu.oauth2.client.response.OAuthJSONAccessTokenResponse)2 OAuthResourceResponse (org.apache.oltu.oauth2.client.response.OAuthResourceResponse)2 OAuthProblemException (org.apache.oltu.oauth2.common.exception.OAuthProblemException)2 OAuthSystemException (org.apache.oltu.oauth2.common.exception.OAuthSystemException)2 URISyntaxException (java.net.URISyntaxException)1 URL (java.net.URL)1 Date (java.util.Date)1 GregorianCalendar (java.util.GregorianCalendar)1 AuthenticationException (org.apache.airavata.model.error.AuthenticationException)1 AiravataSecurityException (org.apache.airavata.security.AiravataSecurityException)1 DefaultOAuthClient (org.apache.airavata.service.security.oauth.DefaultOAuthClient)1 NonTransientException (org.apache.gobblin.exception.NonTransientException)1 TokenRequestBuilder (org.apache.oltu.oauth2.client.request.OAuthClientRequest.TokenRequestBuilder)1 OAuthAuthzResponse (org.apache.oltu.oauth2.client.response.OAuthAuthzResponse)1 OAuthRegistrationClient (org.apache.oltu.oauth2.ext.dynamicreg.client.OAuthRegistrationClient)1