Search in sources :

Example 11 with OAuthPermission

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

the class CryptoUtilsTest method compareAccessTokens.

private void compareAccessTokens(ServerAccessToken token, ServerAccessToken token2) {
    assertEquals(token.getTokenKey(), token2.getTokenKey());
    assertEquals(token.getTokenType(), token2.getTokenType());
    assertEquals(token.getIssuedAt(), token2.getIssuedAt());
    assertEquals(token.getExpiresIn(), token2.getExpiresIn());
    Client regClient1 = token.getClient();
    Client regClient2 = token2.getClient();
    assertEquals(regClient1.getClientId(), regClient2.getClientId());
    assertNull(regClient2.getApplicationDescription());
    UserSubject endUser1 = token.getSubject();
    UserSubject endUser2 = token2.getSubject();
    assertEquals(endUser1.getLogin(), endUser2.getLogin());
    assertEquals(endUser1.getId(), endUser2.getId());
    assertEquals(endUser1.getRoles(), endUser2.getRoles());
    assertEquals(token.getRefreshToken(), token2.getRefreshToken());
    assertEquals(token.getAudiences(), token2.getAudiences());
    assertEquals(token.getGrantType(), token2.getGrantType());
    assertEquals(token.getParameters(), token2.getParameters());
    List<OAuthPermission> permissions = token.getScopes();
    List<OAuthPermission> permissions2 = token2.getScopes();
    assertEquals(1, permissions.size());
    assertEquals(1, permissions2.size());
    OAuthPermission perm1 = permissions.get(0);
    OAuthPermission perm2 = permissions2.get(0);
    assertEquals(perm1.getPermission(), perm2.getPermission());
    assertEquals(perm1.getDescription(), perm2.getDescription());
    RefreshToken refreshToken = ModelEncryptionSupport.decryptRefreshToken(p, token2.getRefreshToken(), p.key);
    assertEquals(1200L, refreshToken.getExpiresIn());
}
Also used : OAuthPermission(org.apache.cxf.rs.security.oauth2.common.OAuthPermission) RefreshToken(org.apache.cxf.rs.security.oauth2.tokens.refresh.RefreshToken) UserSubject(org.apache.cxf.rs.security.oauth2.common.UserSubject) Client(org.apache.cxf.rs.security.oauth2.common.Client)

Example 12 with OAuthPermission

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

the class OidcImplicitService method canAuthorizationBeSkipped.

@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;
}
Also used : OAuthError(org.apache.cxf.rs.security.oauth2.common.OAuthError) OAuthServiceException(org.apache.cxf.rs.security.oauth2.provider.OAuthServiceException)

Example 13 with OAuthPermission

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

the class OAuthDataProviderImpl method convertScopeToPermissions.

@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 ("read_book".equals(requestedScope)) {
            OAuthPermission permission = new OAuthPermission("read_book");
            permission.setHttpVerbs(Collections.singletonList("GET"));
            List<String> uris = new ArrayList<>();
            String partnerAddress = "/secured/bookstore/books/*";
            uris.add(partnerAddress);
            permission.setUris(uris);
            permissions.add(permission);
        } else if ("create_book".equals(requestedScope)) {
            OAuthPermission permission = new OAuthPermission("create_book");
            permission.setHttpVerbs(Collections.singletonList("POST"));
            List<String> uris = new ArrayList<>();
            String partnerAddress = "/secured/bookstore/books/*";
            uris.add(partnerAddress);
            permission.setUris(uris);
            permissions.add(permission);
        } else if ("create_image".equals(requestedScope)) {
            OAuthPermission permission = new OAuthPermission("create_image");
            permission.setHttpVerbs(Collections.singletonList("POST"));
            List<String> uris = new ArrayList<>();
            String partnerAddress = "/secured/bookstore/image/*";
            uris.add(partnerAddress);
            permission.setUris(uris);
            permissions.add(permission);
        } else if ("read_balance".equals(requestedScope)) {
            OAuthPermission permission = new OAuthPermission("read_balance");
            permission.setHttpVerbs(Collections.singletonList("GET"));
            List<String> uris = new ArrayList<>();
            String partnerAddress = "/partners/balance/*";
            uris.add(partnerAddress);
            permission.setUris(uris);
            permissions.add(permission);
        } else if ("create_balance".equals(requestedScope)) {
            OAuthPermission permission = new OAuthPermission("create_balance");
            permission.setHttpVerbs(Collections.singletonList("POST"));
            List<String> uris = new ArrayList<>();
            String partnerAddress = "/partners/balance/*";
            uris.add(partnerAddress);
            permission.setUris(uris);
            permissions.add(permission);
        } else if ("read_data".equals(requestedScope)) {
            OAuthPermission permission = new OAuthPermission("read_data");
            permission.setHttpVerbs(Collections.singletonList("GET"));
            List<String> uris = new ArrayList<>();
            String partnerAddress = "/partners/data/*";
            uris.add(partnerAddress);
            permission.setUris(uris);
            permissions.add(permission);
        } else if ("openid".equals(requestedScope)) {
            OAuthPermission permission = new OAuthPermission("openid", "Authenticate user");
            permissions.add(permission);
        } else {
            throw new OAuthServiceException("invalid_scope");
        }
    }
    return permissions;
}
Also used : OAuthPermission(org.apache.cxf.rs.security.oauth2.common.OAuthPermission) OAuthServiceException(org.apache.cxf.rs.security.oauth2.provider.OAuthServiceException) ArrayList(java.util.ArrayList) ArrayList(java.util.ArrayList) List(java.util.List)

Example 14 with OAuthPermission

use of org.apache.cxf.rs.security.oauth2.common.OAuthPermission 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 15 with OAuthPermission

use of org.apache.cxf.rs.security.oauth2.common.OAuthPermission 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)

Aggregations

OAuthPermission (org.apache.cxf.rs.security.oauth2.common.OAuthPermission)22 ServerAccessToken (org.apache.cxf.rs.security.oauth2.common.ServerAccessToken)8 LinkedList (java.util.LinkedList)6 Client (org.apache.cxf.rs.security.oauth2.common.Client)6 AccessTokenRegistration (org.apache.cxf.rs.security.oauth2.common.AccessTokenRegistration)4 OAuthAuthorizationData (org.apache.cxf.rs.security.oauth2.common.OAuthAuthorizationData)4 UserSubject (org.apache.cxf.rs.security.oauth2.common.UserSubject)4 OAuthServiceException (org.apache.cxf.rs.security.oauth2.provider.OAuthServiceException)4 RefreshToken (org.apache.cxf.rs.security.oauth2.tokens.refresh.RefreshToken)4 Test (org.junit.Test)4 ArrayList (java.util.ArrayList)3 AccessTokenValidation (org.apache.cxf.rs.security.oauth2.common.AccessTokenValidation)3 Instant (java.time.Instant)2 JwtClaims (org.apache.cxf.rs.security.jose.jwt.JwtClaims)2 OAuthContext (org.apache.cxf.rs.security.oauth2.common.OAuthContext)2 OAuthError (org.apache.cxf.rs.security.oauth2.common.OAuthError)2 BearerAccessToken (org.apache.cxf.rs.security.oauth2.tokens.bearer.BearerAccessToken)2 Ignore (org.junit.Ignore)2 X509Certificate (java.security.cert.X509Certificate)1 HashMap (java.util.HashMap)1