Search in sources :

Example 11 with UserSubject

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

the class AuthorizationCodeGrantService method createAuthorizationData.

@Override
protected OAuthAuthorizationData createAuthorizationData(Client client, MultivaluedMap<String, String> params, String redirectUri, UserSubject subject, List<OAuthPermission> requestedPerms, List<OAuthPermission> alreadyAuthorizedPerms, boolean authorizationCanBeSkipped) {
    OAuthAuthorizationData data = super.createAuthorizationData(client, params, redirectUri, subject, requestedPerms, alreadyAuthorizedPerms, authorizationCanBeSkipped);
    setCodeChallenge(data, params);
    return data;
}
Also used : OAuthAuthorizationData(org.apache.cxf.rs.security.oauth2.common.OAuthAuthorizationData)

Example 12 with UserSubject

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

the class DynamicRegistrationService method createNewClient.

protected Client createNewClient(ClientRegistration request) {
    // Client ID
    String clientId = generateClientId();
    // Client Name
    String clientName = request.getClientName();
    if (StringUtils.isEmpty(clientName)) {
        clientName = clientId;
    }
    List<String> grantTypes = request.getGrantTypes();
    if (grantTypes == null) {
        grantTypes = Collections.singletonList(OAuthConstants.AUTHORIZATION_CODE_GRANT);
    }
    String tokenEndpointAuthMethod = request.getTokenEndpointAuthMethod();
    // TODO: default is expected to be set to OAuthConstants.TOKEN_ENDPOINT_AUTH_BASIC
    boolean passwordRequired = isPasswordRequired(grantTypes, tokenEndpointAuthMethod);
    // Application Type
    // https://tools.ietf.org/html/rfc7591 has no this property but
    // but http://openid.net/specs/openid-connect-registration-1_0.html#ClientMetadata does
    String appType = request.getApplicationType();
    if (appType == null) {
        appType = DEFAULT_APPLICATION_TYPE;
    }
    boolean isConfidential = DEFAULT_APPLICATION_TYPE.equals(appType) && (passwordRequired || OAuthConstants.TOKEN_ENDPOINT_AUTH_TLS.equals(tokenEndpointAuthMethod));
    // Client Secret
    String clientSecret = passwordRequired ? generateClientSecret(request) : null;
    Client newClient = new Client(clientId, clientSecret, isConfidential, clientName);
    newClient.setAllowedGrantTypes(grantTypes);
    newClient.setTokenEndpointAuthMethod(tokenEndpointAuthMethod);
    if (OAuthConstants.TOKEN_ENDPOINT_AUTH_TLS.equals(tokenEndpointAuthMethod)) {
        String subjectDn = (String) request.getProperty(OAuthConstants.TLS_CLIENT_AUTH_SUBJECT_DN);
        if (subjectDn != null) {
            newClient.getProperties().put(OAuthConstants.TLS_CLIENT_AUTH_SUBJECT_DN, subjectDn);
        }
        String issuerDn = (String) request.getProperty(OAuthConstants.TLS_CLIENT_AUTH_ISSUER_DN);
        if (issuerDn != null) {
            newClient.getProperties().put(OAuthConstants.TLS_CLIENT_AUTH_ISSUER_DN, issuerDn);
        }
    }
    // Client Registration Time
    newClient.setRegisteredAt(System.currentTimeMillis() / 1000);
    // Client Redirect URIs
    List<String> redirectUris = request.getRedirectUris();
    if (redirectUris != null) {
        for (String uri : redirectUris) {
            validateRequestUri(uri, appType, grantTypes);
        }
        newClient.setRedirectUris(redirectUris);
    }
    // Client Resource Audience URIs
    List<String> resourceUris = request.getResourceUris();
    if (resourceUris != null) {
        newClient.setRegisteredAudiences(resourceUris);
    }
    // Client Scopes
    String scope = request.getScope();
    if (!StringUtils.isEmpty(scope)) {
        newClient.setRegisteredScopes(OAuthUtils.parseScope(scope));
    }
    // Client Application URI
    String clientUri = request.getClientUri();
    if (clientUri != null) {
        newClient.setApplicationWebUri(clientUri);
    }
    // Client Logo URI
    String clientLogoUri = request.getLogoUri();
    if (clientLogoUri != null) {
        newClient.setApplicationLogoUri(clientLogoUri);
    }
    // TODO: check other properties
    // Add more typed properties like tosUri, policyUri, etc to Client
    // or set them as Client extra properties
    SecurityContext sc = mc.getSecurityContext();
    if (sc != null && sc.getUserPrincipal() != null && sc.getUserPrincipal().getName() != null) {
        UserSubject subject = new UserSubject(sc.getUserPrincipal().getName());
        newClient.setResourceOwnerSubject(subject);
    }
    newClient.setRegisteredDynamically(true);
    return newClient;
}
Also used : UserSubject(org.apache.cxf.rs.security.oauth2.common.UserSubject) SecurityContext(javax.ws.rs.core.SecurityContext) Client(org.apache.cxf.rs.security.oauth2.common.Client)

Example 13 with UserSubject

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

the class RedirectionBasedGrantService method startAuthorization.

protected Response startAuthorization(MultivaluedMap<String, String> params, UserSubject userSubject, Client client, String redirectUri) {
    // Enforce the client confidentiality requirements
    if (!OAuthUtils.isGrantSupportedForClient(client, canSupportPublicClient(client), supportedGrantType)) {
        LOG.fine("The grant type is not supported");
        return createErrorResponse(params, redirectUri, OAuthConstants.UNAUTHORIZED_CLIENT);
    }
    // Check response_type
    String responseType = params.getFirst(OAuthConstants.RESPONSE_TYPE);
    if (responseType == null || !getSupportedResponseTypes().contains(responseType)) {
        LOG.fine("The response type is null or not supported");
        return createErrorResponse(params, redirectUri, OAuthConstants.UNSUPPORTED_RESPONSE_TYPE);
    }
    // Get the requested scopes
    String providedScope = params.getFirst(OAuthConstants.SCOPE);
    List<String> requestedScope = null;
    List<OAuthPermission> requestedPermissions = null;
    try {
        requestedScope = OAuthUtils.getRequestedScopes(client, providedScope, useAllClientScopes, partialMatchScopeValidation);
        requestedPermissions = getDataProvider().convertScopeToPermissions(client, requestedScope);
    } catch (OAuthServiceException ex) {
        LOG.log(Level.FINE, "Error processing scopes", ex);
        return createErrorResponse(params, redirectUri, OAuthConstants.INVALID_SCOPE);
    }
    // Validate the audience
    String clientAudience = params.getFirst(OAuthConstants.CLIENT_AUDIENCE);
    // in the list of Client audiences set at the Client registration time.
    if (!OAuthUtils.validateAudience(clientAudience, client.getRegisteredAudiences())) {
        LOG.fine("Error validating audience parameter");
        return createErrorResponse(params, redirectUri, OAuthConstants.INVALID_REQUEST);
    }
    // Request a new grant only if no pre-authorized token is available
    ServerAccessToken preAuthorizedToken = null;
    if (canAccessTokenBeReturned(responseType)) {
        preAuthorizedToken = getDataProvider().getPreauthorizedToken(client, requestedScope, userSubject, supportedGrantType);
    }
    List<OAuthPermission> alreadyAuthorizedPerms = null;
    boolean preAuthorizationComplete = false;
    if (preAuthorizedToken != null) {
        alreadyAuthorizedPerms = preAuthorizedToken.getScopes();
        preAuthorizationComplete = OAuthUtils.convertPermissionsToScopeList(alreadyAuthorizedPerms).containsAll(requestedScope);
    }
    Response finalResponse = null;
    try {
        final boolean authorizationCanBeSkipped = preAuthorizationComplete || canAuthorizationBeSkipped(params, client, userSubject, requestedScope, requestedPermissions);
        // Populate the authorization challenge data
        OAuthAuthorizationData data = createAuthorizationData(client, params, redirectUri, userSubject, requestedPermissions, alreadyAuthorizedPerms, authorizationCanBeSkipped);
        if (authorizationCanBeSkipped) {
            getMessageContext().put(AUTHORIZATION_REQUEST_PARAMETERS, params);
            List<OAuthPermission> approvedScopes = preAuthorizationComplete ? preAuthorizedToken.getScopes() : requestedPermissions;
            finalResponse = createGrant(data, client, requestedScope, OAuthUtils.convertPermissionsToScopeList(approvedScopes), userSubject, preAuthorizedToken);
        } else {
            if (preAuthorizedToken != null) {
                data.setPreauthorizedTokenKey(preAuthorizedToken.getTokenKey());
            }
            finalResponse = Response.ok(data).build();
        }
    } catch (OAuthServiceException ex) {
        finalResponse = createErrorResponse(params, redirectUri, ex.getError().getError());
    }
    return finalResponse;
}
Also used : Response(javax.ws.rs.core.Response) OAuthPermission(org.apache.cxf.rs.security.oauth2.common.OAuthPermission) ServerAccessToken(org.apache.cxf.rs.security.oauth2.common.ServerAccessToken) OAuthServiceException(org.apache.cxf.rs.security.oauth2.provider.OAuthServiceException) OAuthAuthorizationData(org.apache.cxf.rs.security.oauth2.common.OAuthAuthorizationData)

Example 14 with UserSubject

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

the class RedirectionBasedGrantService method startAuthorization.

/**
 * Starts the authorization process
 */
protected Response startAuthorization(MultivaluedMap<String, String> params) {
    // Make sure the end user has authenticated, check if HTTPS is used
    SecurityContext sc = getAndValidateSecurityContext(params);
    Client client = getClient(params.getFirst(OAuthConstants.CLIENT_ID), params);
    // Create a UserSubject representing the end user
    UserSubject userSubject = createUserSubject(sc, params);
    if (authorizationFilter != null) {
        params = authorizationFilter.process(params, userSubject, client);
    }
    // Validate the provided request URI, if any, against the ones Client provided
    // during the registration
    String redirectUri = validateRedirectUri(client, params.getFirst(OAuthConstants.REDIRECT_URI));
    return startAuthorization(params, userSubject, client, redirectUri);
}
Also used : UserSubject(org.apache.cxf.rs.security.oauth2.common.UserSubject) SecurityContext(org.apache.cxf.security.SecurityContext) Client(org.apache.cxf.rs.security.oauth2.common.Client)

Example 15 with UserSubject

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

the class RedirectionBasedGrantService method completeAuthorization.

/**
 * Completes the authorization process
 */
protected Response completeAuthorization(MultivaluedMap<String, String> params) {
    // Make sure the end user has authenticated, check if HTTPS is used
    SecurityContext securityContext = getAndValidateSecurityContext(params);
    UserSubject userSubject = createUserSubject(securityContext, params);
    // Make sure the session is valid
    String sessionTokenParamName = params.getFirst(OAuthConstants.SESSION_AUTHENTICITY_TOKEN_PARAM_NAME);
    if (sessionTokenParamName == null) {
        sessionTokenParamName = OAuthConstants.SESSION_AUTHENTICITY_TOKEN;
    }
    String sessionToken = params.getFirst(sessionTokenParamName);
    if (sessionToken == null || !compareRequestAndSessionTokens(sessionToken, params, userSubject)) {
        throw ExceptionUtils.toBadRequestException(null, null);
    }
    OAuthRedirectionState state = recreateRedirectionStateFromSession(userSubject, sessionToken);
    if (state == null) {
        state = recreateRedirectionStateFromParams(params);
    }
    Client client = getClient(state.getClientId(), params);
    String redirectUri = validateRedirectUri(client, state.getRedirectUri());
    // Get the end user decision value
    String decision = params.getFirst(OAuthConstants.AUTHORIZATION_DECISION_KEY);
    boolean allow = OAuthConstants.AUTHORIZATION_DECISION_ALLOW.equals(decision);
    // Return the error if denied
    if (!allow) {
        return createErrorResponse(params, redirectUri, OAuthConstants.ACCESS_DENIED);
    }
    // Check if the end user may have had a chance to down-scope the requested scopes
    List<String> requestedScope = OAuthUtils.parseScope(state.getProposedScope());
    List<String> approvedScope = new LinkedList<String>();
    for (String rScope : requestedScope) {
        String param = params.getFirst(rScope + "_status");
        if (param != null && OAuthConstants.AUTHORIZATION_DECISION_ALLOW.equals(param)) {
            approvedScope.add(rScope);
        }
    }
    if (!requestedScope.containsAll(approvedScope) || !OAuthUtils.validateScopes(requestedScope, client.getRegisteredScopes(), partialMatchScopeValidation)) {
        return createErrorResponse(params, redirectUri, OAuthConstants.INVALID_SCOPE);
    }
    getMessageContext().put(AUTHORIZATION_REQUEST_PARAMETERS, params);
    String preAuthorizedTokenKey = params.getFirst(PREAUTHORIZED_TOKEN_KEY);
    if (preAuthorizedTokenKey != null && isRevokePreauthorizedTokenOnApproval()) {
        getDataProvider().revokeToken(client, preAuthorizedTokenKey, OAuthConstants.ACCESS_TOKEN);
    }
    // Request a new grant
    return createGrant(state, client, requestedScope, approvedScope, userSubject, null);
}
Also used : OAuthRedirectionState(org.apache.cxf.rs.security.oauth2.common.OAuthRedirectionState) UserSubject(org.apache.cxf.rs.security.oauth2.common.UserSubject) SecurityContext(org.apache.cxf.security.SecurityContext) Client(org.apache.cxf.rs.security.oauth2.common.Client) LinkedList(java.util.LinkedList)

Aggregations

UserSubject (org.apache.cxf.rs.security.oauth2.common.UserSubject)29 Client (org.apache.cxf.rs.security.oauth2.common.Client)17 ServerAccessToken (org.apache.cxf.rs.security.oauth2.common.ServerAccessToken)10 OAuthServiceException (org.apache.cxf.rs.security.oauth2.provider.OAuthServiceException)8 ArrayList (java.util.ArrayList)7 OAuthPermission (org.apache.cxf.rs.security.oauth2.common.OAuthPermission)7 AccessTokenRegistration (org.apache.cxf.rs.security.oauth2.common.AccessTokenRegistration)6 LinkedList (java.util.LinkedList)5 ServerAuthorizationCodeGrant (org.apache.cxf.rs.security.oauth2.grants.code.ServerAuthorizationCodeGrant)5 SecurityContext (org.apache.cxf.security.SecurityContext)5 ClientAccessToken (org.apache.cxf.rs.security.oauth2.common.ClientAccessToken)4 OAuthAuthorizationData (org.apache.cxf.rs.security.oauth2.common.OAuthAuthorizationData)4 Principal (java.security.Principal)3 Map (java.util.Map)3 Message (org.apache.cxf.message.Message)3 Test (org.junit.Test)3 ByteArrayInputStream (java.io.ByteArrayInputStream)2 IOException (java.io.IOException)2 Instant (java.time.Instant)2 HashMap (java.util.HashMap)2