Search in sources :

Example 1 with OAuthServiceException

use of org.apache.cxf.rs.security.oauth2.provider.OAuthServiceException in project cxf by apache.

the class JoseClientCodeStateManager method toRedirectState.

@Override
public MultivaluedMap<String, String> toRedirectState(MessageContext mc, MultivaluedMap<String, String> requestState) {
    JweEncryptionProvider theEncryptionProvider = getInitializedEncryptionProvider();
    JwsSignatureProvider theSigProvider = getInitializedSigProvider(theEncryptionProvider);
    if (theEncryptionProvider == null && theSigProvider == null) {
        throw new OAuthServiceException("The state can not be protected");
    }
    MultivaluedMap<String, String> redirectMap = new MetadataMap<String, String>();
    if (generateNonce && theSigProvider != null) {
        JwsCompactProducer nonceProducer = new JwsCompactProducer(OAuthUtils.generateRandomTokenKey());
        String nonceParam = nonceProducer.signWith(theSigProvider);
        requestState.putSingle(OAuthConstants.NONCE, nonceParam);
        redirectMap.putSingle(OAuthConstants.NONCE, nonceParam);
    }
    Map<String, Object> stateMap = CastUtils.cast((Map<?, ?>) requestState);
    String json = jsonp.toJson(stateMap);
    String stateParam = null;
    if (theSigProvider != null) {
        JwsCompactProducer stateProducer = new JwsCompactProducer(json);
        stateParam = stateProducer.signWith(theSigProvider);
    }
    if (theEncryptionProvider != null) {
        stateParam = theEncryptionProvider.encrypt(StringUtils.toBytesUTF8(stateParam), null);
    }
    if (storeInSession) {
        String sessionStateAttribute = OAuthUtils.generateRandomTokenKey();
        OAuthUtils.setSessionToken(mc, stateParam, sessionStateAttribute, 0);
        stateParam = sessionStateAttribute;
    }
    redirectMap.putSingle(OAuthConstants.STATE, stateParam);
    return redirectMap;
}
Also used : MetadataMap(org.apache.cxf.jaxrs.impl.MetadataMap) JweEncryptionProvider(org.apache.cxf.rs.security.jose.jwe.JweEncryptionProvider) OAuthServiceException(org.apache.cxf.rs.security.oauth2.provider.OAuthServiceException) JwsCompactProducer(org.apache.cxf.rs.security.jose.jws.JwsCompactProducer) JwsSignatureProvider(org.apache.cxf.rs.security.jose.jws.JwsSignatureProvider) NoneJwsSignatureProvider(org.apache.cxf.rs.security.jose.jws.NoneJwsSignatureProvider)

Example 2 with OAuthServiceException

use of org.apache.cxf.rs.security.oauth2.provider.OAuthServiceException in project cxf by apache.

the class OAuthClientUtils method getAccessToken.

/**
 * Obtains the access token from OAuth AccessToken Service
 * using the initialized web client
 * @param accessTokenService the AccessToken client
 * @param consumer {@link Consumer} representing the registered client.
 * @param grant {@link AccessTokenGrant} grant
 * @param extraParams extra parameters
 * @param defaultTokenType default expected token type - some early
 *        well-known OAuth2 services do not return a required token_type parameter
 * @param setAuthorizationHeader if set to true then HTTP Basic scheme
 *           will be used to pass client id and secret, otherwise they will
 *           be passed in the form payload
 * @return {@link ClientAccessToken} access token
 * @throws OAuthServiceException
 */
public static ClientAccessToken getAccessToken(WebClient accessTokenService, Consumer consumer, AccessTokenGrant grant, Map<String, String> extraParams, String defaultTokenType, boolean setAuthorizationHeader) throws OAuthServiceException {
    if (accessTokenService == null) {
        throw new OAuthServiceException(OAuthConstants.SERVER_ERROR);
    }
    Form form = new Form(grant.toMap());
    if (extraParams != null) {
        for (Map.Entry<String, String> entry : extraParams.entrySet()) {
            form.param(entry.getKey(), entry.getValue());
        }
    }
    if (consumer != null) {
        boolean secretAvailable = !StringUtils.isEmpty(consumer.getClientSecret());
        if (setAuthorizationHeader && secretAvailable) {
            StringBuilder sb = new StringBuilder();
            sb.append("Basic ");
            try {
                String data = consumer.getClientId() + ":" + consumer.getClientSecret();
                sb.append(Base64Utility.encode(data.getBytes(StandardCharsets.UTF_8)));
            } catch (Exception ex) {
                throw new ProcessingException(ex);
            }
            accessTokenService.replaceHeader("Authorization", sb.toString());
        } else {
            form.param(OAuthConstants.CLIENT_ID, consumer.getClientId());
            if (secretAvailable) {
                form.param(OAuthConstants.CLIENT_SECRET, consumer.getClientSecret());
            }
        }
    } else {
    // in this case the AccessToken service is expected to find a mapping between
    // the authenticated credentials and the client registration id
    }
    Response response = accessTokenService.form(form);
    Map<String, String> map = null;
    try {
        map = new OAuthJSONProvider().readJSONResponse((InputStream) response.getEntity());
    } catch (IOException ex) {
        throw new ResponseProcessingException(response, ex);
    }
    if (200 == response.getStatus()) {
        ClientAccessToken token = fromMapToClientToken(map, defaultTokenType);
        if (token == null) {
            throw new OAuthServiceException(OAuthConstants.SERVER_ERROR);
        }
        return token;
    } else if (response.getStatus() >= 400 && map.containsKey(OAuthConstants.ERROR_KEY)) {
        OAuthError error = new OAuthError(map.get(OAuthConstants.ERROR_KEY), map.get(OAuthConstants.ERROR_DESCRIPTION_KEY));
        error.setErrorUri(map.get(OAuthConstants.ERROR_URI_KEY));
        throw new OAuthServiceException(error);
    }
    throw new OAuthServiceException(OAuthConstants.SERVER_ERROR);
}
Also used : OAuthServiceException(org.apache.cxf.rs.security.oauth2.provider.OAuthServiceException) Form(javax.ws.rs.core.Form) InputStream(java.io.InputStream) ClientAccessToken(org.apache.cxf.rs.security.oauth2.common.ClientAccessToken) OAuthJSONProvider(org.apache.cxf.rs.security.oauth2.provider.OAuthJSONProvider) IOException(java.io.IOException) OAuthServiceException(org.apache.cxf.rs.security.oauth2.provider.OAuthServiceException) IOException(java.io.IOException) ProcessingException(javax.ws.rs.ProcessingException) ResponseProcessingException(javax.ws.rs.client.ResponseProcessingException) Response(javax.ws.rs.core.Response) OAuthError(org.apache.cxf.rs.security.oauth2.common.OAuthError) ResponseProcessingException(javax.ws.rs.client.ResponseProcessingException) Map(java.util.Map) ProcessingException(javax.ws.rs.ProcessingException) ResponseProcessingException(javax.ws.rs.client.ResponseProcessingException)

Example 3 with OAuthServiceException

use of org.apache.cxf.rs.security.oauth2.provider.OAuthServiceException in project cxf by apache.

the class AccessTokenValidatorClient method validateAccessToken.

public AccessTokenValidation validateAccessToken(MessageContext mc, String authScheme, String authSchemeData, MultivaluedMap<String, String> extraProps) throws OAuthServiceException {
    WebClient client = WebClient.fromClient(tokenValidatorClient, true);
    MultivaluedMap<String, String> props = new MetadataMap<String, String>();
    props.putSingle(OAuthConstants.AUTHORIZATION_SCHEME_TYPE, authScheme);
    props.putSingle(OAuthConstants.AUTHORIZATION_SCHEME_DATA, authSchemeData);
    if (extraProps != null) {
        props.putAll(extraProps);
    }
    try {
        return client.post(props, AccessTokenValidation.class);
    } catch (WebApplicationException ex) {
        throw new OAuthServiceException(ex);
    }
}
Also used : MetadataMap(org.apache.cxf.jaxrs.impl.MetadataMap) WebApplicationException(javax.ws.rs.WebApplicationException) OAuthServiceException(org.apache.cxf.rs.security.oauth2.provider.OAuthServiceException) WebClient(org.apache.cxf.jaxrs.client.WebClient)

Example 4 with OAuthServiceException

use of org.apache.cxf.rs.security.oauth2.provider.OAuthServiceException in project cxf by apache.

the class AuthorizationCodeGrantHandler method doCreateAccessToken.

private ServerAccessToken doCreateAccessToken(Client client, ServerAuthorizationCodeGrant grant, String requestedGrant, String codeVerifier, List<String> audiences) {
    if (grant.isPreauthorizedTokenAvailable()) {
        ServerAccessToken token = getPreAuthorizedToken(client, grant.getSubject(), requestedGrant, grant.getRequestedScopes(), getAudiences(client, grant.getAudience()));
        if (token != null) {
            if (grant.getNonce() != null) {
                JAXRSUtils.getCurrentMessage().getExchange().put(OAuthConstants.NONCE, grant.getNonce());
            }
            return token;
        }
        // creating a completely new token can be wrong - though this needs to be reviewed
        throw new OAuthServiceException(OAuthConstants.INVALID_GRANT);
    }
    if (!client.getAllowedGrantTypes().isEmpty() && !client.getAllowedGrantTypes().contains(requestedGrant)) {
        throw new OAuthServiceException(OAuthConstants.INVALID_GRANT);
    }
    // Delegate to the data provider to create the one
    AccessTokenRegistration reg = new AccessTokenRegistration();
    reg.setGrantCode(grant.getCode());
    reg.setClient(client);
    reg.setGrantType(requestedGrant);
    reg.setSubject(grant.getSubject());
    reg.setRequestedScope(grant.getRequestedScopes());
    reg.setNonce(grant.getNonce());
    if (grant.getApprovedScopes() != null) {
        reg.setApprovedScope(grant.getApprovedScopes());
    } else {
        reg.setApprovedScope(Collections.emptyList());
    }
    reg.setAudiences(audiences);
    reg.setResponseType(grant.getResponseType());
    reg.setClientCodeVerifier(codeVerifier);
    reg.getExtraProperties().putAll(grant.getExtraProperties());
    return getDataProvider().createAccessToken(reg);
}
Also used : ServerAccessToken(org.apache.cxf.rs.security.oauth2.common.ServerAccessToken) OAuthServiceException(org.apache.cxf.rs.security.oauth2.provider.OAuthServiceException) AccessTokenRegistration(org.apache.cxf.rs.security.oauth2.common.AccessTokenRegistration)

Example 5 with OAuthServiceException

use of org.apache.cxf.rs.security.oauth2.provider.OAuthServiceException in project cxf by apache.

the class AuthorizationCodeGrantHandler method createAccessToken.

public ServerAccessToken createAccessToken(Client client, MultivaluedMap<String, String> params) throws OAuthServiceException {
    // Get the grant representation from the provider
    String codeValue = params.getFirst(OAuthConstants.AUTHORIZATION_CODE_VALUE);
    ServerAuthorizationCodeGrant grant = ((AuthorizationCodeDataProvider) getDataProvider()).removeCodeGrant(codeValue);
    if (grant == null) {
        return null;
    }
    // check it has not expired, the client ids are the same
    if (OAuthUtils.isExpired(grant.getIssuedAt(), grant.getExpiresIn())) {
        throw new OAuthServiceException(OAuthConstants.INVALID_GRANT);
    }
    if (!grant.getClient().getClientId().equals(client.getClientId())) {
        throw new OAuthServiceException(OAuthConstants.INVALID_GRANT);
    }
    // redirect URIs must match too
    String expectedRedirectUri = grant.getRedirectUri();
    String providedRedirectUri = params.getFirst(OAuthConstants.REDIRECT_URI);
    if (providedRedirectUri != null) {
        if (expectedRedirectUri == null || !providedRedirectUri.equals(expectedRedirectUri)) {
            throw new OAuthServiceException(OAuthConstants.INVALID_REQUEST);
        }
    } else if (expectedRedirectUri == null && !isCanSupportPublicClients() || expectedRedirectUri != null && (client.getRedirectUris().size() != 1 || !client.getRedirectUris().contains(expectedRedirectUri))) {
        throw new OAuthServiceException(OAuthConstants.INVALID_REQUEST);
    }
    String clientCodeVerifier = params.getFirst(OAuthConstants.AUTHORIZATION_CODE_VERIFIER);
    String clientCodeChallenge = grant.getClientCodeChallenge();
    if (!compareCodeVerifierWithChallenge(client, clientCodeVerifier, clientCodeChallenge)) {
        throw new OAuthServiceException(OAuthConstants.INVALID_GRANT);
    }
    List<String> audiences = getAudiences(client, params, grant.getAudience());
    return doCreateAccessToken(client, grant, getSingleGrantType(), clientCodeVerifier, audiences);
}
Also used : OAuthServiceException(org.apache.cxf.rs.security.oauth2.provider.OAuthServiceException)

Aggregations

OAuthServiceException (org.apache.cxf.rs.security.oauth2.provider.OAuthServiceException)37 ServerAccessToken (org.apache.cxf.rs.security.oauth2.common.ServerAccessToken)12 WebClient (org.apache.cxf.jaxrs.client.WebClient)11 Test (org.junit.Test)8 HashMap (java.util.HashMap)6 IOException (java.io.IOException)4 OAuthPermission (org.apache.cxf.rs.security.oauth2.common.OAuthPermission)4 UserSubject (org.apache.cxf.rs.security.oauth2.common.UserSubject)4 ArrayList (java.util.ArrayList)3 Base64Exception (org.apache.cxf.common.util.Base64Exception)3 Consumer (org.apache.cxf.rs.security.oauth2.client.Consumer)3 AccessTokenValidation (org.apache.cxf.rs.security.oauth2.common.AccessTokenValidation)3 OAuthError (org.apache.cxf.rs.security.oauth2.common.OAuthError)3 InputStream (java.io.InputStream)2 List (java.util.List)2 Map (java.util.Map)2 Consumes (javax.ws.rs.Consumes)2 POST (javax.ws.rs.POST)2 ProcessingException (javax.ws.rs.ProcessingException)2 Produces (javax.ws.rs.Produces)2