org.apache.cxf.rs.security.oauth2.common.Client Java Examples

The following examples show how to use org.apache.cxf.rs.security.oauth2.common.Client. 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 File: AuthorizationCodeGrantService.java    From cxf with Apache License 2.0 6 votes vote down vote up
protected AuthorizationCodeRegistration createCodeRegistration(OAuthRedirectionState state,
                                                               Client client,
                                                               List<String> requestedScope,
                                                               List<String> approvedScope,
                                                               UserSubject userSubject,
                                                               ServerAccessToken preauthorizedToken) {
    AuthorizationCodeRegistration codeReg = new AuthorizationCodeRegistration();
    codeReg.setPreauthorizedTokenAvailable(preauthorizedToken != null);
    codeReg.setClient(client);
    codeReg.setRedirectUri(state.getRedirectUri());
    codeReg.setRequestedScope(requestedScope);
    codeReg.setResponseType(state.getResponseType());
    codeReg.setApprovedScope(getApprovedScope(requestedScope, approvedScope));
    codeReg.setSubject(userSubject);
    codeReg.setAudience(state.getAudience());
    codeReg.setNonce(state.getNonce());
    codeReg.setClientCodeChallenge(state.getClientCodeChallenge());
    codeReg.getExtraProperties().putAll(state.getExtraProperties());
    return codeReg;
}
 
Example #2
Source File: AbstractOAuthDataProviderTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testAddGetDeleteAccessTokenWithNullSubject() {
    Client c = addClient("102", "bob");

    AccessTokenRegistration atr = new AccessTokenRegistration();
    atr.setClient(c);
    atr.setApprovedScope(Collections.singletonList("a"));
    atr.setSubject(null);

    getProvider().createAccessToken(atr);
    List<ServerAccessToken> tokens = getProvider().getAccessTokens(c, null);
    assertNotNull(tokens);
    assertEquals(1, tokens.size());
    validateAccessToken(tokens.get(0));

    getProvider().removeClient(c.getClientId());

    tokens = getProvider().getAccessTokens(c, null);
    assertNotNull(tokens);
    assertEquals(0, tokens.size());
}
 
Example #3
Source File: IdTokenResponseFilter.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Override
public String processJwt(JwtToken jwt, Client client) {
    if (keyServiceClient != null) {
        List<String> opers = new LinkedList<>();
        if (super.isJwsRequired()) {
            opers.add(JsonWebKey.KEY_OPER_SIGN);
        }
        if (super.isJweRequired()) {
            opers.add(JsonWebKey.KEY_OPER_ENCRYPT);
        }
        // the form request can be supported too
        keyServiceClient.resetQuery();
        keyServiceClient.query(JsonWebKey.KEY_OPERATIONS, opers);
        //TODO: OIDC core talks about various security algorithm preferences
        // that may be set during the client registrations, they can be passed along too
        return keyServiceClient.post(jwt, String.class);
    }
    return super.processJwt(jwt, client);
}
 
Example #4
Source File: OAuthServerJoseJwtProducer.java    From cxf with Apache License 2.0 6 votes vote down vote up
protected JweEncryptionProvider getInitializedEncryptionProvider(Client c) {
    JweEncryptionProvider theEncryptionProvider = null;
    if (encryptWithClientCertificates && c != null && !c.getApplicationCertificates().isEmpty()) {
        X509Certificate cert =
            (X509Certificate)CryptoUtils.decodeCertificate(c.getApplicationCertificates().get(0));
        theEncryptionProvider = JweUtils.createJweEncryptionProvider(cert.getPublicKey(),
                                                                     KeyAlgorithm.RSA_OAEP,
                                                                     ContentAlgorithm.A128GCM,
                                                                     null);
    }
    if (theEncryptionProvider == null && c != null && c.getClientSecret() != null) {
        theEncryptionProvider = super.getInitializedEncryptionProvider(c.getClientSecret());
    }
    return theEncryptionProvider;

}
 
Example #5
Source File: RedirectionBasedGrantService.java    From cxf with 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 #6
Source File: OidcHybridService.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Override
protected StringBuilder prepareRedirectResponse(OAuthRedirectionState state,
                               Client client,
                               List<String> requestedScope,
                               List<String> approvedScope,
                               UserSubject userSubject,
                               ServerAccessToken preAuthorizedToken) {
    ServerAuthorizationCodeGrant codeGrant = prepareHybrideCode(
        state, client, requestedScope, approvedScope, userSubject, preAuthorizedToken);

    StringBuilder sb = super.prepareRedirectResponse(state, client, requestedScope,
                                                      approvedScope, userSubject, preAuthorizedToken);

    if (codeGrant != null) {
        sb.append('&');
        sb.append(OAuthConstants.AUTHORIZATION_CODE_VALUE).append('=').append(codeGrant.getCode());
    }
    return sb;
}
 
Example #7
Source File: AbstractTokenService.java    From cxf with Apache License 2.0 6 votes vote down vote up
protected Client getClient(String clientId, String clientSecret, MultivaluedMap<String, String> params) {
    if (clientId == null) {
        reportInvalidRequestError("Client ID is null");
        return null;
    }
    Client client = null;
    try {
        client = getValidClient(clientId, clientSecret, params);
    } catch (OAuthServiceException ex) {
        LOG.warning("No valid client found for clientId: " + clientId);
        if (ex.getError() != null) {
            reportInvalidClient(ex.getError());
            return null;
        }
    }
    if (client == null) {
        LOG.warning("No valid client found for clientId: " + clientId);
        reportInvalidClient();
    }
    return client;
}
 
Example #8
Source File: ClientRegistrationService.java    From cxf-fediz with Apache License 2.0 6 votes vote down vote up
@POST
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
@Produces(MediaType.TEXT_HTML)
@Path("/{id}/remove")
public RegisteredClients removeClient(@PathParam("id") String id,
                                      @FormParam("client_csrfToken") String csrfToken) {
    // CSRF
    checkCSRFToken(csrfToken);
    checkSecurityContext();
    
    Collection<Client> clients = getClientRegistrations();
    for (Iterator<Client> it = clients.iterator(); it.hasNext();) {
        Client c = it.next();
        if (c.getClientId().equals(id)) {
            clientProvider.removeClient(id);
            it.remove();
            break;
        }
    }
    return new RegisteredClients(clients);
}
 
Example #9
Source File: AbstractGrantHandler.java    From cxf with Apache License 2.0 6 votes vote down vote up
protected ServerAccessToken doCreateAccessToken(Client client,
                                                UserSubject subject,
                                                String requestedGrant,
                                                List<String> requestedScopes,
                                                List<String> audiences) {
    ServerAccessToken token = getPreAuthorizedToken(client, subject, requestedGrant,
                                                    requestedScopes, audiences);
    if (token != null) {
        return token;
    }

    // Delegate to the data provider to create the one
    AccessTokenRegistration reg = new AccessTokenRegistration();
    reg.setClient(client);
    reg.setGrantType(requestedGrant);
    reg.setSubject(subject);
    reg.setRequestedScope(requestedScopes);
    reg.setApprovedScope(getApprovedScopes(client, subject, requestedScopes));
    reg.setAudiences(audiences);
    return dataProvider.createAccessToken(reg);
}
 
Example #10
Source File: JCacheCodeDataProviderTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Ignore
@Test
public void testAddGetDeleteCodeGrants2() {
    Client c = addClient("111", "bob");

    AuthorizationCodeRegistration atr = new AuthorizationCodeRegistration();
    atr.setClient(c);
    atr.setApprovedScope(Collections.singletonList("a"));
    atr.setSubject(c.getResourceOwnerSubject());

    provider.createCodeGrant(atr);

    List<ServerAuthorizationCodeGrant> grants = provider.getCodeGrants(c, c.getResourceOwnerSubject());
    assertNotNull(grants);
    assertEquals(1, grants.size());
    provider.removeClient(c.getClientId());
    grants = provider.getCodeGrants(c, c.getResourceOwnerSubject());
    assertNotNull(grants);
    assertEquals(0, grants.size());
}
 
Example #11
Source File: JPACodeDataProviderTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testAddGetDeleteCodeGrants2() {
    Client c = addClient("111", "bob");

    AuthorizationCodeRegistration atr = new AuthorizationCodeRegistration();
    atr.setClient(c);
    atr.setApprovedScope(Collections.singletonList("a"));
    atr.setSubject(c.getResourceOwnerSubject());

    getProvider().createCodeGrant(atr);

    List<ServerAuthorizationCodeGrant> grants = getProvider().getCodeGrants(c, c.getResourceOwnerSubject());
    assertNotNull(grants);
    assertEquals(1, grants.size());
    getProvider().removeClient(c.getClientId());
    grants = getProvider().getCodeGrants(c, c.getResourceOwnerSubject());
    assertNotNull(grants);
    assertEquals(0, grants.size());
}
 
Example #12
Source File: JPAOAuthDataProvider.java    From cxf with Apache License 2.0 6 votes vote down vote up
public void setClient(final Client client) {
    executeInTransaction(em -> {
        if (client.getResourceOwnerSubject() != null) {
            UserSubject sub =
                    em.find(UserSubject.class, client.getResourceOwnerSubject().getId());
            if (sub == null) {
                em.persist(client.getResourceOwnerSubject());
            } else {
                client.setResourceOwnerSubject(sub);
            }
        }
        boolean clientExists = em.createQuery("SELECT count(client) from Client client "
                        + "where client.clientId = :id", Long.class)
                .setParameter("id", client.getClientId())
                .getSingleResult() > 0;
        if (clientExists) {
            em.merge(client);
        } else {
            em.persist(client);
        }
        return null;
    });
}
 
Example #13
Source File: AbstractOAuthDataProvider.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Override
public ServerAccessToken getPreauthorizedToken(Client client,
                                               List<String> requestedScopes,
                                               UserSubject sub,
                                               String grantType) throws OAuthServiceException {
    if (!isSupportPreauthorizedTokens()) {
        return null;
    }

    ServerAccessToken token = null;
    for (ServerAccessToken at : getAccessTokens(client, sub)) {
        if (at.getClient().getClientId().equals(client.getClientId())
            && at.getGrantType().equals(grantType)
            && (sub == null && at.getSubject() == null
            || sub != null && at.getSubject().getLogin().equals(sub.getLogin()))) {
            if (!OAuthUtils.isExpired(at.getIssuedAt(), at.getExpiresIn())) {
                token = at;
            } else {
                revokeToken(client, at.getTokenKey(), OAuthConstants.ACCESS_TOKEN);
            }
            break;
        }
    }
    return token;

}
 
Example #14
Source File: AbstractCodeDataProvider.java    From cxf with Apache License 2.0 5 votes vote down vote up
public static boolean isCodeMatched(ServerAuthorizationCodeGrant grant, Client c, UserSubject sub) {
    if (grant != null && (c == null || grant.getClient().getClientId().equals(c.getClientId()))) {
        UserSubject grantSub = grant.getSubject();
        return sub == null || grantSub != null && grantSub.getLogin().equals(sub.getLogin());
    }
    return false;
}
 
Example #15
Source File: DynamicRegistrationService.java    From cxf with Apache License 2.0 5 votes vote down vote up
protected ClientRegistration fromClientToClientRegistration(Client c) {
    ClientRegistration reg = new ClientRegistration();
    reg.setClientName(c.getApplicationName());
    reg.setGrantTypes(c.getAllowedGrantTypes());
    reg.setApplicationType(c.isConfidential() ? "web" : "native");
    if (!c.getRedirectUris().isEmpty()) {
        reg.setRedirectUris(c.getRedirectUris());
    }
    if (!c.getRegisteredScopes().isEmpty()) {
        reg.setScope(OAuthUtils.convertListOfScopesToString(c.getRegisteredScopes()));
    }
    if (c.getApplicationWebUri() != null) {
        reg.setClientUri(c.getApplicationWebUri());
    }
    if (c.getApplicationLogoUri() != null) {
        reg.setLogoUri(c.getApplicationLogoUri());
    }
    if (!c.getRegisteredAudiences().isEmpty()) {
        reg.setResourceUris(c.getRegisteredAudiences());
    }
    if (c.getTokenEndpointAuthMethod() != null) {
        reg.setTokenEndpointAuthMethod(c.getTokenEndpointAuthMethod());
        if (OAuthConstants.TOKEN_ENDPOINT_AUTH_TLS.equals(c.getTokenEndpointAuthMethod())) {
            String subjectDn = c.getProperties().get(OAuthConstants.TLS_CLIENT_AUTH_SUBJECT_DN);
            if (subjectDn != null) {
                reg.setProperty(OAuthConstants.TLS_CLIENT_AUTH_SUBJECT_DN, subjectDn);
            }
            String issuerDn = c.getProperties().get(OAuthConstants.TLS_CLIENT_AUTH_ISSUER_DN);
            if (issuerDn != null) {
                reg.setProperty(OAuthConstants.TLS_CLIENT_AUTH_ISSUER_DN, issuerDn);
            }
        }
    }

    return reg;
}
 
Example #16
Source File: HawkAccessToken.java    From cxf with Apache License 2.0 5 votes vote down vote up
public HawkAccessToken(Client client,
                      HmacAlgorithm macAlgo,
                      long lifetime) {
    this(client,
         macAlgo,
         OAuthUtils.generateRandomTokenKey(),
         lifetime,
         OAuthUtils.getIssuedAt());
}
 
Example #17
Source File: AbstractImplicitGrantService.java    From cxf with Apache License 2.0 5 votes vote down vote up
protected Response createGrant(OAuthRedirectionState state,
                               Client client,
                               List<String> requestedScope,
                               List<String> approvedScope,
                               UserSubject userSubject,
                               ServerAccessToken preAuthorizedToken) {
    if (isFormResponse(state)) {
        return createHtmlResponse(prepareFormResponse(state, client, requestedScope,
                                        approvedScope, userSubject, preAuthorizedToken));
    }
    StringBuilder sb =
        prepareRedirectResponse(state, client, requestedScope, approvedScope, userSubject, preAuthorizedToken);
    return Response.seeOther(URI.create(sb.toString())).build();
}
 
Example #18
Source File: OidcAuthorizationCodeService.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Override
protected Response startAuthorization(MultivaluedMap<String, String> params,
                                      UserSubject userSubject,
                                      Client client,
                                      String redirectUri) {
    // Validate the prompt - if it contains "none" then an error is returned with any other value
    List<String> promptValues = OidcUtils.getPromptValues(params);
    if (promptValues != null && promptValues.size() > 1 && promptValues.contains(OidcUtils.PROMPT_NONE_VALUE)) {
        LOG.log(Level.FINE, "The prompt value {} is invalid", params.getFirst(OidcUtils.PROMPT_PARAMETER));
        return createErrorResponse(params, redirectUri, OAuthConstants.INVALID_REQUEST);
    }

    return super.startAuthorization(params, userSubject, client, redirectUri);
}
 
Example #19
Source File: OAuth2Provider.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
@Override
public ServerAccessToken getPreauthorizedToken(
    final Client client, final List<String> list, final UserSubject us, final String string)
    throws OAuthServiceException {

  return null;
}
 
Example #20
Source File: AuthorizationCodeGrantHandler.java    From cxf with Apache License 2.0 5 votes vote down vote up
private boolean compareCodeVerifierWithChallenge(Client c, String clientCodeVerifier,
                                                 String clientCodeChallenge) {
    if (clientCodeChallenge == null && clientCodeVerifier == null
        && (c.isConfidential() || !expectCodeVerifierForPublicClients)) {
        return true;
    } else if (clientCodeChallenge != null && clientCodeVerifier == null
        || clientCodeChallenge == null && clientCodeVerifier != null) {
        return false;
    } else {
        String transformedCodeVerifier = codeVerifierTransformer == null
            ? clientCodeVerifier : codeVerifierTransformer.transformCodeVerifier(clientCodeVerifier);
        return clientCodeChallenge.equals(transformedCodeVerifier);
    }
}
 
Example #21
Source File: RefreshToken.java    From cxf with Apache License 2.0 5 votes vote down vote up
public RefreshToken(Client client,
                    String tokenKey,
                    long lifetime,
                    long issuedAt) {
    super(client,
            OAuthConstants.REFRESH_TOKEN_TYPE,
            tokenKey,
            lifetime,
            issuedAt);
}
 
Example #22
Source File: AbstractOAuthDataProvider.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Override
public ServerAccessToken refreshAccessToken(Client client, String refreshTokenKey,
                                            List<String> restrictedScopes) throws OAuthServiceException {
    RefreshToken currentRefreshToken = recycleRefreshTokens
        ? revokeRefreshToken(client, refreshTokenKey) : getRefreshToken(refreshTokenKey);
    if (currentRefreshToken == null) {
        throw new OAuthServiceException(OAuthConstants.ACCESS_DENIED);
    }
    if (OAuthUtils.isExpired(currentRefreshToken.getIssuedAt(), currentRefreshToken.getExpiresIn())) {
        if (!recycleRefreshTokens) {
            revokeRefreshToken(client, refreshTokenKey);
        }
        throw new OAuthServiceException(OAuthConstants.ACCESS_DENIED);
    }
    if (recycleRefreshTokens) {
        revokeAccessTokens(client, currentRefreshToken);
    }

    ServerAccessToken at = doRefreshAccessToken(client, currentRefreshToken, restrictedScopes);
    saveAccessToken(at);
    if (recycleRefreshTokens) {
        createNewRefreshToken(at);
    } else {
        updateExistingRefreshToken(currentRefreshToken, at);
    }
    return at;
}
 
Example #23
Source File: DirectAuthorizationService.java    From cxf with Apache License 2.0 5 votes vote down vote up
@POST
@Consumes("application/x-www-form-urlencoded")
@Produces("text/html")
public Response authorize(MultivaluedMap<String, String> params) {
    SecurityContext sc = getAndValidateSecurityContext(params);
    Client client = getClient(params);
    // Create a UserSubject representing the end user
    UserSubject userSubject = createUserSubject(sc, params);


    AccessTokenRegistration reg = new AccessTokenRegistration();
    reg.setClient(client);
    reg.setGrantType(OAuthConstants.DIRECT_TOKEN_GRANT);
    reg.setSubject(userSubject);

    String providedScope = params.getFirst(OAuthConstants.SCOPE);
    List<String> requestedScope = OAuthUtils.getRequestedScopes(client,
                                                       providedScope,
                                                       useAllClientScopes,
                                                       partialMatchScopeValidation);

    reg.setRequestedScope(requestedScope);
    reg.setApprovedScope(requestedScope);
    ServerAccessToken token = getDataProvider().createAccessToken(reg);
    ClientAccessToken clientToken = OAuthUtils.toClientAccessToken(token, isWriteOptionalParameters());
    return Response.ok(clientToken).build();
}
 
Example #24
Source File: OAuth2TokenService.java    From openwebbeans-meecrowave with Apache License 2.0 5 votes vote down vote up
@Override // don't fail without a client
protected Client getClientFromBasicAuthScheme(final MultivaluedMap<String, String> params) {
    final List<String> authorization = getMessageContext().getHttpHeaders().getRequestHeader("Authorization");
    if (authorization == null || authorization.isEmpty()) {
        if (!configurer.getConfiguration().isForceClient()) {
            return DEFAULT_CLIENT;
        }
    }
    return super.getClientFromBasicAuthScheme(params);
}
 
Example #25
Source File: AbstractOAuthDataProviderTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testAddGetDeleteRefreshToken() {
    Client c = addClient("101", "bob");

    AccessTokenRegistration atr = new AccessTokenRegistration();
    atr.setClient(c);
    atr.setApprovedScope(Arrays.asList("a", "refreshToken"));
    atr.setSubject(c.getResourceOwnerSubject());

    ServerAccessToken at = getProvider().createAccessToken(atr);
    validateAccessToken(at);
    ServerAccessToken at2 = getProvider().getAccessToken(at.getTokenKey());
    validateAccessToken(at2);
    assertEquals(at.getTokenKey(), at2.getTokenKey());
    List<OAuthPermission> scopes = at2.getScopes();
    assertNotNull(scopes);
    assertEquals(2, scopes.size());
    OAuthPermission perm = scopes.get(0);
    assertEquals("a", perm.getPermission());
    OAuthPermission perm2 = scopes.get(1);
    assertEquals("refreshToken", perm2.getPermission());

    RefreshToken rt = getProvider().getRefreshToken(at2.getRefreshToken());
    assertNotNull(rt);
    assertEquals(at2.getTokenKey(), rt.getAccessTokens().get(0));

    List<RefreshToken> tokens = getProvider().getRefreshTokens(c, c.getResourceOwnerSubject());
    assertNotNull(tokens);
    assertEquals(1, tokens.size());
    assertEquals(rt.getTokenKey(), tokens.get(0).getTokenKey());

    getProvider().revokeToken(c, rt.getTokenKey(), OAuthConstants.REFRESH_TOKEN);

    assertNull(getProvider().getRefreshToken(rt.getTokenKey()));
}
 
Example #26
Source File: JPACodeDataProvider.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Override
public List<ServerAuthorizationCodeGrant> getCodeGrants(final Client c, final UserSubject subject)
        throws OAuthServiceException {
    return execute(em -> {
        return getCodeGrants(c, subject, em);
    });
}
 
Example #27
Source File: JCacheCodeDataProvider.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Override
protected void doRemoveClient(Client c) {
    for (ServerAuthorizationCodeGrant grant : getCodeGrants(c, null)) {
        removeCodeGrant(grant.getCode());
    }

    super.doRemoveClient(c);
}
 
Example #28
Source File: ServerAuthorizationCodeGrant.java    From cxf with Apache License 2.0 5 votes vote down vote up
public ServerAuthorizationCodeGrant(Client client,
                                    String code,
                                    long expiresIn,
                                    long issuedAt) {
    super(code);
    this.client = client;
    this.expiresIn = expiresIn;
    this.issuedAt = issuedAt;
}
 
Example #29
Source File: AbstractOAuthDataProvider.java    From cxf with Apache License 2.0 5 votes vote down vote up
protected void revokeAccessTokens(Client client, RefreshToken currentRefreshToken) {
    if (currentRefreshToken != null) {
        for (String accessTokenKey : currentRefreshToken.getAccessTokens()) {
            revokeAccessToken(client, accessTokenKey);
        }
    }
}
 
Example #30
Source File: AbstractOAuthDataProvider.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Override
public void revokeToken(Client client, String tokenKey, String tokenTypeHint) throws OAuthServiceException {
    ServerAccessToken accessToken = null;
    if (!OAuthConstants.REFRESH_TOKEN.equals(tokenTypeHint)) {
        accessToken = revokeAccessToken(client, tokenKey);
    }
    if (accessToken != null) {
        handleLinkedRefreshToken(client, accessToken);
    } else if (!OAuthConstants.ACCESS_TOKEN.equals(tokenTypeHint)) {
        RefreshToken currentRefreshToken = revokeRefreshToken(client, tokenKey);
        revokeAccessTokens(client, currentRefreshToken);
    }
}