Search in sources :

Example 16 with AuthenticationContext

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

the class GatewayUtils method generateAuthenticationContext.

public static AuthenticationContext generateAuthenticationContext(String jti, JWTValidationInfo jwtValidationInfo, APIKeyValidationInfoDTO apiKeyValidationInfoDTO, String endUserToken, boolean isOauth) {
    AuthenticationContext authContext = new AuthenticationContext();
    authContext.setAuthenticated(true);
    authContext.setApiKey(jti);
    authContext.setUsername(getEndUserFromJWTValidationInfo(jwtValidationInfo, apiKeyValidationInfoDTO));
    authContext.setRequestTokenScopes(jwtValidationInfo.getScopes());
    authContext.setAccessToken(jwtValidationInfo.getRawPayload());
    if (apiKeyValidationInfoDTO != null) {
        authContext.setApiTier(apiKeyValidationInfoDTO.getApiTier());
        authContext.setKeyType(apiKeyValidationInfoDTO.getType());
        authContext.setApplicationId(apiKeyValidationInfoDTO.getApplicationId());
        authContext.setApplicationUUID(apiKeyValidationInfoDTO.getApplicationUUID());
        authContext.setApplicationName(apiKeyValidationInfoDTO.getApplicationName());
        authContext.setApplicationTier(apiKeyValidationInfoDTO.getApplicationTier());
        authContext.setSubscriber(apiKeyValidationInfoDTO.getSubscriber());
        authContext.setTier(apiKeyValidationInfoDTO.getTier());
        authContext.setSubscriberTenantDomain(apiKeyValidationInfoDTO.getSubscriberTenantDomain());
        authContext.setApiName(apiKeyValidationInfoDTO.getApiName());
        authContext.setApiPublisher(apiKeyValidationInfoDTO.getApiPublisher());
        authContext.setStopOnQuotaReach(apiKeyValidationInfoDTO.isStopOnQuotaReach());
        authContext.setSpikeArrestLimit(apiKeyValidationInfoDTO.getSpikeArrestLimit());
        authContext.setSpikeArrestUnit(apiKeyValidationInfoDTO.getSpikeArrestUnit());
        authContext.setConsumerKey(apiKeyValidationInfoDTO.getConsumerKey());
        authContext.setIsContentAware(apiKeyValidationInfoDTO.isContentAware());
        authContext.setGraphQLMaxDepth(apiKeyValidationInfoDTO.getGraphQLMaxDepth());
        authContext.setGraphQLMaxComplexity(apiKeyValidationInfoDTO.getGraphQLMaxComplexity());
    }
    if (isOauth) {
        authContext.setConsumerKey(jwtValidationInfo.getConsumerKey());
        if (jwtValidationInfo.getIssuer() != null) {
            authContext.setIssuer(jwtValidationInfo.getIssuer());
        }
    }
    // Set JWT token sent to the backend
    if (StringUtils.isNotEmpty(endUserToken)) {
        authContext.setCallerToken(endUserToken);
    }
    return authContext;
}
Also used : AuthenticationContext(org.wso2.carbon.apimgt.gateway.handlers.security.AuthenticationContext)

Example 17 with AuthenticationContext

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

the class TestUtils method getMessageContextWithAuthContext.

public static MessageContext getMessageContextWithAuthContext(String context, String version) {
    SynapseConfiguration synCfg = new SynapseConfiguration();
    org.apache.axis2.context.MessageContext axisMsgCtx = new org.apache.axis2.context.MessageContext();
    axisMsgCtx.setIncomingTransportName("http");
    axisMsgCtx.setProperty(Constants.Configuration.TRANSPORT_IN_URL, "/test/1.0.0/search.atom");
    AxisConfiguration axisConfig = new AxisConfiguration();
    ConfigurationContext cfgCtx = new ConfigurationContext(axisConfig);
    MessageContext synCtx = new Axis2MessageContext(axisMsgCtx, synCfg, new Axis2SynapseEnvironment(cfgCtx, synCfg));
    synCtx.setProperty(RESTConstants.REST_API_CONTEXT, context);
    synCtx.setProperty(RESTConstants.SYNAPSE_REST_API_VERSION, version);
    synCtx.setProperty(APIMgtGatewayConstants.API_STATUS, APIConstants.PUBLISHED);
    AuthenticationContext authenticationContext = new AuthenticationContext();
    authenticationContext.setUsername("sanjeewa");
    authenticationContext.setApiKey("123456789");
    authenticationContext.setApplicationId("123");
    authenticationContext.setApplicationName("test-app");
    authenticationContext.setAuthenticated(true);
    authenticationContext.setCallerToken("987654321");
    authenticationContext.setTier("Silver");
    authenticationContext.setSpikeArrestLimit(600);
    authenticationContext.setSubscriber("testSubscriber");
    Map map = new TreeMap();
    map.put("host", "127.0.0.1");
    map.put("X-FORWARDED-FOR", "127.0.0.1");
    ((Axis2MessageContext) synCtx).getAxis2MessageContext().setProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS, map);
    synCtx.setProperty(API_AUTH_CONTEXT, authenticationContext);
    return synCtx;
}
Also used : AxisConfiguration(org.apache.axis2.engine.AxisConfiguration) ConfigurationContext(org.apache.axis2.context.ConfigurationContext) AuthenticationContext(org.wso2.carbon.apimgt.gateway.handlers.security.AuthenticationContext) SynapseConfiguration(org.apache.synapse.config.SynapseConfiguration) TreeMap(java.util.TreeMap) Axis2SynapseEnvironment(org.apache.synapse.core.axis2.Axis2SynapseEnvironment) MessageContext(org.apache.synapse.MessageContext) Axis2MessageContext(org.apache.synapse.core.axis2.Axis2MessageContext) HashMap(java.util.HashMap) Map(java.util.Map) TreeMap(java.util.TreeMap) Axis2MessageContext(org.apache.synapse.core.axis2.Axis2MessageContext)

Example 18 with AuthenticationContext

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

the class DataProcessAndPublishingAgent method setDataReference.

/**
 * This method will use to set message context.
 */
public void setDataReference(String applicationLevelThrottleKey, String applicationLevelTier, String apiLevelThrottleKey, String apiLevelTier, String subscriptionLevelThrottleKey, String subscriptionLevelTier, String resourceLevelThrottleKey, String resourceLevelTier, String authorizedUser, String apiContext, String apiVersion, String appTenant, String apiTenant, String appId, MessageContext messageContext, AuthenticationContext authenticationContext) {
    if (!StringUtils.isEmpty(apiLevelTier)) {
        resourceLevelTier = apiLevelTier;
        resourceLevelThrottleKey = apiLevelThrottleKey;
    }
    this.authenticationContext = authenticationContext;
    this.messageContext = messageContext;
    this.applicationLevelThrottleKey = applicationLevelThrottleKey;
    this.applicationLevelTier = applicationLevelTier;
    this.apiLevelThrottleKey = apiLevelThrottleKey;
    this.subscriptionLevelThrottleKey = subscriptionLevelThrottleKey;
    this.subscriptionLevelTier = subscriptionLevelTier;
    this.resourceLevelThrottleKey = resourceLevelThrottleKey;
    this.resourceLevelTier = resourceLevelTier;
    this.authorizedUser = authorizedUser;
    this.apiContext = apiContext;
    this.apiVersion = apiVersion;
    this.appTenant = appTenant;
    this.apiTenant = apiTenant;
    this.appId = appId;
    this.apiName = GatewayUtils.getAPINameFromContextAndVersion(messageContext);
    this.messageSizeInBytes = 0;
    ArrayList<VerbInfoDTO> list = (ArrayList<VerbInfoDTO>) messageContext.getProperty(APIConstants.VERB_INFO_DTO);
    boolean isVerbInfoContentAware = false;
    if (list != null && !list.isEmpty()) {
        VerbInfoDTO verbInfoDTO = list.get(0);
        isVerbInfoContentAware = verbInfoDTO.isContentAware();
    }
    // Build the message if needed from here since it cannot be done from the run() method because content
    // in axis2MessageContext is modified.
    org.apache.axis2.context.MessageContext axis2MessageContext = ((Axis2MessageContext) messageContext).getAxis2MessageContext();
    Map<String, String> transportHeaderMap = (Map<String, String>) axis2MessageContext.getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS);
    if (transportHeaderMap != null) {
        this.headersMap = new HashMap<>(transportHeaderMap);
    }
    if (messageContext.getProperty(APIThrottleConstants.CUSTOM_PROPERTY) != null) {
        HashMap<String, Object> propertyFromMsgCtx = (HashMap<String, Object>) messageContext.getProperty(APIThrottleConstants.CUSTOM_PROPERTY);
        if (propertyFromMsgCtx != null) {
            this.customPropertyMap = (Map<String, Object>) propertyFromMsgCtx.clone();
        }
    }
    this.ipAddress = GatewayUtils.getIp(axis2MessageContext);
    if (log.isDebugEnabled()) {
        log.debug("Remote IP address : " + ipAddress);
    }
    if (authenticationContext.isContentAwareTierPresent() || isVerbInfoContentAware) {
        Object contentLength = transportHeaderMap.get(APIThrottleConstants.CONTENT_LENGTH);
        if (contentLength != null) {
            log.debug("Content lenght found in the request. Using it as the message size..");
            messageSizeInBytes = Long.parseLong(contentLength.toString());
        } else {
            log.debug("Building the message to get the message size..");
            try {
                buildMessage(axis2MessageContext);
            } catch (Exception ex) {
                // In case of any exception, it won't be propagated up,and set response size to 0
                log.error("Error occurred while building the message to" + " calculate the response body size", ex);
            }
            SOAPEnvelope env = messageContext.getEnvelope();
            if (env != null) {
                SOAPBody soapbody = env.getBody();
                if (soapbody != null) {
                    byte[] size = soapbody.toString().getBytes(Charset.defaultCharset());
                    messageSizeInBytes = size.length;
                }
            }
        }
    }
}
Also used : HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) SOAPEnvelope(org.apache.axiom.soap.SOAPEnvelope) XMLStreamException(javax.xml.stream.XMLStreamException) IOException(java.io.IOException) UnknownHostException(java.net.UnknownHostException) SOAPBody(org.apache.axiom.soap.SOAPBody) VerbInfoDTO(org.wso2.carbon.apimgt.impl.dto.VerbInfoDTO) JSONObject(org.json.simple.JSONObject) HashMap(java.util.HashMap) Map(java.util.Map) Axis2MessageContext(org.apache.synapse.core.axis2.Axis2MessageContext)

Example 19 with AuthenticationContext

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

the class APIMgtGoogleAnalyticsTrackingHandler method getVisitorId.

/**
 * Generate a visitor id for this hit. If there is a visitor id in the
 * messageContext, use that. Otherwise use a random number.
 */
private static String getVisitorId(String account, String userAgent, MessageContext msgCtx) throws NoSuchAlgorithmException, UnsupportedEncodingException {
    if (msgCtx.getProperty(COOKIE_NAME) != null) {
        return (String) msgCtx.getProperty(COOKIE_NAME);
    }
    String message;
    AuthenticationContext authContext = APISecurityUtils.getAuthenticationContext(msgCtx);
    if (authContext != null) {
        message = authContext.getApiKey();
    } else {
        message = ANONYMOUS_USER_ID;
    }
    MessageDigest m = MessageDigest.getInstance("MD5");
    m.update(message.getBytes("UTF-8"), 0, message.length());
    byte[] sum = m.digest();
    BigInteger messageAsNumber = new BigInteger(1, sum);
    String md5String = messageAsNumber.toString(16);
    /* Pad to make sure id is 32 characters long. */
    while (md5String.length() < 32) {
        md5String = "0" + md5String;
    }
    return "0x" + md5String.substring(0, 16);
}
Also used : AuthenticationContext(org.wso2.carbon.apimgt.gateway.handlers.security.AuthenticationContext) BigInteger(java.math.BigInteger) MessageDigest(java.security.MessageDigest)

Example 20 with AuthenticationContext

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

the class ExtensionListenerUtil method generateAPIInfoDTO.

/**
 * Generates APIRequestInfoDTO object using Synapse MessageContext.
 *
 * @param messageContext Synapse MessageContext
 * @return APIRequestInfoDTO
 */
private static APIRequestInfoDTO generateAPIInfoDTO(MessageContext messageContext) {
    APIRequestInfoDTO apiRequestInfoDTO = new APIRequestInfoDTO();
    apiRequestInfoDTO.setContext((String) messageContext.getProperty(RESTConstants.REST_API_CONTEXT));
    apiRequestInfoDTO.setVersion((String) messageContext.getProperty(RESTConstants.SYNAPSE_REST_API_VERSION));
    apiRequestInfoDTO.setApiId((String) messageContext.getProperty(APIMgtGatewayConstants.API_UUID_PROPERTY));
    AuthenticationContext authenticationContext = APISecurityUtils.getAuthenticationContext(messageContext);
    if (authenticationContext != null) {
        apiRequestInfoDTO.setUsername(authenticationContext.getUsername());
        apiRequestInfoDTO.setConsumerKey(authenticationContext.getConsumerKey());
    }
    return apiRequestInfoDTO;
}
Also used : AuthenticationContext(org.wso2.carbon.apimgt.gateway.handlers.security.AuthenticationContext) APIRequestInfoDTO(org.wso2.carbon.apimgt.common.gateway.dto.APIRequestInfoDTO)

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