Java Code Examples for org.apache.cxf.rs.security.oauth2.provider.OAuthServiceException

The following examples show how to use org.apache.cxf.rs.security.oauth2.provider.OAuthServiceException. These examples are extracted from open source projects. 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 Project: cxf   Source File: OAuthClientUtils.java    License: Apache License 2.0 6 votes vote down vote up
private static void appendTokenData(StringBuilder sb,
                                    ClientAccessToken token,
                                    HttpRequestProperties httpProps)
    throws OAuthServiceException {
    // this should all be handled by token specific serializers
    String tokenType = token.getTokenType().toLowerCase();
    if (OAuthConstants.BEARER_TOKEN_TYPE.equalsIgnoreCase(tokenType)) {
        sb.append(OAuthConstants.BEARER_AUTHORIZATION_SCHEME);
        sb.append(' ');
        sb.append(token.getTokenKey());
    } else if (OAuthConstants.HAWK_TOKEN_TYPE.equalsIgnoreCase(tokenType)) {
        if (httpProps == null) {
            throw new IllegalArgumentException("MAC scheme requires HTTP Request properties");
        }
        HawkAuthorizationScheme macAuthData = new HawkAuthorizationScheme(httpProps, token);
        String macAlgo = token.getParameters().get(OAuthConstants.HAWK_TOKEN_ALGORITHM);
        String macKey = token.getParameters().get(OAuthConstants.HAWK_TOKEN_KEY);
        sb.append(macAuthData.toAuthorizationHeader(macAlgo, macKey));
    } else {
        throw new ProcessingException(new OAuthServiceException("Unsupported token type"));
    }

}
 
Example 2
Source Project: cxf   Source File: AccessTokenValidatorClient.java    License: Apache License 2.0 6 votes vote down vote up
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<>();
    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);
    }
}
 
Example 3
Source Project: cxf   Source File: HawkAccessTokenValidatorClient.java    License: Apache License 2.0 6 votes vote down vote up
public AccessTokenValidation validateAccessToken(MessageContext mc,
                                                 String authScheme,
                                                 String authSchemeData,
                                                 MultivaluedMap<String, String> extraProps)
    throws OAuthServiceException {
    if (isRemoteSignatureValidation()) {
        MultivaluedMap<String, String> map = new MetadataMap<>();
        if (extraProps != null) {
            map.putAll(extraProps);
        }
        map.putSingle(HTTP_VERB, mc.getRequest().getMethod());
        map.putSingle(HTTP_URI, mc.getUriInfo().getRequestUri().toString());
        return validator.validateAccessToken(mc, authScheme, authSchemeData, map);
    }
    return super.validateAccessToken(mc, authScheme, authSchemeData, extraProps);

}
 
Example 4
Source Project: cxf   Source File: OidcUtils.java    License: Apache License 2.0 6 votes vote down vote up
private static String calculateHash(String value, SignatureAlgorithm sigAlgo) {
    if (sigAlgo == SignatureAlgorithm.NONE) {
        throw new JwsException(JwsException.Error.INVALID_ALGORITHM);
    }
    String algoShaSizeString = sigAlgo.getJwaName().substring(2);
    String javaShaAlgo = "SHA-" + algoShaSizeString;
    int algoShaSize = Integer.parseInt(algoShaSizeString);
    int valueHashSize = (algoShaSize / 8) / 2;
    try {
        byte[] atBytes = StringUtils.toBytesASCII(value);
        byte[] digest = MessageDigestUtils.createDigest(atBytes,  javaShaAlgo);
        return Base64UrlUtility.encodeChunk(digest, 0, valueHashSize);
    } catch (NoSuchAlgorithmException ex) {
        throw new OAuthServiceException(ex);
    }
}
 
Example 5
Source Project: cxf   Source File: JAXRSOAuth2Test.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testBasicAuthClientCred() throws Exception {
    String address = "https://localhost:" + port + "/oauth2/token";
    WebClient wc = createWebClient(address);
    ClientCredentialsGrant grant = new ClientCredentialsGrant();
    // Pass client_id & client_secret as form properties
    // (instead WebClient can be initialized with username & password)
    grant.setClientId("bob");
    grant.setClientSecret("bobPassword");
    try {
        OAuthClientUtils.getAccessToken(wc, grant);
        fail("Form based authentication is not supported");
    } catch (OAuthServiceException ex) {
        assertEquals(OAuthConstants.UNAUTHORIZED_CLIENT, ex.getError().getError());
    }

    ClientAccessToken at = OAuthClientUtils.getAccessToken(wc,
                                                           new Consumer("bob", "bobPassword"),
                                                           new ClientCredentialsGrant(),
                                                           true);
    assertNotNull(at.getTokenKey());
}
 
Example 6
Source Project: cxf   Source File: JAXRSOAuth2Test.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testSAMLAudRestr() throws Exception {
    String address = "https://localhost:" + port + "/oauth2-auth/token";
    WebClient wc = createWebClient(address);

    String audienceURI = "https://localhost:" + port + "/oauth2-auth/token2";
    String assertion = OAuth2TestUtils.createToken(audienceURI, true, true);
    String encodedAssertion = Base64UrlUtility.encode(assertion);

    Map<String, String> extraParams = new HashMap<>();
    extraParams.put(Constants.CLIENT_AUTH_ASSERTION_TYPE, Constants.CLIENT_AUTH_SAML2_BEARER);
    extraParams.put(Constants.CLIENT_AUTH_ASSERTION_PARAM, encodedAssertion);

    try {
        OAuthClientUtils.getAccessToken(wc, new CustomGrant(), extraParams);
        fail("Failure expected on a bad audience restriction");
    } catch (OAuthServiceException ex) {
        // expected
    }
}
 
Example 7
Source Project: cxf   Source File: JAXRSOAuth2Test.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testJWTBadSubjectName() throws Exception {
    String address = "https://localhost:" + port + "/oauth2-auth-jwt/token";
    WebClient wc = createWebClient(address);

    // Create the JWT Token
    String token = OAuth2TestUtils.createToken("resourceOwner", "bob", address, true, true);

    Map<String, String> extraParams = new HashMap<>();
    extraParams.put(Constants.CLIENT_AUTH_ASSERTION_TYPE,
                    "urn:ietf:params:oauth:client-assertion-type:jwt-bearer");
    extraParams.put(Constants.CLIENT_AUTH_ASSERTION_PARAM, token);

    try {
        OAuthClientUtils.getAccessToken(wc, new CustomGrant(), extraParams);
        fail("Failure expected on a bad subject name");
    } catch (OAuthServiceException ex) {
        // expected
    }
}
 
Example 8
Source Project: cxf-fediz   Source File: EHCacheOIDCTokenProvider.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public List<OAuthPermission> convertScopeToPermissions(Client client, List<String> requestedScopes) {
    if (requestedScopes.isEmpty()) {
        return Collections.emptyList();
    }

    List<OAuthPermission> permissions = new ArrayList<>();
    for (String requestedScope : requestedScopes) {
        if ("openid".equals(requestedScope)) {
            OAuthPermission permission = new OAuthPermission("openid", "Authenticate user");
            permissions.add(permission);
        } else {
            throw new OAuthServiceException("invalid_scope");
        }
    }

    return permissions;
}
 
Example 9
Source Project: cxf-fediz   Source File: FedizSubjectCreator.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public OidcUserSubject createUserSubject(MessageContext mc, MultivaluedMap<String, String> params) {
    Principal principal = mc.getSecurityContext().getUserPrincipal();

    if (!(principal instanceof FedizPrincipal)) {
        throw new OAuthServiceException("Unsupported Principal");
    }
    FedizPrincipal fedizPrincipal = (FedizPrincipal) principal;

    // In the future FedizPrincipal will likely have JWT claims already prepared,
    // with IdToken being initialized here from those claims
    OidcUserSubject oidcSub = new OidcUserSubject();
    oidcSub.setLogin(fedizPrincipal.getName());

    // REVISIT: use fedizPrincipal.getId() to guarantee the uniqueness once FEDIZ-207 is resolved
    oidcSub.setId(fedizPrincipal.getName());

    IdToken idToken = convertToIdToken(mc, fedizPrincipal.getLoginToken(), oidcSub.getLogin(), oidcSub.getId(),
            fedizPrincipal.getClaims(), fedizPrincipal.getRoleClaims(), params);
    oidcSub.setIdToken(idToken);
    oidcSub.setRoles(fedizPrincipal.getRoleClaims());
    // UserInfo can be populated and set on OidcUserSubject too.
    // UserInfoService will create it otherwise.

    return oidcSub;
}
 
Example 10
Source Project: cxf   Source File: OidcAuthorizationCodeService.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected boolean canAuthorizationBeSkipped(MultivaluedMap<String, String> params,
                                            Client client,
                                            UserSubject userSubject,
                                            List<String> requestedScope,
                                            List<OAuthPermission> permissions) {
    List<String> promptValues = OidcUtils.getPromptValues(params);
    if (promptValues.contains(OidcUtils.PROMPT_CONSENT_VALUE)) {
        // Displaying the consent screen is preferred by the client
        return false;
    }
    // Check the pre-configured consent
    boolean preConfiguredConsentForScopes =
        super.canAuthorizationBeSkipped(params, client, userSubject, requestedScope, permissions);

    if (!preConfiguredConsentForScopes && promptValues.contains(OidcUtils.PROMPT_NONE_VALUE)) {
        // An error is returned if client does not have pre-configured consent for the requested scopes/claims
        LOG.log(Level.FINE, "Prompt 'none' request can not be met");
        throw new OAuthServiceException(new OAuthError(OidcUtils.CONSENT_REQUIRED_ERROR));
    }
    return preConfiguredConsentForScopes;
}
 
Example 11
Source Project: cxf   Source File: AbstractGrantHandler.java    License: Apache License 2.0 6 votes vote down vote up
protected ServerAccessToken getPreAuthorizedToken(Client client,
                                                  UserSubject subject,
                                                  String requestedGrant,
                                                  List<String> requestedScopes,
                                                  List<String> audiences) {
    if (!OAuthUtils.validateScopes(requestedScopes, client.getRegisteredScopes(),
                                   partialMatchScopeValidation)) {
        throw new OAuthServiceException(new OAuthError(OAuthConstants.INVALID_SCOPE));
    }
    if (!OAuthUtils.validateAudiences(audiences, client.getRegisteredAudiences())) {
        throw new OAuthServiceException(new OAuthError(OAuthConstants.INVALID_GRANT));
    }

    // Get a pre-authorized token if available
    return dataProvider.getPreauthorizedToken(
                                 client, requestedScopes, subject, requestedGrant);

}
 
Example 12
Source Project: cxf   Source File: OidcImplicitService.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected boolean canAuthorizationBeSkipped(MultivaluedMap<String, String> params,
                                            Client client,
                                            UserSubject userSubject,
                                            List<String> requestedScope,
                                            List<OAuthPermission> permissions) {
    List<String> promptValues = OidcUtils.getPromptValues(params);
    if (promptValues.contains(OidcUtils.PROMPT_CONSENT_VALUE)) {
        // Displaying the consent screen is preferred by the client
        return false;
    }
    // Check the pre-configured consent
    boolean preConfiguredConsentForScopes =
        super.canAuthorizationBeSkipped(params, client, userSubject, requestedScope, permissions);

    if (!preConfiguredConsentForScopes && promptValues.contains(OidcUtils.PROMPT_NONE_VALUE)) {
        // An error is returned if client does not have pre-configured consent for the requested scopes/claims
        LOG.log(Level.FINE, "Prompt 'none' request can not be met");
        throw new OAuthServiceException(new OAuthError(OidcUtils.CONSENT_REQUIRED_ERROR));
    }
    return preConfiguredConsentForScopes;
}
 
Example 13
Source Project: cxf   Source File: OAuthUtils.java    License: Apache License 2.0 6 votes vote down vote up
public static List<String> getRequestedScopes(Client client,
                                              String scopeParameter,
                                              boolean useAllClientScopes,
                                              boolean partialMatchScopeValidation) {
    List<String> requestScopes = parseScope(scopeParameter);
    List<String> registeredScopes = client.getRegisteredScopes();
    if (requestScopes.isEmpty()) {
        return registeredScopes;
    }
    if (!validateScopes(requestScopes, registeredScopes, partialMatchScopeValidation)) {
        throw new OAuthServiceException("Unexpected scope");
    }
    if (useAllClientScopes) {
        for (String registeredScope : registeredScopes) {
            if (!requestScopes.contains(registeredScope)) {
                requestScopes.add(registeredScope);
            }
        }
    }

    return requestScopes;
}
 
Example 14
Source Project: cxf   Source File: OAuthUtils.java    License: Apache License 2.0 6 votes vote down vote up
public static SignatureAlgorithm getClientSecretSignatureAlgorithm(Properties sigProps) {

        String clientSecretSigProp = sigProps.getProperty(OAuthConstants.CLIENT_SECRET_SIGNATURE_ALGORITHM);
        if (clientSecretSigProp == null) {
            String sigProp = sigProps.getProperty(JoseConstants.RSSEC_SIGNATURE_ALGORITHM);
            if (AlgorithmUtils.isHmacSign(sigProp)) {
                clientSecretSigProp = sigProp;
            }
        }
        SignatureAlgorithm sigAlgo = SignatureAlgorithm.getAlgorithm(clientSecretSigProp);
        sigAlgo = sigAlgo != null ? sigAlgo : SignatureAlgorithm.HS256;
        if (!AlgorithmUtils.isHmacSign(sigAlgo)) {
            // Must be HS-based for the symmetric signature
            throw new OAuthServiceException(OAuthConstants.SERVER_ERROR);
        }
        return sigAlgo;
    }
 
Example 15
Source Project: cxf   Source File: DirectAuthorizationService.java    License: Apache License 2.0 6 votes vote down vote up
protected Client getClient(MultivaluedMap<String, String> params) {
    Client client = null;

    try {
        client = getValidClient(params.getFirst(OAuthConstants.CLIENT_ID), params);
    } catch (OAuthServiceException ex) {
        if (ex.getError() != null) {
            reportInvalidRequestError(ex.getError(), null);
        }
    }

    if (client == null) {
        reportInvalidRequestError("Client ID is invalid", null);
    }
    return client;

}
 
Example 16
Source Project: cxf   Source File: RedirectionBasedGrantService.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Get the {@link Client} reference
 * @param params request parameters
 * @return Client the client reference
 * @throws {@link javax.ws.rs.WebApplicationException} if no matching Client is found,
 *         the error is returned directly to the end user without
 *         following the redirect URI if any
 */
protected Client getClient(String clientId, MultivaluedMap<String, String> params) {
    Client client = null;

    try {
        client = getValidClient(clientId, params);
    } catch (OAuthServiceException ex) {
        if (ex.getError() != null) {
            reportInvalidRequestError(ex.getError(), null);
        }
    }

    if (client == null) {
        reportInvalidRequestError("Client ID is invalid", null);
    }
    return client;

}
 
Example 17
Source Project: cxf   Source File: NonceVerifierImplTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testVerifyNonceInvalidTimestamp() {
    long now = System.currentTimeMillis();
    Nonce nonce1 = new Nonce("nonce1", now - 2000); // first request 2 seconds back
    Nonce nonce2 = new Nonce("nonce2", now - 1000); // second request 1 second back
    NonceHistory nonceHistory = new NonceHistory(200, nonce1); // first request time delta is 200ms
    nonceHistory.addNonce(nonce2);

    EasyMock.expect(nonceStore.getNonceHistory("testTokenKey")).andReturn(nonceHistory);
    EasyMock.replay(nonceStore);
    nonceVerifier.setAllowedWindow(2000); // allowed window is 2 seconds
    try {
        nonceVerifier.verifyNonce("testTokenKey", "nonce3", Long.toString(now - 5000)); // very old timestamp
        fail("Exception expected");
    } catch (OAuthServiceException ex) {
        assertEquals("Timestamp is invalid", ex.getMessage());
    }
}
 
Example 18
@Override
public ServerAccessToken createAccessToken(final AccessTokenRegistration accessToken) throws OAuthServiceException {
    if (!accessToken.getRequestedScope().contains(OAuthConstants.REFRESH_TOKEN_SCOPE)) {
        accessToken.setRequestedScope(new ArrayList<>(accessToken.getRequestedScope()));
        accessToken.getRequestedScope().add(OAuthConstants.REFRESH_TOKEN_SCOPE);
    }
    if (!accessToken.getApprovedScope().contains(OAuthConstants.REFRESH_TOKEN_SCOPE)) {
        accessToken.setApprovedScope(new ArrayList<>(accessToken.getApprovedScope()));
        accessToken.getApprovedScope().add(OAuthConstants.REFRESH_TOKEN_SCOPE);
    }
    return delegate.createAccessToken(accessToken);
}
 
Example 19
Source Project: cxf   Source File: NonceVerifierImpl.java    License: Apache License 2.0 5 votes vote down vote up
private void checkAdjustedRequestTime(long serverClock, long clientTimestamp, NonceHistory nonceHistory) {
    long adjustedRequestTime = clientTimestamp + nonceHistory.getRequestTimeDelta();
    long requestDelta = Math.abs(serverClock - adjustedRequestTime);
    if (requestDelta > allowedWindow) {
        throw new OAuthServiceException("Timestamp is invalid");
    }
}
 
Example 20
Source Project: cxf   Source File: OAuthClientUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static ClientAccessToken refreshAccessToken(WebClient accessTokenService,
                                                   Consumer consumer,
                                                   ClientAccessToken at,
                                                   String scope,
                                                   boolean setAuthorizationHeader)
    throws OAuthServiceException {
    RefreshTokenGrant grant = new RefreshTokenGrant(at.getRefreshToken(), scope);
    return getAccessToken(accessTokenService, consumer, grant, null,
                          at.getTokenType(), setAuthorizationHeader);
}
 
Example 21
Source Project: olingo-odata4   Source File: OAuth2Provider.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public ServerAccessToken refreshAccessToken(
    final Client client, final String string, final List<String> list)
    throws OAuthServiceException {

  throw new UnsupportedOperationException("Not supported yet.");
}
 
Example 22
Source Project: cxf   Source File: MemoryClientCodeStateManager.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public MultivaluedMap<String, String> fromRedirectState(MessageContext mc,
                                                        MultivaluedMap<String, String> redirectState) {
    String stateParam = redirectState.getFirst(OAuthConstants.STATE);
    String sessionToken = OAuthUtils.getSessionToken(mc, "state");
    if (sessionToken == null || !sessionToken.equals(stateParam)) {
        throw new OAuthServiceException("Invalid session token");
    }
    return map.remove(stateParam);
}
 
Example 23
Source Project: cxf   Source File: OidcUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static void validateAccessTokenHash(String accessToken, JwtToken jwt, boolean required) {
    String hashClaim = (String)jwt.getClaims().getClaim(IdToken.ACCESS_TOKEN_HASH_CLAIM);
    if (hashClaim == null && required) {
        throw new OAuthServiceException("Invalid hash");
    }
    if (hashClaim != null) {
        validateHash(accessToken,
                     (String)jwt.getClaims().getClaim(IdToken.ACCESS_TOKEN_HASH_CLAIM),
                     jwt.getJwsHeaders().getSignatureAlgorithm());
    }
}
 
Example 24
Source Project: cxf   Source File: CodeGrantEncryptingDataProvider.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public ServerAuthorizationCodeGrant createCodeGrant(AuthorizationCodeRegistration reg)
    throws OAuthServiceException {
    ServerAuthorizationCodeGrant grant =
        new ServerAuthorizationCodeGrant(reg.getClient(), 123);
    grant.setAudience(reg.getAudience());
    String encrypted = ModelEncryptionSupport.encryptCodeGrant(grant, key);
    grant.setCode(encrypted);
    grants.add(encrypted);
    return grant;
}
 
Example 25
Source Project: cxf   Source File: PublicClientTest.java    License: Apache License 2.0 5 votes vote down vote up
private void testPKCEMissingVerifier(CodeVerifierTransformer transformer, String tokenServiceAddress) {
    URL busFile = PublicClientTest.class.getResource("publicclient.xml");

    String address = "https://localhost:" + JCACHE_PORT + "/services/";
    WebClient client = WebClient.create(address, OAuth2TestUtils.setupProviders(),
                                        "alice", "security", busFile.toString());
    // Save the Cookie for the second request...
    WebClient.getConfig(client).getRequestContext().put(
        org.apache.cxf.message.Message.MAINTAIN_SESSION, Boolean.TRUE);

    // Get Authorization Code
    AuthorizationCodeParameters parameters = new AuthorizationCodeParameters();
    parameters.setConsumerId("consumer-id");
    String codeVerifier = Base64UrlUtility.encode(CryptoUtils.generateSecureRandomBytes(32));
    parameters.setCodeChallenge(transformer.transformCodeVerifier(codeVerifier));
    parameters.setCodeChallengeMethod(transformer.getChallengeMethod());
    parameters.setResponseType(OAuthConstants.CODE_RESPONSE_TYPE);
    parameters.setPath("authorize/");

    String location = OAuth2TestUtils.getLocation(client, parameters);
    String code = OAuth2TestUtils.getSubstring(location, "code");
    assertNotNull(code);

    // Now get the access token
    client = WebClient.create(tokenServiceAddress, busFile.toString());
    try {
        OAuth2TestUtils.getAccessTokenWithAuthorizationCode(client, code, "consumer-id", null);
        fail("Failure expected on a missing verifier");
    } catch (OAuthServiceException ex) {
        assertFalse(ex.getError().getError().isEmpty());
    }
}
 
Example 26
Source Project: cxf   Source File: PublicClientTest.java    License: Apache License 2.0 5 votes vote down vote up
private void testPKCEDifferentVerifier(CodeVerifierTransformer transformer, String tokenServiceAddress) {
    URL busFile = PublicClientTest.class.getResource("publicclient.xml");

    String address = "https://localhost:" + JCACHE_PORT + "/services/";
    WebClient client = WebClient.create(address, OAuth2TestUtils.setupProviders(),
                                        "alice", "security", busFile.toString());
    // Save the Cookie for the second request...
    WebClient.getConfig(client).getRequestContext().put(
        org.apache.cxf.message.Message.MAINTAIN_SESSION, Boolean.TRUE);

    // Get Authorization Code
    AuthorizationCodeParameters parameters = new AuthorizationCodeParameters();
    parameters.setConsumerId("consumer-id");
    String codeVerifier = Base64UrlUtility.encode(CryptoUtils.generateSecureRandomBytes(32));
    parameters.setCodeChallenge(transformer.transformCodeVerifier(codeVerifier));
    parameters.setCodeChallengeMethod(transformer.getChallengeMethod());
    parameters.setResponseType(OAuthConstants.CODE_RESPONSE_TYPE);
    parameters.setPath("authorize/");

    String location = OAuth2TestUtils.getLocation(client, parameters);
    String code = OAuth2TestUtils.getSubstring(location, "code");
    assertNotNull(code);

    // Now get the access token
    client = WebClient.create(tokenServiceAddress, busFile.toString());

    codeVerifier = Base64UrlUtility.encode(CryptoUtils.generateSecureRandomBytes(32));
    try {
        OAuth2TestUtils.getAccessTokenWithAuthorizationCode(client, code, "consumer-id", null, codeVerifier);
        fail("Failure expected on a different verifier");
    } catch (OAuthServiceException ex) {
        assertFalse(ex.getError().getError().isEmpty());
    }
}
 
Example 27
Source Project: cxf   Source File: JAXRSOAuth2Test.java    License: Apache License 2.0 5 votes vote down vote up
@Test()
public void testConfidentialClientIdOnly() throws Exception {
    String address = "https://localhost:" + port + "/oauth2/token";
    WebClient wc = createWebClient(address);

    try {
        OAuthClientUtils.getAccessToken(wc,
                                        new Consumer("fredNoPassword"),
                                        new CustomGrant(),
                                        false);
        fail("NotAuthorizedException exception is expected");
    } catch (OAuthServiceException ex) {
        assertEquals("invalid_client", ex.getError().getError());
    }
}
 
Example 28
Source Project: cxf   Source File: Saml2BearerGrantHandler.java    License: Apache License 2.0 5 votes vote down vote up
private InputStream decodeAssertion(String assertion) {
    try {
        byte[] deflatedToken = Base64UrlUtility.decode(assertion);
        return new ByteArrayInputStream(deflatedToken);
    } catch (Base64Exception ex) {
        throw new OAuthServiceException(OAuthConstants.INVALID_GRANT);
    }
}
 
Example 29
Source Project: cxf   Source File: Saml2BearerGrantHandler.java    License: Apache License 2.0 5 votes vote down vote up
protected Element readToken(InputStream tokenStream) {

        try {
            Document doc = StaxUtils.read(new InputStreamReader(tokenStream, StandardCharsets.UTF_8));
            return doc.getDocumentElement();
        } catch (Exception ex) {
            throw new OAuthServiceException(OAuthConstants.INVALID_GRANT);
        }
    }
 
Example 30
Source Project: cxf   Source File: AbstractSaml2BearerGrant.java    License: Apache License 2.0 5 votes vote down vote up
protected String encodeAssertion() {
    if (encoded) {
        return assertion;
    }

    try {
        return Base64UrlUtility.encode(assertion);
    } catch (Exception ex) {
        throw new OAuthServiceException(ex.getMessage(), ex);
    }
}