Search in sources :

Example 16 with OAuthClientRequest

use of org.apache.oltu.oauth2.client.request.OAuthClientRequest in project irida by phac-nml.

the class RemoteAPITokenServiceImpl method createTokenFromAuthCode.

/**
 * Get a new token from the given auth code
 * @param authcode      the auth code to create a token for
 * @param remoteAPI     the remote api to get a token for
 * @param tokenRedirect a redirect url to get the token from
 * @return a new token
 * @throws OAuthSystemException If building the token request fails
 * @throws OAuthProblemException If the token request fails
 */
@Transactional
public RemoteAPIToken createTokenFromAuthCode(String authcode, RemoteAPI remoteAPI, String tokenRedirect) throws OAuthSystemException, OAuthProblemException {
    String serviceURI = remoteAPI.getServiceURI();
    // Build the token location for this service
    URI serviceTokenLocation = UriBuilder.fromUri(serviceURI).path("oauth").path("token").build();
    logger.debug("Remote token location: " + serviceTokenLocation);
    // Create the token request form the given auth code
    OAuthClientRequest tokenRequest = OAuthClientRequest.tokenLocation(serviceTokenLocation.toString()).setClientId(remoteAPI.getClientId()).setClientSecret(remoteAPI.getClientSecret()).setRedirectURI(tokenRedirect).setCode(authcode).setGrantType(GrantType.AUTHORIZATION_CODE).buildBodyMessage();
    // execute the request
    OAuthJSONAccessTokenResponse accessTokenResponse = oauthClient.accessToken(tokenRequest);
    // read the response for the access token
    String accessToken = accessTokenResponse.getAccessToken();
    // Handle Refresh Tokens
    String refreshToken = accessTokenResponse.getRefreshToken();
    // check the token expiry
    Long expiresIn = accessTokenResponse.getExpiresIn();
    Long currentTime = System.currentTimeMillis();
    Date expiry = new Date(currentTime + (expiresIn * ONE_SECOND_IN_MS));
    logger.debug("Token expiry: " + expiry);
    // create the OAuth2 token and store it
    RemoteAPIToken token = new RemoteAPIToken(accessToken, refreshToken, remoteAPI, expiry);
    return create(token);
}
Also used : RemoteAPIToken(ca.corefacility.bioinformatics.irida.model.RemoteAPIToken) OAuthJSONAccessTokenResponse(org.apache.oltu.oauth2.client.response.OAuthJSONAccessTokenResponse) OAuthClientRequest(org.apache.oltu.oauth2.client.request.OAuthClientRequest) URI(java.net.URI) Date(java.util.Date) Transactional(org.springframework.transaction.annotation.Transactional)

Example 17 with OAuthClientRequest

use of org.apache.oltu.oauth2.client.request.OAuthClientRequest in project irida by phac-nml.

the class RemoteAPITokenServiceImpl method updateTokenFromRefreshToken.

/**
 * {@inheritDoc}
 */
@Transactional
public RemoteAPIToken updateTokenFromRefreshToken(RemoteAPI api) {
    RemoteAPIToken token = null;
    try {
        token = getToken(api);
        String refreshToken = token.getRefreshToken();
        if (refreshToken != null) {
            URI serviceTokenLocation = UriBuilder.fromUri(api.getServiceURI()).path("oauth").path("token").build();
            OAuthClientRequest tokenRequest = OAuthClientRequest.tokenLocation(serviceTokenLocation.toString()).setClientId(api.getClientId()).setClientSecret(api.getClientSecret()).setRefreshToken(refreshToken).setGrantType(GrantType.REFRESH_TOKEN).buildBodyMessage();
            OAuthJSONAccessTokenResponse accessToken = oauthClient.accessToken(tokenRequest);
            token = buildTokenFromResponse(accessToken, api);
            delete(api);
            token = create(token);
            logger.debug("Token for api " + api + " updated by refresh token.");
        } else {
            logger.debug("No refresh token for api " + api + ". Cannot update access token.");
        }
    } catch (EntityNotFoundException ex) {
        logger.debug("Token not found for api " + api + ".  Cannot update access token.");
    } catch (OAuthProblemException | OAuthSystemException ex) {
        logger.error("Updating token by refresh token failed", ex.getMessage());
    }
    return token;
}
Also used : OAuthProblemException(org.apache.oltu.oauth2.common.exception.OAuthProblemException) RemoteAPIToken(ca.corefacility.bioinformatics.irida.model.RemoteAPIToken) OAuthSystemException(org.apache.oltu.oauth2.common.exception.OAuthSystemException) OAuthJSONAccessTokenResponse(org.apache.oltu.oauth2.client.response.OAuthJSONAccessTokenResponse) EntityNotFoundException(ca.corefacility.bioinformatics.irida.exceptions.EntityNotFoundException) OAuthClientRequest(org.apache.oltu.oauth2.client.request.OAuthClientRequest) URI(java.net.URI) Transactional(org.springframework.transaction.annotation.Transactional)

Example 18 with OAuthClientRequest

use of org.apache.oltu.oauth2.client.request.OAuthClientRequest 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 19 with OAuthClientRequest

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

the class StructrOAuthClient method getEndUserAuthorizationRequestUri.

/**
 * Create an end-user authorization request
 *
 * Use with {@literal response.setRedirect(request.getLocationUri());}
 *
 * @param request
 * @return request URI
 */
public String getEndUserAuthorizationRequestUri(final HttpServletRequest request) {
    OAuthClientRequest oauthClientRequest;
    try {
        oauthClientRequest = OAuthClientRequest.authorizationLocation(authorizationLocation).setClientId(clientId).setRedirectURI(getAbsoluteUrl(request, redirectUri)).setScope(getScope()).setResponseType(getResponseType()).setState(getState()).buildQueryMessage();
        logger.info("Authorization request location URI: {}", oauthClientRequest.getLocationUri());
        return oauthClientRequest.getLocationUri();
    } catch (OAuthSystemException ex) {
        logger.error("", ex);
    }
    return null;
}
Also used : OAuthSystemException(org.apache.oltu.oauth2.common.exception.OAuthSystemException) OAuthClientRequest(org.apache.oltu.oauth2.client.request.OAuthClientRequest)

Example 20 with OAuthClientRequest

use of org.apache.oltu.oauth2.client.request.OAuthClientRequest 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)

Aggregations

OAuthClientRequest (org.apache.oltu.oauth2.client.request.OAuthClientRequest)34 OAuthSystemException (org.apache.oltu.oauth2.common.exception.OAuthSystemException)25 IOException (java.io.IOException)20 Request (okhttp3.Request)18 Response (okhttp3.Response)18 Builder (okhttp3.Request.Builder)17 OAuthJSONAccessTokenResponse (org.apache.oltu.oauth2.client.response.OAuthJSONAccessTokenResponse)13 OAuthBearerClientRequest (org.apache.oltu.oauth2.client.request.OAuthBearerClientRequest)11 Map (java.util.Map)10 AuthenticationRequestBuilder (org.apache.oltu.oauth2.client.request.OAuthClientRequest.AuthenticationRequestBuilder)10 TokenRequestBuilder (org.apache.oltu.oauth2.client.request.OAuthClientRequest.TokenRequestBuilder)10 MediaType (okhttp3.MediaType)9 RequestBody (okhttp3.RequestBody)9 OAuthClientResponse (org.apache.oltu.oauth2.client.response.OAuthClientResponse)9 URI (java.net.URI)6 URLConnectionClient (org.apache.oltu.oauth2.client.URLConnectionClient)6 OAuthClient (org.apache.oltu.oauth2.client.OAuthClient)5 OAuthProblemException (org.apache.oltu.oauth2.common.exception.OAuthProblemException)5 OAuthRegistrationClient (org.apache.oltu.oauth2.ext.dynamicreg.client.OAuthRegistrationClient)3 OAuthClientRegistrationResponse (org.apache.oltu.oauth2.ext.dynamicreg.client.response.OAuthClientRegistrationResponse)3