Search in sources :

Example 1 with RestAPIAuthenticator

use of org.wso2.carbon.apimgt.rest.api.common.RestAPIAuthenticator in project carbon-apimgt by wso2.

the class RESTAPISecurityInterceptor method preCall.

/**
 * preCall is run before a handler method call is made. If any of the preCalls throw exception or return false then
 * no other subsequent preCalls will be called and the request processing will be terminated,
 * also no postCall interceptors will be called.
 *
 * @param request           HttpRequest being processed.
 * @param response          HttpResponder to send response.
 * @param serviceMethodInfo Info on handler method that will be called.
 * @return true if the request processing can continue, otherwise the hook should send response and return false to
 * stop further processing.
 * @throws APIMgtSecurityException if error occurs while executing the preCall
 */
@Override
public boolean preCall(Request request, Response response, ServiceMethodInfo serviceMethodInfo) throws APIMgtSecurityException {
    ErrorHandler errorHandler = null;
    boolean isAuthenticated = false;
    // CORS for Environments - Add allowed Origin when User-Agent sent 'Origin' header.
    String origin = request.getHeader(RestApiConstants.ORIGIN_HEADER);
    String allowedOrigin = EnvironmentUtils.getAllowedOrigin(origin);
    if (allowedOrigin != null) {
        response.setHeader(RestApiConstants.ACCESS_CONTROL_ALLOW_ORIGIN_HEADER, allowedOrigin).setHeader(RestApiConstants.ACCESS_CONTROL_ALLOW_CREDENTIALS_HEADER, "true");
    }
    // CORS for Environments - Add allowed Methods and Headers when 'OPTIONS' method is called.
    if (request.getHttpMethod().equalsIgnoreCase(APIConstants.HTTP_OPTIONS)) {
        try {
            String definedHttpMethods = RestApiUtil.getDefinedMethodHeadersInSwaggerContent(request, serviceMethodInfo);
            if (definedHttpMethods != null) {
                response.setHeader(RestApiConstants.ACCESS_CONTROL_ALLOW_METHODS_HEADER, definedHttpMethods).setHeader(RestApiConstants.ACCESS_CONTROL_ALLOW_HEADERS_HEADER, RestApiConstants.ACCESS_CONTROL_ALLOW_HEADERS_LIST).setStatus(javax.ws.rs.core.Response.Status.OK.getStatusCode()).send();
                return false;
            }
        } catch (APIManagementException e) {
            String msg = "Couldn't find declared HTTP methods in swagger.yaml";
            ErrorDTO errorDTO = RestApiUtil.getErrorDTO(e.getErrorHandler());
            log.error(msg, e);
            response.setStatus(javax.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).setEntity(errorDTO).send();
            return false;
        }
    }
    /* TODO: Following string contains check is done to avoid checking security headers in non API requests.
         * Consider this as a temporary fix until MSF4J support context based interceptor registration */
    String requestURI = request.getUri().toLowerCase(Locale.ENGLISH);
    if (!requestURI.contains("/api/am/")) {
        return true;
    }
    if (requestURI.contains("/login/token")) {
        return true;
    }
    String yamlContent = null;
    String protocol = (String) request.getProperty(PROTOCOL);
    Swagger swagger = null;
    if (requestURI.contains("/api/am/publisher")) {
        if (requestURI.contains("swagger.yaml")) {
            try {
                yamlContent = RestApiUtil.getPublisherRestAPIResource();
                response.setStatus(javax.ws.rs.core.Response.Status.OK.getStatusCode()).setEntity(yamlContent).setMediaType("text/x-yaml").send();
            } catch (APIManagementException e) {
                String msg = "Couldn't find swagger.yaml for publisher";
                ErrorDTO errorDTO = RestApiUtil.getErrorDTO(e.getErrorHandler());
                log.error(msg, e);
                response.setStatus(javax.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).setEntity(errorDTO).send();
            }
            return false;
        }
    } else if (requestURI.contains("/api/am/store")) {
        if (requestURI.contains("swagger.json")) {
            try {
                yamlContent = RestApiUtil.getStoreRestAPIResource();
                swagger = new SwaggerParser().parse(yamlContent);
                swagger.setBasePath(RestApiUtil.getContext(RestApiConstants.APPType.STORE));
                swagger.setHost(RestApiUtil.getHost(protocol.toLowerCase(Locale.ENGLISH)));
                response.setStatus(javax.ws.rs.core.Response.Status.OK.getStatusCode()).setEntity(Json.pretty(swagger)).setMediaType(MediaType.APPLICATION_JSON).send();
            } catch (APIManagementException e) {
                String msg = "Couldn't find swagger.json for store";
                ErrorDTO errorDTO = RestApiUtil.getErrorDTO(e.getErrorHandler());
                log.error(msg, e);
                response.setStatus(javax.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).setEntity(errorDTO).send();
            }
            return false;
        } else if (requestURI.contains("swagger.yaml")) {
            try {
                yamlContent = RestApiUtil.getStoreRestAPIResource();
                response.setStatus(javax.ws.rs.core.Response.Status.OK.getStatusCode()).setEntity(yamlContent).setMediaType("text/x-yaml").send();
            } catch (APIManagementException e) {
                String msg = "Couldn't find swagger.yaml for store";
                ErrorDTO errorDTO = RestApiUtil.getErrorDTO(e.getErrorHandler());
                log.error(msg, e);
                response.setStatus(javax.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).setEntity(errorDTO).send();
            }
            return false;
        }
    } else if (requestURI.contains("/api/am/analytics")) {
        if (requestURI.contains("swagger.json")) {
            try {
                yamlContent = RestApiUtil.getAnalyticsRestAPIResource();
                swagger = new SwaggerParser().parse(yamlContent);
                swagger.setBasePath(RestApiUtil.getContext(RestApiConstants.APPType.ANALYTICS));
                swagger.setHost(RestApiUtil.getHost(protocol.toLowerCase(Locale.ENGLISH)));
            } catch (APIManagementException e) {
                log.error("Couldn't find swagger.json for analytics", e);
            }
            response.setStatus(javax.ws.rs.core.Response.Status.OK.getStatusCode()).setEntity(Json.pretty(swagger)).setMediaType(MediaType.APPLICATION_JSON).send();
            return false;
        }
    } else if (requestURI.contains("/editor") || requestURI.contains("keyserver") || requestURI.contains("core") || requestURI.contains("/api/am/config")) {
        return true;
    } else if (requestURI.contains("/api/am/admin")) {
        if (requestURI.contains("swagger.json")) {
            try {
                yamlContent = RestApiUtil.getAdminRestAPIResource();
                swagger = new SwaggerParser().parse(yamlContent);
                swagger.setBasePath(RestApiUtil.getContext(RestApiConstants.APPType.ADMIN));
                swagger.setHost(RestApiUtil.getHost(protocol.toLowerCase(Locale.ENGLISH)));
                response.setStatus(javax.ws.rs.core.Response.Status.OK.getStatusCode()).setEntity(Json.pretty(swagger)).setMediaType(MediaType.APPLICATION_JSON).send();
            } catch (APIManagementException e) {
                String msg = "Couldn't find swagger.yaml for admin";
                ErrorDTO errorDTO = RestApiUtil.getErrorDTO(e.getErrorHandler());
                log.error(msg, e);
                response.setStatus(javax.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).setEntity(errorDTO).send();
            }
            return false;
        } else if (requestURI.contains("swagger.yaml")) {
            try {
                yamlContent = RestApiUtil.getAdminRestAPIResource();
                response.setStatus(javax.ws.rs.core.Response.Status.OK.getStatusCode()).setEntity(yamlContent).setMediaType("text/x-yaml").send();
            } catch (APIManagementException e) {
                String msg = "Couldn't find swagger.yaml for admin";
                ErrorDTO errorDTO = RestApiUtil.getErrorDTO(e.getErrorHandler());
                log.error(msg, e);
                response.setStatus(javax.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).setEntity(errorDTO).send();
            }
            return false;
        }
    }
    try {
        if (authenticatorImplClass == null) {
            Class<?> implClass = null;
            try {
                implClass = Class.forName(authenticatorName);
            } catch (ClassNotFoundException e) {
                throw new APIMgtSecurityException("Error while loading class " + authenticatorName, e);
            }
            authenticatorImplClass = (RESTAPIAuthenticator) implClass.newInstance();
        }
        isAuthenticated = authenticatorImplClass.authenticate(request, response, serviceMethodInfo);
    } catch (APIMgtSecurityException e) {
        errorHandler = e.getErrorHandler();
        log.error(e.getMessage() + " Requested Path: " + request.getUri());
    } catch (InstantiationException e) {
        log.error(e.getMessage() + " Error while instantiating authenticator: " + authenticatorName);
        isAuthenticated = false;
        errorHandler = ExceptionCodes.AUTH_GENERAL_ERROR;
    } catch (IllegalAccessException e) {
        log.error(e.getMessage() + " Error while accessing resource : " + authenticatorName);
        isAuthenticated = false;
        errorHandler = ExceptionCodes.AUTH_GENERAL_ERROR;
    }
    if (!isAuthenticated) {
        handleSecurityError(errorHandler, response);
    }
    return isAuthenticated;
}
Also used : SwaggerParser(io.swagger.parser.SwaggerParser) ErrorHandler(org.wso2.carbon.apimgt.core.exception.ErrorHandler) APIManagementException(org.wso2.carbon.apimgt.core.exception.APIManagementException) APIMgtSecurityException(org.wso2.carbon.apimgt.rest.api.common.exception.APIMgtSecurityException) ErrorDTO(org.wso2.carbon.apimgt.rest.api.common.dto.ErrorDTO) Swagger(io.swagger.models.Swagger)

Example 2 with RestAPIAuthenticator

use of org.wso2.carbon.apimgt.rest.api.common.RestAPIAuthenticator in project carbon-apimgt by wso2.

the class OAuthAuthenticationInterceptor method handleMessage.

@Override
@MethodStats
public void handleMessage(Message inMessage) {
    // by-passes the interceptor if user calls an anonymous api
    if (RestApiUtil.checkIfAnonymousAPI(inMessage)) {
        return;
    }
    HashMap<String, Object> authContext = JWTAuthenticationUtils.addToJWTAuthenticationContext(inMessage);
    RestAPIAuthenticator authenticator = RestAPIAuthenticationManager.getAuthenticator(authContext);
    if (authenticator != null) {
        try {
            String authenticationType = authenticator.getAuthenticationType();
            inMessage.put(RestApiConstants.REQUEST_AUTHENTICATION_SCHEME, authenticator.getAuthenticationType());
            String basePath = (String) inMessage.get(RestApiConstants.BASE_PATH);
            String version = (String) inMessage.get(RestApiConstants.API_VERSION);
            authContext.put(RestApiConstants.URI_TEMPLATES, RestApiUtil.getURITemplatesForBasePath(basePath + version));
            authContext.put(RestApiConstants.ORG_ID, RestApiUtil.resolveOrganization(inMessage));
            if (authenticator.authenticate(authContext)) {
                inMessage = JWTAuthenticationUtils.addToMessageContext(inMessage, authContext);
                if (logger.isDebugEnabled()) {
                    logger.debug("Request has been Authenticated , authentication type : " + authenticationType);
                }
            } else {
                logger.error("Failed to Authenticate , authentication type : " + authenticationType);
                throw new AuthenticationException("Unauthenticated request");
            }
        } catch (APIManagementException e) {
            logger.error("Authentication Failure " + e.getMessage());
            return;
        }
    }
    // Following logic will be moved to separate class in near future
    if (authenticator == null) {
        String accessToken = RestApiUtil.extractOAuthAccessTokenFromMessage(inMessage, RestApiConstants.REGEX_BEARER_PATTERN, RestApiConstants.AUTH_HEADER_NAME);
        // add masked token to the Message
        inMessage.put(RestApiConstants.MASKED_TOKEN, APIUtil.getMaskedToken(accessToken));
        if (accessToken == null) {
            return;
        }
        if (accessToken.contains(RestApiConstants.DOT)) {
            inMessage.put(RestApiConstants.REQUEST_AUTHENTICATION_SCHEME, RestApiConstants.JWT_AUTHENTICATION);
        } else {
            inMessage.put(RestApiConstants.REQUEST_AUTHENTICATION_SCHEME, RestApiConstants.OPAQUE_AUTHENTICATION);
        }
        try {
            if (logger.isDebugEnabled()) {
                logger.debug(String.format("Authenticating request with : " + inMessage.get(RestApiConstants.REQUEST_AUTHENTICATION_SCHEME)) + "Authentication");
            }
            AbstractOAuthAuthenticator abstractOAuthAuthenticator = authenticatorMap.get(inMessage.get(RestApiConstants.REQUEST_AUTHENTICATION_SCHEME));
            logger.debug("Selected Authenticator for the token validation " + abstractOAuthAuthenticator);
            if (abstractOAuthAuthenticator.authenticate(inMessage)) {
                if (logger.isDebugEnabled()) {
                    logger.debug("User logged into Web app using OAuth Authentication");
                }
            } else {
                throw new AuthenticationException("Unauthenticated request");
            }
        } catch (APIManagementException e) {
            logger.error("Error while authenticating incoming request to API Manager REST API", e);
        }
    }
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) AuthenticationException(org.apache.cxf.interceptor.security.AuthenticationException) AbstractOAuthAuthenticator(org.wso2.carbon.apimgt.rest.api.util.authenticators.AbstractOAuthAuthenticator) RestAPIAuthenticator(org.wso2.carbon.apimgt.rest.api.common.RestAPIAuthenticator) MethodStats(org.wso2.carbon.apimgt.rest.api.util.MethodStats)

Aggregations

Swagger (io.swagger.models.Swagger)1 SwaggerParser (io.swagger.parser.SwaggerParser)1 AuthenticationException (org.apache.cxf.interceptor.security.AuthenticationException)1 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)1 APIManagementException (org.wso2.carbon.apimgt.core.exception.APIManagementException)1 ErrorHandler (org.wso2.carbon.apimgt.core.exception.ErrorHandler)1 RestAPIAuthenticator (org.wso2.carbon.apimgt.rest.api.common.RestAPIAuthenticator)1 ErrorDTO (org.wso2.carbon.apimgt.rest.api.common.dto.ErrorDTO)1 APIMgtSecurityException (org.wso2.carbon.apimgt.rest.api.common.exception.APIMgtSecurityException)1 MethodStats (org.wso2.carbon.apimgt.rest.api.util.MethodStats)1 AbstractOAuthAuthenticator (org.wso2.carbon.apimgt.rest.api.util.authenticators.AbstractOAuthAuthenticator)1