Search in sources :

Example 26 with APISecurityException

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

the class OAuthResponseMediator method mediate.

@Override
public boolean mediate(MessageContext messageContext) {
    if (messageContext != null) {
        TargetResponse targetResponse = (TargetResponse) ((Axis2MessageContext) messageContext).getAxis2MessageContext().getProperty("pass-through.Target-Response");
        int statusCode = targetResponse.getStatus();
        if (statusCode == 401) {
            Object oauthEndpointObject = messageContext.getProperty(APIMgtGatewayConstants.OAUTH_ENDPOINT_INSTANCE);
            if (oauthEndpointObject instanceof OAuthEndpoint) {
                try {
                    OAuthTokenGenerator.generateToken((OAuthEndpoint) oauthEndpointObject, null);
                    log.error("OAuth 2.0 access token has been rejected by the backend...");
                    handleFailure(APISecurityConstants.OAUTH_TEMPORARY_SERVER_ERROR, messageContext, APISecurityConstants.OAUTH_TEMPORARY_SERVER_ERROR_MESSAGE, "Please try again");
                } catch (APISecurityException e) {
                    log.error("Error when generating oauth 2.0 access token...", e);
                }
            }
        }
    }
    return true;
}
Also used : APISecurityException(org.wso2.carbon.apimgt.gateway.handlers.security.APISecurityException) OAuthEndpoint(org.wso2.carbon.apimgt.gateway.mediators.oauth.conf.OAuthEndpoint) TargetResponse(org.apache.synapse.transport.passthru.TargetResponse) OAuthEndpoint(org.wso2.carbon.apimgt.gateway.mediators.oauth.conf.OAuthEndpoint) Axis2MessageContext(org.apache.synapse.core.axis2.Axis2MessageContext)

Example 27 with APISecurityException

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

the class InboundWebSocketProcessor method handleHandshake.

/**
 * This method process websocket handshake and extract necessary API information from the channel context and
 * request. Finally, hand over the processing to relevant handshake processor for authentication etc.
 *
 * @param req                   Handshake request
 * @param ctx                   Channel pipeline context
 * @param inboundMessageContext InboundMessageContext
 * @return InboundProcessorResponseDTO with handshake processing response
 */
public InboundProcessorResponseDTO handleHandshake(FullHttpRequest req, ChannelHandlerContext ctx, InboundMessageContext inboundMessageContext) {
    InboundProcessorResponseDTO inboundProcessorResponseDTO;
    try {
        HandshakeProcessor handshakeProcessor = new HandshakeProcessor();
        setUris(req, inboundMessageContext);
        InboundWebsocketProcessorUtil.setTenantDomainToContext(inboundMessageContext);
        setMatchingResource(ctx, req, inboundMessageContext);
        String userAgent = req.headers().get(HttpHeaders.USER_AGENT);
        // '-' is used for empty values to avoid possible errors in DAS side.
        // Required headers are stored one by one as validateOAuthHeader()
        // removes some headers from the request
        userAgent = userAgent != null ? userAgent : "-";
        inboundMessageContext.getRequestHeaders().put(HttpHeaders.USER_AGENT, userAgent);
        PrivilegedCarbonContext.startTenantFlow();
        PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(inboundMessageContext.getTenantDomain(), true);
        if (validateOAuthHeader(req, inboundMessageContext)) {
            setRequestHeaders(req, inboundMessageContext);
            inboundMessageContext.getRequestHeaders().put(HttpHeaders.AUTHORIZATION, req.headers().get(HttpHeaders.AUTHORIZATION));
            inboundProcessorResponseDTO = handshakeProcessor.processHandshake(inboundMessageContext);
        } else {
            String errorMessage = "No Authorization Header or access_token query parameter present";
            log.error(errorMessage + " in request for the websocket context " + inboundMessageContext.getApiContext());
            inboundProcessorResponseDTO = InboundWebsocketProcessorUtil.getHandshakeErrorDTO(WebSocketApiConstants.HandshakeErrorConstants.API_AUTH_ERROR, errorMessage);
        }
        publishHandshakeAuthErrorEvent(ctx, inboundProcessorResponseDTO.getErrorMessage());
        return inboundProcessorResponseDTO;
    } catch (APISecurityException e) {
        log.error("Authentication Failure for the websocket context: " + inboundMessageContext.getApiContext() + e.getMessage());
        inboundProcessorResponseDTO = InboundWebsocketProcessorUtil.getHandshakeErrorDTO(WebSocketApiConstants.HandshakeErrorConstants.API_AUTH_ERROR, e.getMessage());
        publishHandshakeAuthErrorEvent(ctx, e.getMessage());
    } catch (WebSocketApiException e) {
        log.error(e.getMessage());
        inboundProcessorResponseDTO = InboundWebsocketProcessorUtil.getHandshakeErrorDTO(WebSocketApiConstants.HandshakeErrorConstants.INTERNAL_SERVER_ERROR, e.getMessage());
    } catch (ResourceNotFoundException e) {
        log.error(e.getMessage());
        inboundProcessorResponseDTO = InboundWebsocketProcessorUtil.getHandshakeErrorDTO(WebSocketApiConstants.HandshakeErrorConstants.RESOURCE_NOT_FOUND_ERROR, e.getMessage());
        publishResourceNotFoundEvent(ctx);
    }
    return inboundProcessorResponseDTO;
}
Also used : APISecurityException(org.wso2.carbon.apimgt.gateway.handlers.security.APISecurityException) WebSocketApiException(org.wso2.carbon.apimgt.gateway.handlers.streaming.websocket.WebSocketApiException) ResourceNotFoundException(org.wso2.carbon.apimgt.gateway.handlers.security.ResourceNotFoundException) HandshakeProcessor(org.wso2.carbon.apimgt.gateway.inbound.websocket.handshake.HandshakeProcessor)

Example 28 with APISecurityException

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

the class InboundWebsocketProcessorUtil method authenticateWSJWTToken.

/**
 * Authenticates JWT token in incoming Websocket handshake requests.
 *
 * @param inboundMessageContext InboundMessageContext
 * @return true if authenticated
 * @throws APIManagementException if an internal error occurs
 * @throws APISecurityException   if authentication fails
 */
public static boolean authenticateWSJWTToken(InboundMessageContext inboundMessageContext) throws APIManagementException, APISecurityException {
    AuthenticationContext authenticationContext;
    JWTValidator jwtValidator = new JWTValidator(new APIKeyValidator(), inboundMessageContext.getTenantDomain());
    authenticationContext = jwtValidator.authenticateForWebSocket(inboundMessageContext.getSignedJWTInfo(), inboundMessageContext.getApiContext(), inboundMessageContext.getVersion(), inboundMessageContext.getMatchingResource());
    return validateAuthenticationContext(authenticationContext, inboundMessageContext);
}
Also used : AuthenticationContext(org.wso2.carbon.apimgt.gateway.handlers.security.AuthenticationContext) APIKeyValidator(org.wso2.carbon.apimgt.gateway.handlers.security.APIKeyValidator) JWTValidator(org.wso2.carbon.apimgt.gateway.handlers.security.jwt.JWTValidator)

Example 29 with APISecurityException

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

the class InboundWebsocketProcessorUtil method authenticateGraphQLJWTToken.

/**
 * Authenticates JWT token in incoming GraphQL subscription requests.
 *
 * @param inboundMessageContext InboundMessageContext
 * @return true if authenticated
 * @throws APIManagementException if an internal error occurs
 * @throws APISecurityException   if authentication fails
 */
public static boolean authenticateGraphQLJWTToken(InboundMessageContext inboundMessageContext) throws APIManagementException, APISecurityException {
    AuthenticationContext authenticationContext;
    PrivilegedCarbonContext.startTenantFlow();
    PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(inboundMessageContext.getTenantDomain(), true);
    JWTValidator jwtValidator = new JWTValidator(new APIKeyValidator(), inboundMessageContext.getTenantDomain());
    authenticationContext = jwtValidator.authenticateForGraphQLSubscription(inboundMessageContext.getSignedJWTInfo(), inboundMessageContext.getApiContext(), inboundMessageContext.getVersion());
    return validateAuthenticationContext(authenticationContext, inboundMessageContext);
}
Also used : AuthenticationContext(org.wso2.carbon.apimgt.gateway.handlers.security.AuthenticationContext) APIKeyValidator(org.wso2.carbon.apimgt.gateway.handlers.security.APIKeyValidator) JWTValidator(org.wso2.carbon.apimgt.gateway.handlers.security.jwt.JWTValidator)

Example 30 with APISecurityException

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

the class InboundWebsocketProcessorUtil method authorizeGraphQLSubscriptionEvents.

/**
 * Validate scopes of JWT token for incoming GraphQL subscription messages.
 *
 * @param matchingResource      Invoking GraphQL subscription operation
 * @param inboundMessageContext InboundMessageContext
 * @return true if authorized
 * @throws APIManagementException if an internal error occurs
 * @throws APISecurityException   if authorization fails
 */
public static boolean authorizeGraphQLSubscriptionEvents(String matchingResource, InboundMessageContext inboundMessageContext) throws APIManagementException, APISecurityException {
    JWTValidator jwtValidator = new JWTValidator(new APIKeyValidator(), inboundMessageContext.getTenantDomain());
    jwtValidator.validateScopesForGraphQLSubscriptions(inboundMessageContext.getApiContext(), inboundMessageContext.getVersion(), matchingResource, inboundMessageContext.getSignedJWTInfo(), inboundMessageContext.getAuthContext());
    return true;
}
Also used : APIKeyValidator(org.wso2.carbon.apimgt.gateway.handlers.security.APIKeyValidator) JWTValidator(org.wso2.carbon.apimgt.gateway.handlers.security.jwt.JWTValidator)

Aggregations

APISecurityException (org.wso2.carbon.apimgt.gateway.handlers.security.APISecurityException)34 Test (org.junit.Test)28 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)28 APIKeyValidationInfoDTO (org.wso2.carbon.apimgt.impl.dto.APIKeyValidationInfoDTO)28 Axis2MessageContext (org.apache.synapse.core.axis2.Axis2MessageContext)26 Cache (javax.cache.Cache)22 AuthenticationContext (org.wso2.carbon.apimgt.gateway.handlers.security.AuthenticationContext)16 JWTValidationInfo (org.wso2.carbon.apimgt.common.gateway.dto.JWTValidationInfo)15 APIKeyValidator (org.wso2.carbon.apimgt.gateway.handlers.security.APIKeyValidator)15 MessageContext (org.apache.synapse.MessageContext)14 APIManagerConfiguration (org.wso2.carbon.apimgt.impl.APIManagerConfiguration)14 SignedJWTInfo (org.wso2.carbon.apimgt.impl.jwt.SignedJWTInfo)12 SignedJWT (com.nimbusds.jwt.SignedJWT)11 HashMap (java.util.HashMap)11 VerbInfoDTO (org.wso2.carbon.apimgt.impl.dto.VerbInfoDTO)11 ArrayList (java.util.ArrayList)10 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)10 ExtendedJWTConfigurationDto (org.wso2.carbon.apimgt.impl.dto.ExtendedJWTConfigurationDto)10 JWTValidationService (org.wso2.carbon.apimgt.impl.jwt.JWTValidationService)10 TokenValidationContext (org.wso2.carbon.apimgt.keymgt.service.TokenValidationContext)10