Search in sources :

Example 6 with AccessTokenValidation

use of org.apache.cxf.rs.security.oauth2.common.AccessTokenValidation in project cxf by apache.

the class HawkAccessTokenValidatorTest method testValidateAccessToken.

@Test
public void testValidateAccessToken() throws Exception {
    HawkAccessToken macAccessToken = new HawkAccessToken(new Client("testClientId", "testClientSecret", true), HmacAlgorithm.HmacSHA256, -1);
    HttpServletRequest httpRequest = mockHttpRequest();
    UriInfo uriInfo = mockUriInfo();
    EasyMock.expect(dataProvider.getAccessToken(macAccessToken.getTokenKey())).andReturn(macAccessToken);
    EasyMock.expect(messageContext.getHttpServletRequest()).andReturn(httpRequest);
    EasyMock.expect(messageContext.getUriInfo()).andReturn(uriInfo);
    EasyMock.replay(dataProvider, messageContext, httpRequest, uriInfo);
    String authData = getClientAuthHeader(macAccessToken);
    AccessTokenValidation tokenValidation = validator.validateAccessToken(messageContext, OAuthConstants.HAWK_AUTHORIZATION_SCHEME, authData.split(" ")[1], null);
    assertNotNull(tokenValidation);
    EasyMock.verify(dataProvider, messageContext, httpRequest);
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) AccessTokenValidation(org.apache.cxf.rs.security.oauth2.common.AccessTokenValidation) Client(org.apache.cxf.rs.security.oauth2.common.Client) UriInfo(javax.ws.rs.core.UriInfo) Test(org.junit.Test)

Example 7 with AccessTokenValidation

use of org.apache.cxf.rs.security.oauth2.common.AccessTokenValidation in project cxf by apache.

the class AccessTokenIntrospectionClient 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.TOKEN_ID, authSchemeData);
    try {
        TokenIntrospection response = client.post(props, TokenIntrospection.class);
        return convertIntrospectionToValidation(response);
    } catch (WebApplicationException ex) {
        throw new OAuthServiceException(ex);
    }
}
Also used : TokenIntrospection(org.apache.cxf.rs.security.oauth2.common.TokenIntrospection) 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 8 with AccessTokenValidation

use of org.apache.cxf.rs.security.oauth2.common.AccessTokenValidation in project cxf by apache.

the class JwtAccessTokenValidator method convertClaimsToValidation.

private AccessTokenValidation convertClaimsToValidation(JwtClaims claims) {
    AccessTokenValidation atv = new AccessTokenValidation();
    atv.setInitialValidationSuccessful(true);
    String clientId = claims.getStringProperty(OAuthConstants.CLIENT_ID);
    if (clientId != null) {
        atv.setClientId(clientId);
    }
    if (claims.getIssuedAt() != null) {
        atv.setTokenIssuedAt(claims.getIssuedAt());
    } else {
        Instant now = Instant.now();
        atv.setTokenIssuedAt(now.toEpochMilli());
    }
    if (claims.getExpiryTime() != null) {
        atv.setTokenLifetime(claims.getExpiryTime() - atv.getTokenIssuedAt());
    }
    List<String> audiences = claims.getAudiences();
    if (audiences != null && !audiences.isEmpty()) {
        atv.setAudiences(claims.getAudiences());
    }
    if (claims.getIssuer() != null) {
        atv.setTokenIssuer(claims.getIssuer());
    }
    Object scope = claims.getClaim(OAuthConstants.SCOPE);
    if (scope != null) {
        String[] scopes = scope instanceof String ? scope.toString().split(" ") : CastUtils.cast((List<?>) scope).toArray(new String[] {});
        List<OAuthPermission> perms = new LinkedList<OAuthPermission>();
        for (String s : scopes) {
            if (!StringUtils.isEmpty(s)) {
                perms.add(new OAuthPermission(s.trim()));
            }
        }
        atv.setTokenScopes(perms);
    }
    String usernameClaimName = JwtTokenUtils.getClaimName(USERNAME_PROP, USERNAME_PROP, jwtAccessTokenClaimMap);
    String username = claims.getStringProperty(usernameClaimName);
    if (username != null) {
        UserSubject userSubject = new UserSubject(username);
        if (claims.getSubject() != null) {
            userSubject.setId(claims.getSubject());
        }
        atv.setTokenSubject(userSubject);
    } else if (claims.getSubject() != null) {
        atv.setTokenSubject(new UserSubject(claims.getSubject()));
    }
    Map<String, String> extraProperties = CastUtils.cast((Map<?, ?>) claims.getClaim("extra_properties"));
    if (extraProperties != null) {
        atv.getExtraProps().putAll(extraProperties);
    }
    Map<String, Object> cnfClaim = CastUtils.cast((Map<?, ?>) claims.getClaim(JwtConstants.CLAIM_CONFIRMATION));
    if (cnfClaim != null) {
        Object certCnf = cnfClaim.get(JoseConstants.HEADER_X509_THUMBPRINT_SHA256);
        if (certCnf != null) {
            atv.getExtraProps().put(JoseConstants.HEADER_X509_THUMBPRINT_SHA256, certCnf.toString());
        }
    }
    return atv;
}
Also used : OAuthPermission(org.apache.cxf.rs.security.oauth2.common.OAuthPermission) UserSubject(org.apache.cxf.rs.security.oauth2.common.UserSubject) Instant(java.time.Instant) AccessTokenValidation(org.apache.cxf.rs.security.oauth2.common.AccessTokenValidation) LinkedList(java.util.LinkedList)

Example 9 with AccessTokenValidation

use of org.apache.cxf.rs.security.oauth2.common.AccessTokenValidation in project cxf by apache.

the class OAuthRequestFilter method validateRequest.

protected void validateRequest(Message m) {
    if (isCorsRequest(m)) {
        return;
    }
    // Get the scheme and its data, Bearer only is supported by default
    // WWW-Authenticate with the list of supported schemes will be sent back
    // if the scheme is not accepted
    String[] authParts = getAuthorizationParts(m);
    if (authParts.length < 2) {
        throw ExceptionUtils.toForbiddenException(null, null);
    }
    String authScheme = authParts[0];
    String authSchemeData = authParts[1];
    // Get the access token
    AccessTokenValidation accessTokenV = getAccessTokenValidation(authScheme, authSchemeData, null);
    if (!accessTokenV.isInitialValidationSuccessful()) {
        AuthorizationUtils.throwAuthorizationFailure(supportedSchemes, realm);
    }
    // Check audiences
    String validAudience = validateAudiences(accessTokenV.getAudiences());
    // Check if token was issued by the supported issuer
    if (issuer != null && !issuer.equals(accessTokenV.getTokenIssuer())) {
        AuthorizationUtils.throwAuthorizationFailure(supportedSchemes, realm);
    }
    // Find the scopes which match the current request
    List<OAuthPermission> permissions = accessTokenV.getTokenScopes();
    List<OAuthPermission> matchingPermissions = new ArrayList<>();
    HttpServletRequest req = getMessageContext().getHttpServletRequest();
    for (OAuthPermission perm : permissions) {
        boolean uriOK = checkRequestURI(req, perm.getUris());
        boolean verbOK = checkHttpVerb(req, perm.getHttpVerbs());
        boolean scopeOk = checkScopeProperty(perm.getPermission());
        if (uriOK && verbOK && scopeOk) {
            matchingPermissions.add(perm);
        }
    }
    if (!permissions.isEmpty() && matchingPermissions.isEmpty() || allPermissionsMatch && (matchingPermissions.size() != permissions.size()) || !requiredScopes.isEmpty() && requiredScopes.size() != matchingPermissions.size()) {
        String message = "Client has no valid permissions";
        LOG.warning(message);
        throw ExceptionUtils.toForbiddenException(null, null);
    }
    if (accessTokenV.getClientIpAddress() != null) {
        String remoteAddress = getMessageContext().getHttpServletRequest().getRemoteAddr();
        if (remoteAddress == null || accessTokenV.getClientIpAddress().equals(remoteAddress)) {
            String message = "Client IP Address is invalid";
            LOG.warning(message);
            throw ExceptionUtils.toForbiddenException(null, null);
        }
    }
    if (blockPublicClients && !accessTokenV.isClientConfidential()) {
        String message = "Only Confidential Clients are supported";
        LOG.warning(message);
        throw ExceptionUtils.toForbiddenException(null, null);
    }
    if (am != null && !am.equals(accessTokenV.getTokenSubject().getAuthenticationMethod())) {
        String message = "The token has been authorized by the resource owner " + "using an unsupported authentication method";
        LOG.warning(message);
        throw ExceptionUtils.toNotAuthorizedException(null, null);
    }
    // Check Client Certificate Binding if any
    String certThumbprint = accessTokenV.getExtraProps().get(JoseConstants.HEADER_X509_THUMBPRINT_SHA256);
    if (certThumbprint != null) {
        TLSSessionInfo tlsInfo = getTlsSessionInfo();
        X509Certificate cert = tlsInfo == null ? null : OAuthUtils.getRootTLSCertificate(tlsInfo);
        if (cert == null || !OAuthUtils.compareCertificateThumbprints(cert, certThumbprint)) {
            throw ExceptionUtils.toNotAuthorizedException(null, null);
        }
    }
    // Create the security context and make it available on the message
    SecurityContext sc = createSecurityContext(req, accessTokenV);
    m.put(SecurityContext.class, sc);
    // Also set the OAuthContext
    OAuthContext oauthContext = new OAuthContext(accessTokenV.getTokenSubject(), accessTokenV.getClientSubject(), matchingPermissions, accessTokenV.getTokenGrantType());
    oauthContext.setClientId(accessTokenV.getClientId());
    oauthContext.setClientConfidential(accessTokenV.isClientConfidential());
    oauthContext.setTokenKey(accessTokenV.getTokenKey());
    oauthContext.setTokenAudience(validAudience);
    oauthContext.setTokenIssuer(accessTokenV.getTokenIssuer());
    oauthContext.setTokenRequestParts(authParts);
    oauthContext.setTokenExtraProperties(accessTokenV.getExtraProps());
    m.setContent(OAuthContext.class, oauthContext);
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) OAuthPermission(org.apache.cxf.rs.security.oauth2.common.OAuthPermission) ArrayList(java.util.ArrayList) SecurityContext(org.apache.cxf.security.SecurityContext) OAuthContext(org.apache.cxf.rs.security.oauth2.common.OAuthContext) AccessTokenValidation(org.apache.cxf.rs.security.oauth2.common.AccessTokenValidation) TLSSessionInfo(org.apache.cxf.security.transport.TLSSessionInfo) X509Certificate(java.security.cert.X509Certificate)

Example 10 with AccessTokenValidation

use of org.apache.cxf.rs.security.oauth2.common.AccessTokenValidation in project cxf by apache.

the class AbstractHawkAccessTokenValidator method validateAccessToken.

public AccessTokenValidation validateAccessToken(MessageContext mc, String authScheme, String authSchemeData, MultivaluedMap<String, String> extraProps) throws OAuthServiceException {
    Map<String, String> schemeParams = getSchemeParameters(authSchemeData);
    AccessTokenValidation atv = getAccessTokenValidation(mc, authScheme, authSchemeData, extraProps, schemeParams);
    if (isRemoteSignatureValidation()) {
        return atv;
    }
    String macKey = atv.getExtraProps().get(OAuthConstants.HAWK_TOKEN_KEY);
    String macAlgo = atv.getExtraProps().get(OAuthConstants.HAWK_TOKEN_ALGORITHM);
    HttpRequestProperties httpProps = null;
    if (extraProps != null && extraProps.containsKey(HTTP_VERB) && extraProps.containsKey(HTTP_URI)) {
        httpProps = new HttpRequestProperties(URI.create(extraProps.getFirst(HTTP_URI)), extraProps.getFirst(HTTP_VERB));
    } else {
        httpProps = new HttpRequestProperties(mc.getUriInfo().getRequestUri(), mc.getHttpServletRequest().getMethod());
    }
    HawkAuthorizationScheme macAuthInfo = new HawkAuthorizationScheme(httpProps, schemeParams);
    String normalizedString = macAuthInfo.getNormalizedRequestString();
    try {
        HmacAlgorithm hmacAlgo = HmacAlgorithm.toHmacAlgorithm(macAlgo);
        byte[] serverMacData = HmacUtils.computeHmac(macKey, hmacAlgo.getJavaName(), normalizedString);
        String clientMacString = schemeParams.get(OAuthConstants.HAWK_TOKEN_SIGNATURE);
        byte[] clientMacData = Base64Utility.decode(clientMacString);
        boolean validMac = MessageDigest.isEqual(serverMacData, clientMacData);
        if (!validMac) {
            AuthorizationUtils.throwAuthorizationFailure(Collections.singleton(OAuthConstants.HAWK_AUTHORIZATION_SCHEME));
        }
    } catch (Base64Exception e) {
        throw new OAuthServiceException(OAuthConstants.SERVER_ERROR, e);
    }
    validateTimestampNonce(macKey, macAuthInfo.getTimestamp(), macAuthInfo.getNonce());
    return atv;
}
Also used : OAuthServiceException(org.apache.cxf.rs.security.oauth2.provider.OAuthServiceException) HttpRequestProperties(org.apache.cxf.rs.security.oauth2.client.HttpRequestProperties) Base64Exception(org.apache.cxf.common.util.Base64Exception) AccessTokenValidation(org.apache.cxf.rs.security.oauth2.common.AccessTokenValidation)

Aggregations

AccessTokenValidation (org.apache.cxf.rs.security.oauth2.common.AccessTokenValidation)8 OAuthServiceException (org.apache.cxf.rs.security.oauth2.provider.OAuthServiceException)5 OAuthPermission (org.apache.cxf.rs.security.oauth2.common.OAuthPermission)3 UserSubject (org.apache.cxf.rs.security.oauth2.common.UserSubject)3 Instant (java.time.Instant)2 LinkedList (java.util.LinkedList)2 HttpServletRequest (javax.servlet.http.HttpServletRequest)2 WebApplicationException (javax.ws.rs.WebApplicationException)2 WebClient (org.apache.cxf.jaxrs.client.WebClient)2 MetadataMap (org.apache.cxf.jaxrs.impl.MetadataMap)2 ServerAccessToken (org.apache.cxf.rs.security.oauth2.common.ServerAccessToken)2 SecurityContext (org.apache.cxf.security.SecurityContext)2 X509Certificate (java.security.cert.X509Certificate)1 ArrayList (java.util.ArrayList)1 Consumes (javax.ws.rs.Consumes)1 NotAuthorizedException (javax.ws.rs.NotAuthorizedException)1 POST (javax.ws.rs.POST)1 Produces (javax.ws.rs.Produces)1 UriInfo (javax.ws.rs.core.UriInfo)1 SimplePrincipal (org.apache.cxf.common.security.SimplePrincipal)1