Java Code Examples for org.apache.cxf.rs.security.oauth2.utils.OAuthUtils

The following examples show how to use org.apache.cxf.rs.security.oauth2.utils.OAuthUtils. 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: BigQueryServer.java    License: Apache License 2.0 6 votes vote down vote up
private static ClientAccessToken getAccessToken(PrivateKey privateKey, String issuer) {
    JwsHeaders headers = new JwsHeaders(JoseType.JWT, SignatureAlgorithm.RS256);
    JwtClaims claims = new JwtClaims();
    claims.setIssuer(issuer);
    claims.setAudience("https://www.googleapis.com/oauth2/v3/token");

    long issuedAt = OAuthUtils.getIssuedAt();
    claims.setIssuedAt(issuedAt);
    claims.setExpiryTime(issuedAt + 60 * 60);
    claims.setProperty("scope", "https://www.googleapis.com/auth/bigquery.readonly");

    JwtToken token = new JwtToken(headers, claims);
    JwsJwtCompactProducer p = new JwsJwtCompactProducer(token);
    String base64UrlAssertion = p.signWith(privateKey);

    JwtBearerGrant grant = new JwtBearerGrant(base64UrlAssertion);

    WebClient accessTokenService = WebClient.create("https://www.googleapis.com/oauth2/v3/token",
                                                    Arrays.asList(new OAuthJSONProvider(),
                                                                  new AccessTokenGrantWriter()));
    WebClient.getConfig(accessTokenService).getInInterceptors().add(new LoggingInInterceptor());

    accessTokenService.type(MediaType.APPLICATION_FORM_URLENCODED).accept(MediaType.APPLICATION_JSON);

    return accessTokenService.post(grant, ClientAccessToken.class);
}
 
Example 2
Source Project: cxf   Source File: SubjectCreatorImpl.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public OidcUserSubject createUserSubject(MessageContext mc, MultivaluedMap<String, String> params) {
    OidcUserSubject oidcSub = new OidcUserSubject(OAuthUtils.createSubject(mc,
        (SecurityContext)mc.get(SecurityContext.class.getName())));

    final List<String> scopes;
    String requestedScope = params.getFirst(OAuthConstants.SCOPE);
    if (requestedScope != null && !requestedScope.isEmpty()) {
        scopes = OidcUtils.getScopeClaims(requestedScope.split(" "));
    } else {
        scopes = Collections.emptyList();
    }

    oidcSub.setIdToken(ID_TOKEN_PROVIDER.getIdToken(null, oidcSub, scopes));

    return oidcSub;
}
 
Example 3
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 4
Source Project: cxf   Source File: DirectAuthorizationService.java    License: Apache License 2.0 6 votes vote down vote up
protected UserSubject createUserSubject(SecurityContext securityContext,
                                        MultivaluedMap<String, String> params) {
    UserSubject subject = null;
    if (subjectCreator != null) {
        subject = subjectCreator.createUserSubject(getMessageContext(), params);
        if (subject != null) {
            return subject;
        }
    }

    subject = getMessageContext().getContent(UserSubject.class);
    if (subject != null) {
        return subject;
    }
    return OAuthUtils.createSubject(securityContext);
}
 
Example 5
Source Project: cxf   Source File: RedirectionBasedGrantService.java    License: Apache License 2.0 6 votes vote down vote up
private boolean compareRequestAndSessionTokens(String requestToken,
                                               MultivaluedMap<String, String> params,
                                               UserSubject subject) {
    final String sessionToken;
    if (this.sessionAuthenticityTokenProvider != null) {
        sessionToken = sessionAuthenticityTokenProvider.removeSessionToken(getMessageContext(),
                                                                           params,
                                                                           subject);
    } else {
        sessionToken = OAuthUtils.getSessionToken(getMessageContext());
    }
    if (StringUtils.isEmpty(sessionToken)) {
        return false;
    }
    return requestToken.equals(sessionToken);
}
 
Example 6
Source Project: cxf   Source File: AbstractTokenService.java    License: Apache License 2.0 6 votes vote down vote up
protected void checkCertificateBinding(Client client, TLSSessionInfo tlsSessionInfo) {
    String subjectDn = client.getProperties().get(OAuthConstants.TLS_CLIENT_AUTH_SUBJECT_DN);
    if (subjectDn == null && client.getApplicationCertificates().isEmpty()) {
        LOG.warning("Client \"" + client.getClientId() + "\" can not be bound to the TLS certificate");
        reportInvalidClient();
    }
    X509Certificate cert = OAuthUtils.getRootTLSCertificate(tlsSessionInfo);

    if (subjectDn != null
        && !subjectDn.equals(OAuthUtils.getSubjectDnFromTLSCertificates(cert))) {
        LOG.warning("Client \"" + client.getClientId() + "\" can not be bound to the TLS certificate");
        reportInvalidClient();
    }
    String issuerDn = client.getProperties().get(OAuthConstants.TLS_CLIENT_AUTH_ISSUER_DN);
    if (issuerDn != null
        && !issuerDn.equals(OAuthUtils.getIssuerDnFromTLSCertificates(cert))) {
        LOG.warning("Client \"" + client.getClientId() + "\" can not be bound to the TLS certificate");
        reportInvalidClient();
    }
    if (!client.getApplicationCertificates().isEmpty()) {
        compareTlsCertificates(tlsSessionInfo, client.getApplicationCertificates());
    }
    OAuthUtils.setCertificateThumbprintConfirmation(getMessageContext(), cert);
}
 
Example 7
Source Project: cxf   Source File: AbstractTokenService.java    License: Apache License 2.0 6 votes vote down vote up
protected Client getClientFromTLSCertificates(SecurityContext sc,
                                              TLSSessionInfo tlsSessionInfo,
                                              MultivaluedMap<String, String> params) {
    Client client = null;
    if (OAuthUtils.isMutualTls(sc, tlsSessionInfo)) {
        X509Certificate cert = OAuthUtils.getRootTLSCertificate(tlsSessionInfo);
        String subjectDn = OAuthUtils.getSubjectDnFromTLSCertificates(cert);
        if (!StringUtils.isEmpty(subjectDn)) {
            client = getClient(subjectDn, params);
            validateClientAuthenticationMethod(client, OAuthConstants.TOKEN_ENDPOINT_AUTH_TLS);
            // The certificates must be registered with the client and match TLS certificates
            // in case of the binding where Client's clientId is a subject distinguished name
            compareTlsCertificates(tlsSessionInfo, client.getApplicationCertificates());
            OAuthUtils.setCertificateThumbprintConfirmation(getMessageContext(), cert);
        }
    }
    return client;
}
 
Example 8
Source Project: cxf   Source File: AbstractImplicitGrantService.java    License: Apache License 2.0 6 votes vote down vote up
protected ClientAccessToken getClientAccessToken(OAuthRedirectionState state,
                                                 Client client,
                                                 List<String> requestedScope,
                                                 List<String> approvedScope,
                                                 UserSubject userSubject,
                                                 ServerAccessToken preAuthorizedToken) {

    ServerAccessToken token = null;
    if (preAuthorizedToken == null) {
        AccessTokenRegistration reg = createTokenRegistration(state,
                                                              client,
                                                              requestedScope,
                                                              approvedScope,
                                                              userSubject);
        token = getDataProvider().createAccessToken(reg);
    } else {
        token = preAuthorizedToken;
        if (state.getNonce() != null) {
            JAXRSUtils.getCurrentMessage().getExchange().put(OAuthConstants.NONCE, state.getNonce());
        }
    }

    ClientAccessToken clientToken = OAuthUtils.toClientAccessToken(token, isWriteOptionalParameters());
    processClientAccessToken(clientToken, token);
    return clientToken;
}
 
Example 9
Source Project: cxf   Source File: MemoryClientCodeStateManager.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public MultivaluedMap<String, String> toRedirectState(MessageContext mc,
                                                      MultivaluedMap<String, String> requestState) {
    String stateParam = OAuthUtils.generateRandomTokenKey();
    MultivaluedMap<String, String> redirectMap = new MetadataMap<>();

    if (generateNonce) {
        String nonceParam = MessageDigestUtils.generate(CryptoUtils.generateSecureRandomBytes(32));
        requestState.putSingle(OAuthConstants.NONCE, nonceParam);
        redirectMap.putSingle(OAuthConstants.NONCE, nonceParam);
    }
    map.put(stateParam, requestState);
    OAuthUtils.setSessionToken(mc, stateParam, "state", 0);
    redirectMap.putSingle(OAuthConstants.STATE, stateParam);
    return redirectMap;
}
 
Example 10
Source Project: cxf   Source File: JoseClientCodeStateManager.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public MultivaluedMap<String, String> fromRedirectState(MessageContext mc,
                                                        MultivaluedMap<String, String> redirectState) {

    String stateParam = redirectState.getFirst(OAuthConstants.STATE);

    if (storeInSession) {
        stateParam = OAuthUtils.getSessionToken(mc, stateParam);
    }

    JweDecryptionProvider jwe = getInitializedDecryptionProvider();
    if (jwe != null) {
        stateParam = jwe.decrypt(stateParam).getContentText();
    }
    JwsCompactConsumer jws = new JwsCompactConsumer(stateParam);
    JwsSignatureVerifier theSigVerifier = getInitializedSigVerifier();
    if (!jws.verifySignatureWith(theSigVerifier)) {
        throw new SecurityException();
    }
    String json = jws.getUnsignedEncodedSequence();
    //CHECKSTYLE:OFF
    Map<String, List<String>> map = CastUtils.cast((Map<?, ?>)jsonp.fromJson(json));
    return (MultivaluedMap<String, String>)map; //NOPMD
    //CHECKSTYLE:ON
}
 
Example 11
Source Project: cxf   Source File: AbstractOAuthDataProvider.java    License: 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 12
Source Project: cxf   Source File: OAuthRequestFilter.java    License: Apache License 2.0 6 votes vote down vote up
protected boolean checkRequestURI(HttpServletRequest request, List<String> uris, Message m) {

        if (uris.isEmpty()) {
            return true;
        }
        String servletPath = request.getPathInfo();
        if (servletPath == null) {
            servletPath = (String)m.get(Message.PATH_INFO);
        }
        boolean foundValidScope = false;
        for (String uri : uris) {
            if (OAuthUtils.checkRequestURI(servletPath, uri)) {
                foundValidScope = true;
                break;
            }
        }
        if (!foundValidScope) {
            String message = "Invalid request URI: " + request.getRequestURL().toString();
            LOG.fine(message);
        }
        return foundValidScope;
    }
 
Example 13
Source Project: cxf   Source File: OidcImplicitService.java    License: Apache License 2.0 6 votes vote down vote up
protected String processIdToken(OAuthRedirectionState state, IdToken idToken) {
    OAuthJoseJwtProducer processor = idTokenHandler == null ? new OAuthJoseJwtProducer() : idTokenHandler;

    String code =
        (String)JAXRSUtils.getCurrentMessage().getExchange().get(OAuthConstants.AUTHORIZATION_CODE_VALUE);
    if (code != null) {
        // this service is invoked as part of the hybrid flow
        Properties props = JwsUtils.loadSignatureOutProperties(false);
        SignatureAlgorithm sigAlgo = null;
        if (processor.isSignWithClientSecret()) {
            sigAlgo = OAuthUtils.getClientSecretSignatureAlgorithm(props);
        } else {
            sigAlgo = JwsUtils.getSignatureAlgorithm(props, SignatureAlgorithm.RS256);
        }
        idToken.setAuthorizationCodeHash(OidcUtils.calculateAuthorizationCodeHash(code, sigAlgo));
    }

    idToken.setNonce(state.getNonce());
    return processor.processJwt(new JwtToken(idToken));
}
 
Example 14
Source Project: g-suite-identity-sync   Source File: TokenCache.java    License: Apache License 2.0 5 votes vote down vote up
private ClientAccessToken getAccessToken() throws NoPrivateKeyException {
    JwsHeaders headers = new JwsHeaders(JoseType.JWT, SignatureAlgorithm.RS256);
    JwtClaims claims = new JwtClaims();
    claims.setIssuer(config.getServiceAccountEmail());
    claims.setAudience(config.getServiceAccountTokenUri());
    claims.setSubject(config.getServiceAccountSubject());

    long issuedAt = OAuthUtils.getIssuedAt();
    long tokenTimeout = config.getServiceAccountTokenLifetime();
    claims.setIssuedAt(issuedAt);
    claims.setExpiryTime(issuedAt + tokenTimeout);
    String scopes = String.join(" ", config.getServiceAccountScopes());
    claims.setProperty("scope", scopes);

    JwtToken token = new JwtToken(headers, claims);
    JwsJwtCompactProducer p = new JwsJwtCompactProducer(token);
    String base64UrlAssertion = p.signWith(config.readServiceAccountKey());

    JwtBearerGrant grant = new JwtBearerGrant(base64UrlAssertion);

    WebClient accessTokenService = WebClient.create(config.getServiceAccountTokenUri(),
            Arrays.asList(new OAuthJSONProvider(), new AccessTokenGrantWriter()));

    accessTokenService.type(MediaType.APPLICATION_FORM_URLENCODED).accept(MediaType.APPLICATION_JSON);

    return accessTokenService.post(grant, ClientAccessToken.class);
}
 
Example 15
Source Project: cxf   Source File: IdTokenProviderImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public IdToken getIdToken(String clientId, UserSubject authenticatedUser, List<String> scopes) {
    IdToken token = new IdToken();

    token.setIssuedAt(OAuthUtils.getIssuedAt());
    token.setExpiryTime(token.getIssuedAt() + 60L);
    token.setAudience(clientId);
    token.setSubject(authenticatedUser.getLogin());
    token.setIssuer("OIDC IdP");

    return token;
}
 
Example 16
Source Project: cxf   Source File: AuthorizationCodeGrantHandler.java    License: Apache License 2.0 5 votes vote down vote up
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 (!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);
}
 
Example 17
Source Project: cxf   Source File: AbstractGrantHandler.java    License: Apache License 2.0 5 votes vote down vote up
protected ServerAccessToken doCreateAccessToken(Client client,
                                                UserSubject subject,
                                                MultivaluedMap<String, String> params) {

    return doCreateAccessToken(client,
                               subject,
                               OAuthUtils.parseScope(params.getFirst(OAuthConstants.SCOPE)),
                               getAudiences(client, params.getFirst(OAuthConstants.CLIENT_AUDIENCE)));
}
 
Example 18
Source Project: cxf   Source File: AbstractGrantHandler.java    License: Apache License 2.0 5 votes vote down vote up
protected List<String> getAudiences(Client client, String clientAudience) {
    if (client.getRegisteredAudiences().isEmpty() && clientAudience == null) {
        return Collections.emptyList();
    }
    if (clientAudience != null) {
        List<String> audiences = Collections.singletonList(clientAudience);
        if (!OAuthUtils.validateAudiences(audiences, client.getRegisteredAudiences())) {
            throw new OAuthServiceException(OAuthConstants.INVALID_GRANT);
        }
        return audiences;
    }
    return client.getRegisteredAudiences();
}
 
Example 19
Source Project: cxf   Source File: RefreshTokenGrantHandler.java    License: Apache License 2.0 5 votes vote down vote up
public ServerAccessToken createAccessToken(Client client, MultivaluedMap<String, String> params)
    throws OAuthServiceException {
    String refreshToken = params.getFirst(OAuthConstants.REFRESH_TOKEN);
    List<String> requestedScopes = OAuthUtils.getRequestedScopes(client,
                                        params.getFirst(OAuthConstants.SCOPE),
                                        useAllClientScopes,
                                        partialMatchScopeValidation);
    final ServerAccessToken st = dataProvider.refreshAccessToken(client, refreshToken, requestedScopes);
    st.setGrantType(OAuthConstants.REFRESH_TOKEN_GRANT);
    return st;
}
 
Example 20
Source Project: cxf   Source File: DirectAuthorizationService.java    License: 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 21
Source Project: cxf   Source File: DynamicRegistrationService.java    License: 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 22
Source Project: cxf   Source File: RedirectionBasedGrantService.java    License: Apache License 2.0 5 votes vote down vote up
protected UserSubject createUserSubject(SecurityContext securityContext,
                                        MultivaluedMap<String, String> params) {
    if (subjectCreator != null) {
        UserSubject subject = subjectCreator.createUserSubject(getMessageContext(),
                                                   params);
        if (subject != null) {
            return subject;
        }
    }
    return OAuthUtils.createSubject(getMessageContext(), securityContext);
}
 
Example 23
Source Project: cxf   Source File: RedirectionBasedGrantService.java    License: Apache License 2.0 5 votes vote down vote up
private void addAuthenticityTokenToSession(OAuthAuthorizationData secData,
                                           MultivaluedMap<String, String> params,
                                           UserSubject subject) {
    final String sessionToken;
    if (this.sessionAuthenticityTokenProvider != null) {
        sessionToken = sessionAuthenticityTokenProvider.createSessionToken(getMessageContext(),
                                                                           params,
                                                                           subject,
                                                                           secData);
    } else {
        sessionToken = OAuthUtils.setSessionToken(getMessageContext(), maxDefaultSessionInterval);
    }
    secData.setAuthenticityToken(sessionToken);
}
 
Example 24
Source Project: cxf   Source File: AccessTokenService.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected void injectContextIntoOAuthProviders() {
    super.injectContextIntoOAuthProviders();
    for (AccessTokenGrantHandler grantHandler : grantHandlers) {
        OAuthUtils.injectContextIntoOAuthProvider(getMessageContext(), grantHandler);
    }
}
 
Example 25
Source Project: cxf   Source File: AccessTokenService.java    License: Apache License 2.0 5 votes vote down vote up
protected void checkAudience(Client c, MultivaluedMap<String, String> params) {
    String audienceParam = params.getFirst(OAuthConstants.CLIENT_AUDIENCE);
    if (!OAuthUtils.validateAudience(audienceParam, c.getRegisteredAudiences())) {
        LOG.log(Level.FINE, "Error validating the audience parameter. Supplied audience {0} "
                + "does not match with the registered audiences {1}",
                new Object[] {audienceParam, c.getRegisteredAudiences() });
        throw new OAuthServiceException(new OAuthError(OAuthConstants.ACCESS_DENIED));
    }

}
 
Example 26
Source Project: cxf   Source File: BearerAuthSupplier.java    License: Apache License 2.0 5 votes vote down vote up
private void refreshAccessTokenIfExpired(AuthorizationPolicy authPolicy) {
    ClientAccessToken at = getClientAccessToken();
    if (OAuthUtils.isExpired(at.getIssuedAt(),
                             at.getExpiresIn())) {
        refreshAccessToken(authPolicy);
    }

}
 
Example 27
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 28
Source Project: cxf   Source File: MemoryClientTokenContextManager.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void setClientTokenContext(MessageContext mc, ClientTokenContext request) {
    String key = getKey(mc, false);
    if (key == null) {
        key = OAuthUtils.generateRandomTokenKey();
        OAuthUtils.setSessionToken(mc, key, "org.apache.cxf.websso.context", 0);
    }
    map.put(key, request);

}
 
Example 29
Source Project: cxf   Source File: ClientCodeRequestFilter.java    License: Apache License 2.0 5 votes vote down vote up
private ClientAccessToken refreshAccessTokenIfExpired(ClientAccessToken at) {
    if (at.getRefreshToken() != null
        && ((expiryThreshold > 0 && OAuthUtils.isExpired(at.getIssuedAt(), at.getExpiresIn() - expiryThreshold))
        || OAuthUtils.isExpired(at.getIssuedAt(), at.getExpiresIn()))) {
        return OAuthClientUtils.refreshAccessToken(accessTokenServiceClient, consumer, at);
    }
    return null;
}
 
Example 30
Source Project: cxf   Source File: JoseClientCodeStateManager.java    License: Apache License 2.0 5 votes vote down vote up
@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<>();

    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;
}