Search in sources :

Example 56 with AuthenticationContext

use of org.wso2.carbon.apimgt.gateway.handlers.security.AuthenticationContext in project carbon-apimgt by wso2.

the class JWTValidator method validateScopesForGraphQLSubscriptions.

/**
 * Validate scopes for GraphQL subscription API calls using token scopes in authentication context.
 *
 * @param apiContext            API Context
 * @param apiVersion            API Version
 * @param matchingResource      Matching resource
 * @param jwtToken              JWT Token
 * @param authenticationContext AuthenticationContext
 * @throws APISecurityException if an error occurs
 */
public void validateScopesForGraphQLSubscriptions(String apiContext, String apiVersion, String matchingResource, SignedJWTInfo jwtToken, AuthenticationContext authenticationContext) throws APISecurityException {
    String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain();
    // Generate TokenValidationContext
    TokenValidationContext tokenValidationContext = new TokenValidationContext();
    APIKeyValidationInfoDTO apiKeyValidationInfoDTO = new APIKeyValidationInfoDTO();
    Set<String> scopeSet = new HashSet<>();
    scopeSet.addAll(authenticationContext.getRequestTokenScopes());
    apiKeyValidationInfoDTO.setScopes(scopeSet);
    tokenValidationContext.setValidationInfoDTO(apiKeyValidationInfoDTO);
    tokenValidationContext.setAccessToken(jwtToken.getToken());
    tokenValidationContext.setHttpVerb(GraphQLConstants.SubscriptionConstants.HTTP_METHOD_NAME);
    tokenValidationContext.setMatchingResource(matchingResource);
    tokenValidationContext.setContext(apiContext);
    tokenValidationContext.setVersion(apiVersion);
    boolean valid = this.apiKeyValidator.validateScopes(tokenValidationContext, tenantDomain);
    if (valid) {
        if (log.isDebugEnabled()) {
            log.debug("Scope validation successful for the resource: " + matchingResource + ", user: " + authenticationContext.getUsername());
        }
    } else {
        String message = "User is NOT authorized to access the Resource: " + matchingResource + ". Scope validation failed.";
        log.debug(message);
        throw new APISecurityException(APISecurityConstants.INVALID_SCOPE, message);
    }
}
Also used : APISecurityException(org.wso2.carbon.apimgt.gateway.handlers.security.APISecurityException) TokenValidationContext(org.wso2.carbon.apimgt.keymgt.service.TokenValidationContext) APIKeyValidationInfoDTO(org.wso2.carbon.apimgt.impl.dto.APIKeyValidationInfoDTO) HashSet(java.util.HashSet)

Example 57 with AuthenticationContext

use of org.wso2.carbon.apimgt.gateway.handlers.security.AuthenticationContext in project carbon-apimgt by wso2.

the class JWTValidator method authenticate.

/**
 * Authenticates the given request with a JWT token to see if an API consumer is allowed to access
 * a particular API or not.
 *
 * @param signedJWTInfo The JWT token sent with the API request
 * @param synCtx   The message to be authenticated
 * @return an AuthenticationContext object which contains the authentication information
 * @throws APISecurityException in case of authentication failure
 */
@MethodStats
public AuthenticationContext authenticate(SignedJWTInfo signedJWTInfo, MessageContext synCtx) throws APISecurityException {
    String apiContext = (String) synCtx.getProperty(RESTConstants.REST_API_CONTEXT);
    String apiVersion = (String) synCtx.getProperty(RESTConstants.SYNAPSE_REST_API_VERSION);
    org.apache.axis2.context.MessageContext axis2MsgContext = ((Axis2MessageContext) synCtx).getAxis2MessageContext();
    String httpMethod = (String) axis2MsgContext.getProperty(Constants.Configuration.HTTP_METHOD);
    String matchingResource = (String) synCtx.getProperty(APIConstants.API_ELECTED_RESOURCE);
    String jwtTokenIdentifier = getJWTTokenIdentifier(signedJWTInfo);
    String jwtHeader = signedJWTInfo.getSignedJWT().getHeader().toString();
    try {
        X509Certificate clientCertificate = Utils.getClientCertificate(axis2MsgContext);
        signedJWTInfo.setX509ClientCertificate(clientCertificate);
    } catch (APIManagementException e) {
        log.error("Error while obtaining client certificate. " + GatewayUtils.getMaskedToken(jwtHeader));
    }
    if (StringUtils.isNotEmpty(jwtTokenIdentifier)) {
        if (RevokedJWTDataHolder.isJWTTokenSignatureExistsInRevokedMap(jwtTokenIdentifier)) {
            if (log.isDebugEnabled()) {
                log.debug("Token retrieved from the revoked jwt token map. Token: " + GatewayUtils.getMaskedToken(jwtHeader));
            }
            log.error("Invalid JWT token. " + GatewayUtils.getMaskedToken(jwtHeader));
            throw new APISecurityException(APISecurityConstants.API_AUTH_INVALID_CREDENTIALS, "Invalid JWT token");
        }
    }
    JWTValidationInfo jwtValidationInfo = getJwtValidationInfo(signedJWTInfo, jwtTokenIdentifier);
    if (jwtValidationInfo != null) {
        if (jwtValidationInfo.isValid()) {
            // Validate subscriptions
            APIKeyValidationInfoDTO apiKeyValidationInfoDTO;
            log.debug("Begin subscription validation via Key Manager: " + jwtValidationInfo.getKeyManager());
            apiKeyValidationInfoDTO = validateSubscriptionUsingKeyManager(synCtx, jwtValidationInfo);
            if (log.isDebugEnabled()) {
                log.debug("Subscription validation via Key Manager. Status: " + apiKeyValidationInfoDTO.isAuthorized());
            }
            if (!apiKeyValidationInfoDTO.isAuthorized()) {
                log.debug("User is NOT authorized to access the Resource. API Subscription validation failed.");
                throw new APISecurityException(apiKeyValidationInfoDTO.getValidationStatus(), "User is NOT authorized to access the Resource. API Subscription validation failed.");
            }
            // Validate scopes
            validateScopes(apiContext, apiVersion, matchingResource, httpMethod, jwtValidationInfo, signedJWTInfo);
            synCtx.setProperty(APIMgtGatewayConstants.SCOPES, jwtValidationInfo.getScopes().toString());
            if (apiKeyValidationInfoDTO.isAuthorized()) {
                /*
                     * Set api.ut.apiPublisher of the subscribed api to the message context.
                     * This is necessary for the functionality of Publisher alerts.
                     * Set API_NAME of the subscribed api to the message context.
                     * */
                synCtx.setProperty(APIMgtGatewayConstants.API_PUBLISHER, apiKeyValidationInfoDTO.getApiPublisher());
                synCtx.setProperty("API_NAME", apiKeyValidationInfoDTO.getApiName());
                /* GraphQL Query Analysis Information */
                if (APIConstants.GRAPHQL_API.equals(synCtx.getProperty(APIConstants.API_TYPE))) {
                    synCtx.setProperty(APIConstants.MAXIMUM_QUERY_DEPTH, apiKeyValidationInfoDTO.getGraphQLMaxDepth());
                    synCtx.setProperty(APIConstants.MAXIMUM_QUERY_COMPLEXITY, apiKeyValidationInfoDTO.getGraphQLMaxComplexity());
                }
                log.debug("JWT authentication successful.");
            }
            log.debug("JWT authentication successful.");
            String endUserToken = null;
            if (jwtGenerationEnabled) {
                JWTInfoDto jwtInfoDto = GatewayUtils.generateJWTInfoDto(null, jwtValidationInfo, apiKeyValidationInfoDTO, synCtx);
                endUserToken = generateAndRetrieveJWTToken(jwtTokenIdentifier, jwtInfoDto);
            }
            return GatewayUtils.generateAuthenticationContext(jwtTokenIdentifier, jwtValidationInfo, apiKeyValidationInfoDTO, endUserToken, true);
        } else {
            throw new APISecurityException(jwtValidationInfo.getValidationCode(), APISecurityConstants.getAuthenticationFailureMessage(jwtValidationInfo.getValidationCode()));
        }
    } else {
        throw new APISecurityException(APISecurityConstants.API_AUTH_GENERAL_ERROR, APISecurityConstants.API_AUTH_GENERAL_ERROR_MESSAGE);
    }
}
Also used : APISecurityException(org.wso2.carbon.apimgt.gateway.handlers.security.APISecurityException) JWTInfoDto(org.wso2.carbon.apimgt.common.gateway.dto.JWTInfoDto) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) X509Certificate(javax.security.cert.X509Certificate) APIKeyValidationInfoDTO(org.wso2.carbon.apimgt.impl.dto.APIKeyValidationInfoDTO) Axis2MessageContext(org.apache.synapse.core.axis2.Axis2MessageContext) JWTValidationInfo(org.wso2.carbon.apimgt.common.gateway.dto.JWTValidationInfo) MethodStats(org.wso2.carbon.apimgt.gateway.MethodStats)

Example 58 with AuthenticationContext

use of org.wso2.carbon.apimgt.gateway.handlers.security.AuthenticationContext in project carbon-apimgt by wso2.

the class DataProcessAndPublishingAgentTest method testContentAwareTierPresentAndContentLengthNotPresent.

@Test
public void testContentAwareTierPresentAndContentLengthNotPresent() throws Exception {
    ThrottleProperties throttleProperties = new ThrottleProperties();
    DataProcessAndPublishingAgent dataProcessAndPublishingAgent = new DataProcessAndPublishingAgentWrapper(throttleProperties);
    AuthenticationContext authenticationContext = new AuthenticationContext();
    authenticationContext.setIsContentAware(true);
    MessageContext messageContext = Mockito.mock(Axis2MessageContext.class);
    SOAPFactory fac = OMAbstractFactory.getSOAP12Factory();
    SOAPEnvelope env = fac.createSOAPEnvelope();
    fac.createSOAPBody(env);
    env.getBody().addChild(fac.createOMElement("test", "http://t", "t"));
    org.apache.axis2.context.MessageContext axis2MsgCntxt = Mockito.mock(org.apache.axis2.context.MessageContext.class);
    Mockito.when(messageContext.getEnvelope()).thenReturn(env);
    Mockito.when(((Axis2MessageContext) messageContext).getAxis2MessageContext()).thenReturn(axis2MsgCntxt);
    TreeMap headers = new TreeMap();
    Mockito.when(axis2MsgCntxt.getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS)).thenReturn(headers);
    VerbInfoDTO verbInfoDTO = new VerbInfoDTO();
    verbInfoDTO.setContentAware(false);
    ArrayList<VerbInfoDTO> list = new ArrayList<VerbInfoDTO>();
    list.add(verbInfoDTO);
    API api = new API();
    api.setUuid(UUID.randomUUID().toString());
    api.setApiName(apiName);
    api.setApiVersion(apiVersion);
    api.setApiProvider("admin");
    Mockito.when(messageContext.getProperty(APIMgtGatewayConstants.API_OBJECT)).thenReturn(api);
    Mockito.when(messageContext.getProperty(APIConstants.VERB_INFO_DTO)).thenReturn(list);
    dataProcessAndPublishingAgent.setDataReference(applicationLevelThrottleKey, applicationLevelTier, apiLevelThrottleKey, null, subscriptionLevelThrottleKey, subscriptionLevelTier, resourceLevelThrottleKey, resourceLevelTier, authorizedUser, apiContext, apiVersion, appTenant, apiTenant, appId, messageContext, authenticationContext);
    dataProcessAndPublishingAgent.run();
}
Also used : AuthenticationContext(org.wso2.carbon.apimgt.gateway.handlers.security.AuthenticationContext) ArrayList(java.util.ArrayList) SOAPEnvelope(org.apache.axiom.soap.SOAPEnvelope) TreeMap(java.util.TreeMap) SOAPFactory(org.apache.axiom.soap.SOAPFactory) VerbInfoDTO(org.wso2.carbon.apimgt.impl.dto.VerbInfoDTO) API(org.wso2.carbon.apimgt.keymgt.model.entity.API) MessageContext(org.apache.synapse.MessageContext) Axis2MessageContext(org.apache.synapse.core.axis2.Axis2MessageContext) ThrottleProperties(org.wso2.carbon.apimgt.impl.dto.ThrottleProperties) Axis2MessageContext(org.apache.synapse.core.axis2.Axis2MessageContext) Test(org.junit.Test)

Example 59 with AuthenticationContext

use of org.wso2.carbon.apimgt.gateway.handlers.security.AuthenticationContext in project carbon-apimgt by wso2.

the class DataProcessAndPublishingAgentTest method setDataReference.

@Test
public void setDataReference() throws Exception {
    ThrottleProperties throttleProperties = new ThrottleProperties();
    DataPublisher dataPublisher = Mockito.mock(DataPublisher.class);
    Mockito.when(dataPublisher.tryPublish(Mockito.any(Event.class))).thenReturn(true);
    DataProcessAndPublishingAgent dataProcessAndPublishingAgent = new DataProcessAndPublishingAgentWrapper(throttleProperties);
    AuthenticationContext authenticationContext = new AuthenticationContext();
    MessageContext messageContext = Mockito.mock(Axis2MessageContext.class);
    org.apache.axis2.context.MessageContext axis2MsgCntxt = Mockito.mock(org.apache.axis2.context.MessageContext.class);
    Mockito.when(((Axis2MessageContext) messageContext).getAxis2MessageContext()).thenReturn(axis2MsgCntxt);
    VerbInfoDTO verbInfoDTO = new VerbInfoDTO();
    verbInfoDTO.setContentAware(false);
    ArrayList<VerbInfoDTO> list = new ArrayList<VerbInfoDTO>();
    list.add(verbInfoDTO);
    API api = new API();
    api.setUuid(UUID.randomUUID().toString());
    api.setApiName(apiName);
    api.setApiVersion(apiVersion);
    api.setApiProvider("admin");
    Mockito.when(messageContext.getProperty(APIMgtGatewayConstants.API_OBJECT)).thenReturn(api);
    Mockito.when(messageContext.getProperty(APIConstants.VERB_INFO_DTO)).thenReturn(list);
    Mockito.when(axis2MsgCntxt.getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS)).thenReturn(new TreeMap<>());
    dataProcessAndPublishingAgent.setDataReference(applicationLevelThrottleKey, applicationLevelTier, apiLevelThrottleKey, apiLevelTier, subscriptionLevelThrottleKey, subscriptionLevelTier, resourceLevelThrottleKey, resourceLevelTier, authorizedUser, apiContext, apiVersion, appTenant, apiTenant, appId, messageContext, authenticationContext);
    dataProcessAndPublishingAgent.run();
}
Also used : AuthenticationContext(org.wso2.carbon.apimgt.gateway.handlers.security.AuthenticationContext) ArrayList(java.util.ArrayList) VerbInfoDTO(org.wso2.carbon.apimgt.impl.dto.VerbInfoDTO) DataPublisher(org.wso2.carbon.databridge.agent.DataPublisher) Event(org.wso2.carbon.databridge.commons.Event) API(org.wso2.carbon.apimgt.keymgt.model.entity.API) MessageContext(org.apache.synapse.MessageContext) Axis2MessageContext(org.apache.synapse.core.axis2.Axis2MessageContext) ThrottleProperties(org.wso2.carbon.apimgt.impl.dto.ThrottleProperties) Axis2MessageContext(org.apache.synapse.core.axis2.Axis2MessageContext) Test(org.junit.Test)

Example 60 with AuthenticationContext

use of org.wso2.carbon.apimgt.gateway.handlers.security.AuthenticationContext in project carbon-apimgt by wso2.

the class DataProcessAndPublishingAgentTest method setDataReferenceWithHeaderConditionEnable.

@Test
public void setDataReferenceWithHeaderConditionEnable() throws Exception {
    ThrottleProperties throttleProperties = new ThrottleProperties();
    throttleProperties.setEnableHeaderConditions(true);
    DataProcessAndPublishingAgent dataProcessAndPublishingAgent = new DataProcessAndPublishingAgentWrapper(throttleProperties);
    AuthenticationContext authenticationContext = new AuthenticationContext();
    MessageContext messageContext = Mockito.mock(Axis2MessageContext.class);
    org.apache.axis2.context.MessageContext axis2MsgCntxt = Mockito.mock(org.apache.axis2.context.MessageContext.class);
    Mockito.when(((Axis2MessageContext) messageContext).getAxis2MessageContext()).thenReturn(axis2MsgCntxt);
    Mockito.when(axis2MsgCntxt.getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS)).thenReturn(new TreeMap<>());
    VerbInfoDTO verbInfoDTO = new VerbInfoDTO();
    verbInfoDTO.setContentAware(false);
    ArrayList<VerbInfoDTO> list = new ArrayList<VerbInfoDTO>();
    list.add(verbInfoDTO);
    API api = new API();
    api.setUuid(UUID.randomUUID().toString());
    api.setApiName(apiName);
    api.setApiVersion(apiVersion);
    api.setApiProvider("admin");
    Mockito.when(messageContext.getProperty(APIMgtGatewayConstants.API_OBJECT)).thenReturn(api);
    Mockito.when(messageContext.getProperty(APIConstants.VERB_INFO_DTO)).thenReturn(list);
    dataProcessAndPublishingAgent.setDataReference(applicationLevelThrottleKey, applicationLevelTier, apiLevelThrottleKey, null, subscriptionLevelThrottleKey, subscriptionLevelTier, resourceLevelThrottleKey, resourceLevelTier, authorizedUser, apiContext, apiVersion, appTenant, apiTenant, appId, messageContext, authenticationContext);
    dataProcessAndPublishingAgent.run();
}
Also used : AuthenticationContext(org.wso2.carbon.apimgt.gateway.handlers.security.AuthenticationContext) ArrayList(java.util.ArrayList) VerbInfoDTO(org.wso2.carbon.apimgt.impl.dto.VerbInfoDTO) API(org.wso2.carbon.apimgt.keymgt.model.entity.API) MessageContext(org.apache.synapse.MessageContext) Axis2MessageContext(org.apache.synapse.core.axis2.Axis2MessageContext) ThrottleProperties(org.wso2.carbon.apimgt.impl.dto.ThrottleProperties) Axis2MessageContext(org.apache.synapse.core.axis2.Axis2MessageContext) Test(org.junit.Test)

Aggregations

AuthenticationContext (org.wso2.carbon.apimgt.gateway.handlers.security.AuthenticationContext)96 Axis2MessageContext (org.apache.synapse.core.axis2.Axis2MessageContext)69 Test (org.junit.Test)69 MessageContext (org.apache.synapse.MessageContext)56 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)49 ArrayList (java.util.ArrayList)31 ConditionGroupDTO (org.wso2.carbon.apimgt.api.dto.ConditionGroupDTO)31 TreeMap (java.util.TreeMap)22 VerbInfoDTO (org.wso2.carbon.apimgt.impl.dto.VerbInfoDTO)22 API (org.wso2.carbon.apimgt.keymgt.model.entity.API)21 HashMap (java.util.HashMap)19 Cache (javax.cache.Cache)18 Test (org.testng.annotations.Test)18 AuthenticationContext (org.wso2.carbon.identity.application.authentication.framework.context.AuthenticationContext)18 ThrottleProperties (org.wso2.carbon.apimgt.impl.dto.ThrottleProperties)17 SignedJWT (com.nimbusds.jwt.SignedJWT)16 ConditionDTO (org.wso2.carbon.apimgt.api.dto.ConditionDTO)16 ThrottleDataHolder (org.wso2.carbon.apimgt.gateway.throttling.ThrottleDataHolder)16 APISecurityException (org.wso2.carbon.apimgt.gateway.handlers.security.APISecurityException)15 APIKeyValidationInfoDTO (org.wso2.carbon.apimgt.impl.dto.APIKeyValidationInfoDTO)14