Search in sources :

Example 71 with OAuthSystemException

use of org.apache.oltu.oauth2.common.exception.OAuthSystemException in project identity-inbound-auth-oauth by wso2-extensions.

the class RefreshGrantHandler method createTokens.

private void createTokens(AccessTokenDO accessTokenDO, OAuthTokenReqMessageContext tokReqMsgCtx) throws IdentityOAuth2Exception {
    try {
        OauthTokenIssuer oauthTokenIssuer = OAuth2Util.getOAuthTokenIssuerForOAuthApp(accessTokenDO.getConsumerKey());
        String accessToken = oauthTokenIssuer.accessToken(tokReqMsgCtx);
        String refreshToken = oauthTokenIssuer.refreshToken(tokReqMsgCtx);
        if (log.isDebugEnabled()) {
            if (IdentityUtil.isTokenLoggable(IdentityConstants.IdentityTokens.ACCESS_TOKEN)) {
                log.debug("New access token (hashed): " + DigestUtils.sha256Hex(accessToken) + " & new refresh token (hashed): " + DigestUtils.sha256Hex(refreshToken));
            } else {
                log.debug("Access token and refresh token generated.");
            }
        }
        accessTokenDO.setAccessToken(accessToken);
        accessTokenDO.setRefreshToken(refreshToken);
    } catch (OAuthSystemException e) {
        throw new IdentityOAuth2Exception("Error when generating the tokens.", e);
    } catch (InvalidOAuthClientException e) {
        throw new IdentityOAuth2Exception("Error while retrieving oauth issuer for the app with clientId: " + accessTokenDO.getConsumerKey(), e);
    }
}
Also used : OauthTokenIssuer(org.wso2.carbon.identity.oauth2.token.OauthTokenIssuer) IdentityOAuth2Exception(org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception) OAuthSystemException(org.apache.oltu.oauth2.common.exception.OAuthSystemException) InvalidOAuthClientException(org.wso2.carbon.identity.oauth.common.exception.InvalidOAuthClientException)

Example 72 with OAuthSystemException

use of org.apache.oltu.oauth2.common.exception.OAuthSystemException in project javlo by Javlo.

the class AbstractSocialNetwork method getAccessToken.

public String getAccessToken(String code, OAuthClient oAuthClient) throws OAuthSystemException, OAuthProblemException {
    String clientId = getClientId();
    if (clientId == null || clientId.isEmpty()) {
        return null;
    }
    String clientSecret = getClientSecret();
    if (clientSecret == null || clientSecret.isEmpty()) {
        return null;
    }
    TokenRequestBuilder builder = createTokenRequest();
    configureTokenRequest(builder, clientId, clientSecret, code);
    OAuthClientRequest request = buildTokenRequest(builder);
    OAuthAccessTokenResponse response = executeTokenRequest(oAuthClient, request);
    String accessToken = response.getAccessToken();
    Long expiresIn = response.getExpiresIn();
    // TODO remove sysouts
    System.out.println("accessToken = " + accessToken);
    System.out.println("expiresIn = " + expiresIn);
    return accessToken;
}
Also used : TokenRequestBuilder(org.apache.oltu.oauth2.client.request.OAuthClientRequest.TokenRequestBuilder) OAuthAccessTokenResponse(org.apache.oltu.oauth2.client.response.OAuthAccessTokenResponse) OAuthClientRequest(org.apache.oltu.oauth2.client.request.OAuthClientRequest)

Example 73 with OAuthSystemException

use of org.apache.oltu.oauth2.common.exception.OAuthSystemException in project geoprism-registry by terraframe.

the class RegistrySessionService method ologin.

/**
 * Serves as a "redirect url" for logging into DHIS2 via oauth.
 *
 * @param serverId
 * @param code
 * @param locales
 * @param redirectBase
 * @return
 */
@Authenticate
public static java.lang.String ologin(java.lang.String serverId, java.lang.String code, java.lang.String locales, java.lang.String redirectBase) {
    try {
        // We used to try to build this from the controller but it would include stuff (like the port :443) which then wouldn't match
        // with the redirect url the client specified in DHIS2. Therefore this has to be something that the user can set (or, at least,
        // in a properties file)
        redirectBase = GeoregistryProperties.getRemoteServerUrl();
        String redirect = redirectBase + "cgrsession/ologin";
        OauthServer server = OauthServer.get(serverId);
        /*
       * Get the access token
       */
        TokenRequestBuilder tokenBuilder = OAuthClientRequest.tokenLocation(server.getTokenLocation());
        tokenBuilder.setGrantType(GrantType.AUTHORIZATION_CODE);
        tokenBuilder.setRedirectURI(redirect);
        tokenBuilder.setCode(code);
        String auth = server.getClientId() + ":" + server.getSecretKey();
        OAuthClientRequest tokenRequest = tokenBuilder.buildBodyMessage();
        tokenRequest.setHeader("Accept", "application/json");
        tokenRequest.setHeader("Authorization", "Basic " + new String(Base64.getEncoder().encode(auth.getBytes())));
        URLConnectionClient connClient = new URLConnectionClient();
        OAuthClient oAuthClient = new OAuthClient(connClient);
        OAuthJSONAccessTokenResponse accessToken = oAuthClient.accessToken(tokenRequest, OAuth.HttpMethod.POST, OAuthJSONAccessTokenResponse.class);
        /*
       * Request the user information
       */
        OAuthBearerClientRequest requestBuilder = new OAuthBearerClientRequest(server.getProfileLocation());
        requestBuilder.setAccessToken(accessToken.getAccessToken());
        OAuthClientRequest bearerRequest = requestBuilder.buildQueryMessage();
        OAuthResourceResponse resourceResponse = oAuthClient.resource(bearerRequest, OAuth.HttpMethod.GET, OAuthResourceResponse.class);
        String body = resourceResponse.getBody();
        JSONObject object = new JSONObject(body);
        final String username = object.getJSONObject("userCredentials").getString("username");
        SingleActorDAOIF profile = RegistrySessionService.getActor(server, username);
        String sessionId = SessionFacade.logIn(profile, LocaleSerializer.deserialize(locales));
        JsonObject json = new JsonObject();
        json.addProperty("sessionId", sessionId);
        json.addProperty("username", username);
        return json.toString();
    } catch (JSONException | OAuthSystemException | OAuthProblemException e) {
        throw new InvalidLoginException(e);
    }
}
Also used : TokenRequestBuilder(org.apache.oltu.oauth2.client.request.OAuthClientRequest.TokenRequestBuilder) OAuthResourceResponse(org.apache.oltu.oauth2.client.response.OAuthResourceResponse) OAuthClient(org.apache.oltu.oauth2.client.OAuthClient) OAuthSystemException(org.apache.oltu.oauth2.common.exception.OAuthSystemException) JsonObject(com.google.gson.JsonObject) JSONException(org.json.JSONException) OAuthBearerClientRequest(org.apache.oltu.oauth2.client.request.OAuthBearerClientRequest) OAuthProblemException(org.apache.oltu.oauth2.common.exception.OAuthProblemException) URLConnectionClient(org.apache.oltu.oauth2.client.URLConnectionClient) JSONObject(org.json.JSONObject) InvalidLoginException(com.runwaysdk.session.InvalidLoginException) OAuthJSONAccessTokenResponse(org.apache.oltu.oauth2.client.response.OAuthJSONAccessTokenResponse) SingleActorDAOIF(com.runwaysdk.business.rbac.SingleActorDAOIF) OAuthClientRequest(org.apache.oltu.oauth2.client.request.OAuthClientRequest) OauthServer(net.geoprism.account.OauthServer) Authenticate(com.runwaysdk.business.rbac.Authenticate)

Example 74 with OAuthSystemException

use of org.apache.oltu.oauth2.common.exception.OAuthSystemException in project android by gotify.

the class OAuth method retryingIntercept.

private Response retryingIntercept(Chain chain, boolean updateTokenAndRetryOnAuthorizationFailure) throws IOException {
    Request request = chain.request();
    // If the request already have an authorization (eg. Basic auth), do nothing
    if (request.header("Authorization") != null) {
        return chain.proceed(request);
    }
    // If first time, get the token
    OAuthClientRequest oAuthRequest;
    if (getAccessToken() == null) {
        updateAccessToken(null);
    }
    if (getAccessToken() != null) {
        // Build the request
        Builder rb = request.newBuilder();
        String requestAccessToken = new String(getAccessToken());
        try {
            oAuthRequest = new OAuthBearerClientRequest(request.url().toString()).setAccessToken(requestAccessToken).buildHeaderMessage();
        } catch (OAuthSystemException e) {
            throw new IOException(e);
        }
        for (Map.Entry<String, String> header : oAuthRequest.getHeaders().entrySet()) {
            rb.addHeader(header.getKey(), header.getValue());
        }
        rb.url(oAuthRequest.getLocationUri());
        // Execute the request
        Response response = chain.proceed(rb.build());
        // 401/403 most likely indicates that access token has expired. Unless it happens two times in a row.
        if (response != null && (response.code() == HTTP_UNAUTHORIZED || response.code() == HTTP_FORBIDDEN) && updateTokenAndRetryOnAuthorizationFailure) {
            if (updateAccessToken(requestAccessToken)) {
                return retryingIntercept(chain, false);
            }
        }
        return response;
    } else {
        return chain.proceed(chain.request());
    }
}
Also used : OAuthBearerClientRequest(org.apache.oltu.oauth2.client.request.OAuthBearerClientRequest) OAuthJSONAccessTokenResponse(org.apache.oltu.oauth2.client.response.OAuthJSONAccessTokenResponse) Response(okhttp3.Response) OAuthSystemException(org.apache.oltu.oauth2.common.exception.OAuthSystemException) AuthenticationRequestBuilder(org.apache.oltu.oauth2.client.request.OAuthClientRequest.AuthenticationRequestBuilder) Builder(okhttp3.Request.Builder) TokenRequestBuilder(org.apache.oltu.oauth2.client.request.OAuthClientRequest.TokenRequestBuilder) Request(okhttp3.Request) OAuthClientRequest(org.apache.oltu.oauth2.client.request.OAuthClientRequest) OAuthBearerClientRequest(org.apache.oltu.oauth2.client.request.OAuthBearerClientRequest) IOException(java.io.IOException) OAuthClientRequest(org.apache.oltu.oauth2.client.request.OAuthClientRequest) Map(java.util.Map)

Example 75 with OAuthSystemException

use of org.apache.oltu.oauth2.common.exception.OAuthSystemException in project Kustvakt by KorAP.

the class OAuth2ResponseHandler method throwit.

public WebApplicationException throwit(OAuthProblemException e, String state) {
    OAuthResponse oAuthResponse = null;
    try {
        OAuthErrorResponseBuilder builder = OAuthResponse.errorResponse(e.getResponseStatus()).error(e);
        if (state != null && !state.isEmpty()) {
            builder.setState(state);
        }
        oAuthResponse = builder.buildJSONMessage();
    } catch (OAuthSystemException e1) {
        throwit(e1, state);
    }
    Response r = createResponse(oAuthResponse);
    return new WebApplicationException(r);
}
Also used : Response(javax.ws.rs.core.Response) OAuthResponse(org.apache.oltu.oauth2.common.message.OAuthResponse) OAuthErrorResponseBuilder(org.apache.oltu.oauth2.common.message.OAuthResponse.OAuthErrorResponseBuilder) WebApplicationException(javax.ws.rs.WebApplicationException) OAuthSystemException(org.apache.oltu.oauth2.common.exception.OAuthSystemException) OAuthResponse(org.apache.oltu.oauth2.common.message.OAuthResponse)

Aggregations

OAuthSystemException (org.apache.oltu.oauth2.common.exception.OAuthSystemException)103 OAuthClientRequest (org.apache.oltu.oauth2.client.request.OAuthClientRequest)57 OAuthProblemException (org.apache.oltu.oauth2.common.exception.OAuthProblemException)51 OAuthResponse (org.apache.oltu.oauth2.common.message.OAuthResponse)49 IOException (java.io.IOException)41 Request (okhttp3.Request)29 Response (okhttp3.Response)29 OAuthJSONAccessTokenResponse (org.apache.oltu.oauth2.client.response.OAuthJSONAccessTokenResponse)23 Builder (okhttp3.Request.Builder)19 OAuthBearerClientRequest (org.apache.oltu.oauth2.client.request.OAuthBearerClientRequest)18 URI (java.net.URI)17 Map (java.util.Map)16 TokenRequestBuilder (org.apache.oltu.oauth2.client.request.OAuthClientRequest.TokenRequestBuilder)15 OAuthClientResponse (org.apache.oltu.oauth2.client.response.OAuthClientResponse)15 MediaType (okhttp3.MediaType)14 RequestBody (okhttp3.RequestBody)14 OAuthClient (org.apache.oltu.oauth2.client.OAuthClient)13 MD5Generator (org.apache.oltu.oauth2.as.issuer.MD5Generator)12 AuthenticationRequestBuilder (org.apache.oltu.oauth2.client.request.OAuthClientRequest.AuthenticationRequestBuilder)12 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)12