Search in sources :

Example 1 with ISecurityHandler

use of nl.nn.adapterframework.core.ISecurityHandler in project iaf by ibissource.

the class HttpListenerServlet method invoke.

public void invoke(String message, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
    ISecurityHandler securityHandler = new HttpSecurityHandler(request);
    IPipeLineSession messageContext = new PipeLineSessionBase();
    messageContext.put(IPipeLineSession.securityHandlerKey, securityHandler);
    messageContext.put("httpListenerServletRequest", request);
    messageContext.put("httpListenerServletResponse", response);
    String service = request.getParameter(SERVICE_ID_PARAM);
    Enumeration paramnames = request.getParameterNames();
    while (paramnames.hasMoreElements()) {
        String paramname = (String) paramnames.nextElement();
        String paramvalue = request.getParameter(paramname);
        if (log.isDebugEnabled()) {
            log.debug("HttpListenerServlet setting parameter [" + paramname + "] to [" + paramvalue + "]");
        }
        messageContext.put(paramname, paramvalue);
    }
    try {
        log.debug("HttpListenerServlet calling service [" + service + "]");
        String result = sd.dispatchRequest(service, null, message, messageContext);
        response.getWriter().print(result);
    } catch (ListenerException e) {
        log.warn("HttpListenerServlet caught exception, will rethrow as ServletException", e);
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
    }
}
Also used : ISecurityHandler(nl.nn.adapterframework.core.ISecurityHandler) ListenerException(nl.nn.adapterframework.core.ListenerException) Enumeration(java.util.Enumeration) IPipeLineSession(nl.nn.adapterframework.core.IPipeLineSession) PipeLineSessionBase(nl.nn.adapterframework.core.PipeLineSessionBase)

Example 2 with ISecurityHandler

use of nl.nn.adapterframework.core.ISecurityHandler in project iaf by ibissource.

the class RestListenerServlet method service.

protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    String path = request.getPathInfo();
    String restPath = request.getServletPath();
    String body = "";
    if (restPath.contains("rest-public")) {
        response.setHeader("Access-Control-Allow-Origin", "*");
        String headers = request.getHeader("Access-Control-Request-Headers");
        if (headers != null)
            response.setHeader("Access-Control-Allow-Headers", headers);
        response.setHeader("Access-Control-Expose-Headers", "ETag, Content-Disposition");
        String pattern = sd.findMatchingPattern(path);
        if (pattern != null) {
            Map methodConfig = sd.getMethodConfig(pattern, "OPTIONS");
            if (methodConfig == null) {
                // If set, it means the adapter handles the OPTIONS request
                Iterator iter = sd.getAvailableMethods(pattern).iterator();
                StringBuilder sb = new StringBuilder();
                // Append preflight OPTIONS request
                sb.append("OPTIONS");
                while (iter.hasNext()) {
                    sb.append(", ").append(iter.next());
                }
                response.setHeader("Access-Control-Allow-Methods", sb.toString());
                if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
                    response.setStatus(200);
                    // Preflight OPTIONS request should not return any data.
                    return;
                }
            }
        }
    }
    String ifNoneMatch = request.getHeader("If-None-Match");
    String ifMatch = request.getHeader("If-Match");
    String contentType = request.getHeader("accept");
    if (log.isTraceEnabled())
        log.trace("path [" + path + "] If-Match [" + ifMatch + "] If-None-Match [" + ifNoneMatch + "] contentType [" + contentType + "]");
    ISecurityHandler securityHandler = new HttpSecurityHandler(request);
    IPipeLineSession messageContext = new PipeLineSessionBase();
    messageContext.put(IPipeLineSession.securityHandlerKey, securityHandler);
    Enumeration paramnames = request.getParameterNames();
    while (paramnames.hasMoreElements()) {
        String paramname = (String) paramnames.nextElement();
        String paramvalue = request.getParameter(paramname);
        if (log.isTraceEnabled())
            log.trace("setting parameter [" + paramname + "] to [" + paramvalue + "]");
        messageContext.put(paramname, paramvalue);
    }
    if (!ServletFileUpload.isMultipartContent(request)) {
        body = Misc.streamToString(request.getInputStream(), "\n", false);
    }
    try {
        log.trace("RestListenerServlet calling service [" + path + "]");
        String result = sd.dispatchRequest(restPath, path, request, contentType, body, messageContext, response, getServletContext());
        if (result == null && messageContext.containsKey("exitcode") && messageContext.containsKey("validateEtag")) {
            int status = Integer.parseInt("" + messageContext.get("exitcode"));
            response.setStatus(status);
            // TODO: overbodig?
            if (log.isDebugEnabled())
                log.trace("aborted request with status [" + status + "]");
            return;
        }
        String etag = (String) messageContext.get("etag");
        if (StringUtils.isNotEmpty(etag))
            response.setHeader("etag", etag);
        int statusCode = 0;
        if (messageContext.containsKey("exitcode"))
            statusCode = Integer.parseInt("" + messageContext.get("exitcode"));
        if (statusCode > 0)
            response.setStatus(statusCode);
        if (StringUtils.isEmpty(result)) {
            log.trace("RestListenerServlet finished with result set in pipeline");
        } else {
            contentType = (String) messageContext.get("contentType");
            if (StringUtils.isNotEmpty(contentType)) {
                response.setHeader("Content-Type", contentType);
            }
            String contentDisposition = (String) messageContext.get("contentDisposition");
            if (StringUtils.isNotEmpty(contentDisposition)) {
                response.setHeader("Content-Disposition", contentDisposition);
            }
            String allowedMethods = (String) messageContext.get("allowedMethods");
            if (StringUtils.isNotEmpty(allowedMethods)) {
                response.setHeader("Allow", allowedMethods);
            }
            response.getWriter().print(result);
            log.trace("RestListenerServlet finished with result [" + result + "] etag [" + etag + "] contentType [" + contentType + "] contentDisposition [" + contentDisposition + "]");
        }
    } catch (ListenerException e) {
        log.warn("RestListenerServlet caught exception, will rethrow as ServletException", e);
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
    }
}
Also used : ISecurityHandler(nl.nn.adapterframework.core.ISecurityHandler) ListenerException(nl.nn.adapterframework.core.ListenerException) Enumeration(java.util.Enumeration) Iterator(java.util.Iterator) HashMap(java.util.HashMap) Map(java.util.Map) IPipeLineSession(nl.nn.adapterframework.core.IPipeLineSession) PipeLineSessionBase(nl.nn.adapterframework.core.PipeLineSessionBase)

Example 3 with ISecurityHandler

use of nl.nn.adapterframework.core.ISecurityHandler in project iaf by ibissource.

the class SoapGenericProvider method invoke.

public void invoke(SOAPContext reqContext, SOAPContext resContext) throws SOAPException {
    try {
        String targetObjectURI = (String) reqContext.getProperty(TARGET_OBJECT_URI_KEY);
        if (log.isDebugEnabled()) {
            log.debug("Invoking service for targetObjectURI=[" + targetObjectURI + "]");
        }
        // String message=soapWrapper.getBody(reqContext.getBodyPart(0).getContent().toString());
        String message = reqContext.getBodyPart(0).getContent().toString();
        HttpServletRequest httpRequest = (HttpServletRequest) reqContext.getProperty(Constants.BAG_HTTPSERVLETREQUEST);
        HttpServletResponse httpResponse = (HttpServletResponse) reqContext.getProperty(Constants.BAG_HTTPSERVLETRESPONSE);
        ISecurityHandler securityHandler = new HttpSecurityHandler(httpRequest);
        Map messageContext = new HashMap();
        messageContext.put(IPipeLineSession.securityHandlerKey, securityHandler);
        messageContext.put("httpListenerServletRequest", httpRequest);
        messageContext.put("httpListenerServletResponse", httpResponse);
        String result = sd.dispatchRequest(targetObjectURI, null, message, messageContext);
        // resContext.setRootPart( soapWrapper.putInEnvelope(result,null), Constants.HEADERVAL_CONTENT_TYPE_UTF8);
        resContext.setRootPart(result, Constants.HEADERVAL_CONTENT_TYPE_UTF8);
    } catch (Exception e) {
        // log.warn("GenericSoapProvider caught exception:",e);
        if (e instanceof SOAPException) {
            throw (SOAPException) e;
        }
        SOAPException se = new SOAPException(Constants.FAULT_CODE_SERVER, "GenericSoapProvider caught exception");
        se.initCause(e);
        throw se;
    }
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) ISecurityHandler(nl.nn.adapterframework.core.ISecurityHandler) HashMap(java.util.HashMap) SOAPException(org.apache.soap.SOAPException) HttpServletResponse(javax.servlet.http.HttpServletResponse) HttpSecurityHandler(nl.nn.adapterframework.http.HttpSecurityHandler) HashMap(java.util.HashMap) Map(java.util.Map) SOAPException(org.apache.soap.SOAPException)

Example 4 with ISecurityHandler

use of nl.nn.adapterframework.core.ISecurityHandler in project iaf by ibissource.

the class JavaListener method processRequest.

@Override
public String processRequest(String correlationId, String message, HashMap context) throws ListenerException {
    if (!isOpen()) {
        throw new ListenerException("JavaListener [" + getName() + "] is not opened");
    }
    if (log.isDebugEnabled()) {
        log.debug("JavaListener [" + getName() + "] processing correlationId [" + correlationId + "]");
    }
    if (context != null) {
        Object object = context.get("httpRequest");
        if (object != null) {
            if (object instanceof HttpServletRequest) {
                ISecurityHandler securityHandler = new HttpSecurityHandler((HttpServletRequest) object);
                context.put(IPipeLineSession.securityHandlerKey, securityHandler);
            } else {
                log.warn("No securityHandler added for httpRequest [" + object.getClass() + "]");
            }
        }
    }
    if (throwException) {
        return handler.processRequest(this, correlationId, message, context);
    } else {
        try {
            return handler.processRequest(this, correlationId, message, context);
        } catch (ListenerException e) {
            return handler.formatException(null, correlationId, message, e);
        }
    }
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) ListenerException(nl.nn.adapterframework.core.ListenerException) ISecurityHandler(nl.nn.adapterframework.core.ISecurityHandler) HttpSecurityHandler(nl.nn.adapterframework.http.HttpSecurityHandler)

Example 5 with ISecurityHandler

use of nl.nn.adapterframework.core.ISecurityHandler in project iaf by ibissource.

the class ApiListenerServlet method service.

protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    /**
     * Initiate and populate messageContext
     */
    IPipeLineSession messageContext = new PipeLineSessionBase();
    messageContext.put(IPipeLineSession.HTTP_REQUEST_KEY, request);
    messageContext.put(IPipeLineSession.HTTP_RESPONSE_KEY, response);
    messageContext.put(IPipeLineSession.SERVLET_CONTEXT_KEY, getServletContext());
    ISecurityHandler securityHandler = new HttpSecurityHandler(request);
    messageContext.put(IPipeLineSession.securityHandlerKey, securityHandler);
    try {
        String uri = request.getPathInfo();
        String method = request.getMethod().toUpperCase();
        log.trace("ApiListenerServlet dispatching uri [" + uri + "] and method [" + method + "]");
        if (uri == null) {
            response.setStatus(400);
            log.warn("Aborting request with status [400], empty uri");
            return;
        }
        if (uri.startsWith("/"))
            uri = uri.substring(1);
        if (uri.endsWith("/"))
            uri = uri.substring(0, uri.length() - 1);
        ApiDispatchConfig config = dispatcher.findConfigForUri(uri);
        if (config == null) {
            response.setStatus(404);
            log.trace("Aborting request with status [404], no ApiListener configured for [" + uri + "]");
            return;
        }
        /**
         * Handle Cross-Origin Resource Sharing
         */
        if (method.equals("OPTIONS")) {
            response.setHeader("Access-Control-Allow-Origin", CorsAllowOrigin);
            String headers = request.getHeader("Access-Control-Request-Headers");
            if (headers != null)
                response.setHeader("Access-Control-Allow-Headers", headers);
            response.setHeader("Access-Control-Expose-Headers", CorsExposeHeaders);
            StringBuilder methods = new StringBuilder();
            for (String mtd : config.getMethods()) {
                methods.append(", ").append(mtd);
            }
            response.setHeader("Access-Control-Allow-Methods", methods.toString());
            response.setStatus(200);
            log.trace("Aborting preflight request with status [200], method [" + method + "]");
            return;
        }
        /**
         * Get serviceClient
         */
        ApiListener listener = config.getApiListener(method);
        if (listener == null) {
            response.setStatus(405);
            log.trace("Aborting request with status [405], method [" + method + "] not allowed");
            return;
        }
        log.trace("ApiListenerServlet calling service [" + listener.getName() + "]");
        /**
         * Check authentication
         */
        ApiPrincipal userPrincipal = null;
        if (listener.getAuthenticationMethod() != null) {
            String authorizationToken = null;
            Cookie authorizationCookie = null;
            if (listener.getAuthenticationMethod().equals("COOKIE")) {
                Cookie[] cookies = request.getCookies();
                for (Cookie cookie : cookies) {
                    if (cookie.getName().equals("authenticationToken")) {
                        authorizationToken = cookie.getValue();
                        authorizationCookie = cookie;
                        authorizationCookie.setPath("/");
                    }
                }
            } else if (listener.getAuthenticationMethod().equals("HEADER")) {
                authorizationToken = request.getHeader("Authorization");
            }
            if (authorizationToken != null && cache.containsKey(authorizationToken))
                userPrincipal = (ApiPrincipal) cache.get(authorizationToken);
            if (userPrincipal == null || !userPrincipal.isLoggedIn()) {
                cache.remove(authorizationToken);
                if (authorizationCookie != null) {
                    authorizationCookie.setMaxAge(0);
                    response.addCookie(authorizationCookie);
                }
                response.setStatus(401);
                log.trace("Aborting request with status [401], no (valid) credentials supplied");
                return;
            }
            if (authorizationCookie != null) {
                authorizationCookie.setMaxAge(authTTL);
                response.addCookie(authorizationCookie);
            }
            userPrincipal.updateExpiry();
            userPrincipal.setToken(authorizationToken);
            cache.put(authorizationToken, userPrincipal, authTTL);
            messageContext.put("authorizationToken", authorizationToken);
        }
        messageContext.put("remoteAddr", request.getRemoteAddr());
        messageContext.put(IPipeLineSession.API_PRINCIPAL_KEY, userPrincipal);
        messageContext.put("uri", uri);
        /**
         * Evaluate preconditions
         */
        String accept = request.getHeader("Accept");
        if (accept != null && !accept.isEmpty() && !accept.equals("*/*")) {
            if (!listener.getProduces().equals("ANY") && !accept.contains(listener.getContentType())) {
                response.setStatus(406);
                response.getWriter().print("It appears you expected the MediaType [" + accept + "] but I only support the MediaType [" + listener.getContentType() + "] :)");
                log.trace("Aborting request with status [406], client expects [" + accept + "] got [" + listener.getContentType() + "] instead");
                return;
            }
        }
        if (request.getContentType() != null && !listener.isConsumable(request.getContentType())) {
            response.setStatus(415);
            log.trace("Aborting request with status [415], did not match consumes [" + listener.getConsumes() + "] got [" + request.getContentType() + "] instead");
            return;
        }
        String etagCacheKey = ApiCacheManager.buildCacheKey(config.getUriPattern());
        if (cache.containsKey(etagCacheKey)) {
            String cachedEtag = (String) cache.get(etagCacheKey);
            if (method.equals("GET")) {
                String ifNoneMatch = request.getHeader("If-None-Match");
                if (ifNoneMatch != null && ifNoneMatch.equals(cachedEtag)) {
                    response.setStatus(304);
                    log.trace("Aborting request with status [304], matched if-none-match [" + ifNoneMatch + "]");
                    return;
                }
            } else {
                String ifMatch = request.getHeader("If-Match");
                if (ifMatch != null && !ifMatch.equals(cachedEtag)) {
                    response.setStatus(412);
                    log.trace("Aborting request with status [412], matched if-match [" + ifMatch + "] method [" + method + "]");
                    return;
                }
            }
        }
        /**
         * Check authorization
         */
        // TODO: authentication implementation
        /**
         * Map uriIdentifiers into messageContext
         */
        String[] patternSegments = listener.getUriPattern().split("/");
        String[] uriSegments = uri.split("/");
        int uriIdentifier = 0;
        for (int i = 0; i < patternSegments.length; i++) {
            String segment = patternSegments[i];
            if (segment.startsWith("{") && segment.endsWith("}")) {
                String name;
                if (segment.equals("*"))
                    name = "uriIdentifier_" + uriIdentifier;
                else
                    name = segment.substring(1, segment.length() - 1);
                uriIdentifier++;
                log.trace("setting uriSegment [" + name + "] to [" + uriSegments[i] + "]");
                messageContext.put(name, uriSegments[i]);
            }
        }
        /**
         * Map queryParameters into messageContext
         */
        Enumeration<?> paramnames = request.getParameterNames();
        while (paramnames.hasMoreElements()) {
            String paramname = (String) paramnames.nextElement();
            String paramvalue = request.getParameter(paramname);
            log.trace("setting queryParameter [" + paramname + "] to [" + paramvalue + "]");
            messageContext.put(paramname, paramvalue);
        }
        /**
         * Map multipart parts into messageContext
         */
        if (ServletFileUpload.isMultipartContent(request)) {
            DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
            ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory);
            List<FileItem> items = servletFileUpload.parseRequest(request);
            for (FileItem item : items) {
                if (item.isFormField()) {
                    // Process regular form field (input type="text|radio|checkbox|etc", select, etc).
                    String fieldName = item.getFieldName();
                    String fieldValue = item.getString();
                    log.trace("setting multipart formField [" + fieldName + "] to [" + fieldValue + "]");
                    messageContext.put(fieldName, fieldValue);
                } else {
                    // Process form file field (input type="file").
                    String fieldName = item.getFieldName();
                    String fieldNameName = fieldName + "Name";
                    String fileName = FilenameUtils.getName(item.getName());
                    log.trace("setting multipart formFile [" + fieldNameName + "] to [" + fileName + "]");
                    messageContext.put(fieldNameName, fileName);
                    log.trace("setting parameter [" + fieldName + "] to input stream of file [" + fileName + "]");
                    messageContext.put(fieldName, item.getInputStream());
                }
            }
        }
        /**
         * Compile Allow header
         */
        StringBuilder methods = new StringBuilder();
        methods.append("OPTIONS, ");
        for (String mtd : config.getMethods()) {
            methods.append(mtd + ", ");
        }
        messageContext.put("allowedMethods", methods.substring(0, methods.length() - 2));
        /**
         * Process the request through the pipeline
         */
        String body = "";
        if (!ServletFileUpload.isMultipartContent(request)) {
            body = Misc.streamToString(request.getInputStream(), "\n", false);
        }
        String result = listener.processRequest(null, body, messageContext);
        /**
         * Calculate an etag over the processed result and store in cache
         */
        if (listener.getUpdateEtag()) {
            if (result != null && method.equals("GET")) {
                String eTag = ApiCacheManager.buildEtag(listener.getCleanPattern(), result.hashCode());
                cache.put(etagCacheKey, eTag);
                response.addHeader("etag", eTag);
            } else {
                cache.remove(etagCacheKey);
            }
        }
        /**
         * Add headers
         */
        response.addHeader("Allow", (String) messageContext.get("allowedMethods"));
        String contentType = listener.getContentType() + "; charset=utf-8";
        if (listener.getProduces().equals("ANY")) {
            contentType = (String) messageContext.get("contentType");
        }
        response.setHeader("Content-Type", contentType);
        /**
         * Check if an exitcode has been defined or if a statuscode has been added to the messageContext.
         */
        int statusCode = 0;
        if (messageContext.containsKey("exitcode"))
            statusCode = Integer.parseInt("" + messageContext.get("exitcode"));
        if (statusCode > 0)
            response.setStatus(statusCode);
        /**
         * Finalize the pipeline and write the result to the response
         */
        if (result != null)
            response.getWriter().print(result);
        log.trace("ApiListenerServlet finished with statusCode [" + statusCode + "] result [" + result + "]");
    } catch (Exception e) {
        log.warn("ApiListenerServlet caught exception, will rethrow as ServletException", e);
        try {
            response.flushBuffer();
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
        } catch (IllegalStateException ex) {
            // We're only informing the end user(s), no need to catch this error...
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    }
}
Also used : Cookie(javax.servlet.http.Cookie) ISecurityHandler(nl.nn.adapterframework.core.ISecurityHandler) DiskFileItemFactory(org.apache.commons.fileupload.disk.DiskFileItemFactory) ServletException(javax.servlet.ServletException) IOException(java.io.IOException) FileItem(org.apache.commons.fileupload.FileItem) ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) HttpSecurityHandler(nl.nn.adapterframework.http.HttpSecurityHandler) IPipeLineSession(nl.nn.adapterframework.core.IPipeLineSession) PipeLineSessionBase(nl.nn.adapterframework.core.PipeLineSessionBase)

Aggregations

ISecurityHandler (nl.nn.adapterframework.core.ISecurityHandler)5 IPipeLineSession (nl.nn.adapterframework.core.IPipeLineSession)3 ListenerException (nl.nn.adapterframework.core.ListenerException)3 PipeLineSessionBase (nl.nn.adapterframework.core.PipeLineSessionBase)3 HttpSecurityHandler (nl.nn.adapterframework.http.HttpSecurityHandler)3 Enumeration (java.util.Enumeration)2 HashMap (java.util.HashMap)2 Map (java.util.Map)2 HttpServletRequest (javax.servlet.http.HttpServletRequest)2 IOException (java.io.IOException)1 Iterator (java.util.Iterator)1 ServletException (javax.servlet.ServletException)1 Cookie (javax.servlet.http.Cookie)1 HttpServletResponse (javax.servlet.http.HttpServletResponse)1 FileItem (org.apache.commons.fileupload.FileItem)1 DiskFileItemFactory (org.apache.commons.fileupload.disk.DiskFileItemFactory)1 ServletFileUpload (org.apache.commons.fileupload.servlet.ServletFileUpload)1 SOAPException (org.apache.soap.SOAPException)1