Example usage for javax.servlet.http HttpServletRequest authenticate

List of usage examples for javax.servlet.http HttpServletRequest authenticate

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletRequest authenticate.

Prototype

public boolean authenticate(HttpServletResponse response) throws IOException, ServletException;

Source Link

Document

Use the container login mechanism configured for the ServletContext to authenticate the user making this request.

Usage

From source file:com.almende.eve.transport.http.DebugServlet.java

/**
 * Handle session.//ww  w .  j a v  a 2  s  .  c o  m
 * 
 * @param req
 *            the req
 * @param res
 *            the res
 * @return true, if successful
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 */
private boolean handleSession(final HttpServletRequest req, final HttpServletResponse res) throws IOException {
    try {

        if (req.getSession(false) != null) {
            return true;
        }
        // TODO: make sure connection is secure if configured to enforce
        // that.
        final Handshake hs = doHandShake(req);
        if (hs.equals(Handshake.INVALID)) {
            return false;
        }

        final boolean doAuthentication = HttpService.doAuthentication(myUrl);
        if (hs.equals(Handshake.NAK) && doAuthentication) {
            if (!req.isSecure()) {
                res.sendError(HttpServletResponse.SC_BAD_REQUEST,
                        "Request needs to be secured with SSL for session management!");
                return false;
            }
            if (!req.authenticate(res)) {
                return false;
            }
        }
        // generate new session:
        req.getSession(true);
    } catch (final Exception e) {
        res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                "Exception running HandleSession:" + e.getMessage());
        LOG.log(Level.WARNING, "", e);
        return false;
    }
    return true;
}

From source file:com.almende.eve.transport.http.AgentServlet.java

/**
 * Handle session./* ww  w  .j ava2s .co m*/
 * 
 * @param req
 *            the req
 * @param res
 *            the res
 * @return true, if successful
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 */
private boolean handleSession(final HttpServletRequest req, final HttpServletResponse res) throws IOException {
    try {

        if (req.getSession(false) != null) {
            return true;
        }

        final Handshake hs = doHandShake(req);
        if (hs.equals(Handshake.INVALID)) {
            return false;
        }

        String doAuthenticationStr = AgentListener.getParam("eve_authentication");
        if (doAuthenticationStr == null) {
            // TODO: authentication param is deprecated since v2.0. Cleanup
            // some day
            doAuthenticationStr = AgentListener.getParam("authentication");
            if (doAuthenticationStr == null) {
                doAuthenticationStr = "true";
                LOG.warning("context-param \"eve_authentication\" not found. Using default value "
                        + doAuthenticationStr);
            } else {
                LOG.warning(
                        "context-param \"authentication\" is deprecated. Use \"eve_authentication\" instead.");
            }
        }
        final Boolean doAuthentication = Boolean.parseBoolean(doAuthenticationStr);

        if (hs.equals(Handshake.NAK) && doAuthentication) {
            if (!req.isSecure()) {
                res.sendError(HttpServletResponse.SC_BAD_REQUEST,
                        "Request needs to be secured with SSL for session management!");
                return false;
            }
            if (!req.authenticate(res)) {
                return false;
            }
        }
        // generate new session:
        req.getSession(true);
    } catch (final Exception e) {
        res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                "Exception running HandleSession:" + e.getMessage());
        LOG.log(Level.WARNING, "", e);
        return false;
    }
    return true;
}

From source file:net.yacy.http.servlets.YaCyDefaultServlet.java

/**
 * Handles a YaCy servlet template, reads the template and replaces the template
 * items with actual values. Because of supported server side includes target 
 * might not be the same as request.getPathInfo
 * /*w ww  .j  av a2  s . c  o m*/
 * @param target the path to the template
 * @param request the remote servlet request
 * @param response
 * @throws IOException
 * @throws ServletException
 */
protected void handleTemplate(String target, HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    Switchboard sb = Switchboard.getSwitchboard();

    String localeSelection = sb.getConfig("locale.language", "browser");
    if (localeSelection.endsWith("browser")) {
        String lng = request.getLocale().getLanguage();
        if (lng.equalsIgnoreCase("en")) { // because en is handled as "default" in localizer
            localeSelection = "default";
        } else {
            localeSelection = lng;
        }
    }
    File targetFile = getLocalizedFile(target, localeSelection);
    File targetClass = rewriteClassFile(_resourceBase.addPath(target).getFile());
    String targetExt = target.substring(target.lastIndexOf('.') + 1);

    long now = System.currentTimeMillis();
    if (target.endsWith(".css")) {
        response.setDateHeader(HeaderFramework.LAST_MODIFIED, now);
        response.setDateHeader(HeaderFramework.EXPIRES, now + 3600000); // expires in 1 hour (which is still often, others use 1 week, month or year)
    } else if (target.endsWith(".png")) {
        // expires in 1 minute (reduce heavy image creation load)
        if (response.containsHeader(HeaderFramework.LAST_MODIFIED)) {
            response.getHeaders(HeaderFramework.LAST_MODIFIED).clear();
        }
        response.setHeader(HeaderFramework.CACHE_CONTROL, "public, max-age=" + Integer.toString(60));
    } else {
        response.setDateHeader(HeaderFramework.LAST_MODIFIED, now);
        response.setDateHeader(HeaderFramework.EXPIRES, now); // expires now
    }

    if ((targetClass != null)) {
        serverObjects args = new serverObjects();
        Enumeration<String> argNames = request.getParameterNames(); // on ssi jetty dispatcher merged local ssi query parameters
        while (argNames.hasMoreElements()) {
            String argName = argNames.nextElement();
            // standard attributes are just pushed as string
            args.put(argName, request.getParameter(argName));
        }
        RequestHeader legacyRequestHeader = generateLegacyRequestHeader(request, target, targetExt);
        // add multipart-form fields to parameter
        if (ServletFileUpload.isMultipartContent(request)) {
            final String bodyEncoding = request.getHeader(HeaderFramework.CONTENT_ENCODING);
            if (HeaderFramework.CONTENT_ENCODING_GZIP.equalsIgnoreCase(bodyEncoding)) {
                parseMultipart(new GZIPRequestWrapper(request), args);
            } else {
                parseMultipart(request, args);
            }
        }
        // eof modification to read attribute
        Object tmp;
        try {
            if (args.isEmpty()) {
                // yacy servlets typically test for args != null (but not for args .isEmpty())
                tmp = invokeServlet(targetClass, legacyRequestHeader, null);
            } else {
                tmp = invokeServlet(targetClass, legacyRequestHeader, args);
            }
        } catch (InvocationTargetException e) {
            if (e.getCause() instanceof InvalidURLLicenceException) {
                /* A non authaurized user is trying to fetch a image with a bad or already released license code */
                response.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getCause().getMessage());
                return;
            }
            if (e.getCause() instanceof TemplateMissingParameterException) {
                /* A template is used but miss some required parameter */
                response.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getCause().getMessage());
                return;
            }
            ConcurrentLog.logException(e);
            throw new ServletException(targetFile.getAbsolutePath());
        } catch (IllegalArgumentException | IllegalAccessException e) {
            ConcurrentLog.logException(e);
            throw new ServletException(targetFile.getAbsolutePath());
        }

        if (tmp instanceof RasterPlotter || tmp instanceof EncodedImage || tmp instanceof Image) {

            net.yacy.cora.util.ByteBuffer result = null;

            if (tmp instanceof RasterPlotter) {
                final RasterPlotter yp = (RasterPlotter) tmp;
                // send an image to client
                result = RasterPlotter.exportImage(yp.getImage(), "png");
            } else if (tmp instanceof EncodedImage) {
                final EncodedImage yp = (EncodedImage) tmp;
                result = yp.getImage();
                /** When encodedImage is empty, return a code 500 rather than only an empty response 
                 * as it is better handled across different browsers */
                if (result == null || result.length() == 0) {
                    response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                    result.close();
                    return;
                }
                if (yp.isStatic()) { // static image never expires
                    response.setDateHeader(HeaderFramework.EXPIRES, now + 3600000); // expires in 1 hour
                }
            } else if (tmp instanceof Image) {
                final Image i = (Image) tmp;

                // generate an byte array from the generated image
                int width = i.getWidth(null);
                if (width < 0) {
                    width = 96; // bad hack
                }
                int height = i.getHeight(null);
                if (height < 0) {
                    height = 96; // bad hack
                }
                final BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
                bi.createGraphics().drawImage(i, 0, 0, width, height, null);
                result = RasterPlotter.exportImage(bi, targetExt);
            }

            updateRespHeadersForImages(target, response);
            final String mimeType = Classification.ext2mime(targetExt, MimeTypes.Type.TEXT_HTML.asString());
            response.setContentType(mimeType);
            response.setContentLength(result.length());
            response.setStatus(HttpServletResponse.SC_OK);

            result.writeTo(response.getOutputStream());
            result.close();
            return;
        }

        if (tmp instanceof InputStream) {
            /* Images and favicons can also be written directly from an inputStream */
            updateRespHeadersForImages(target, response);

            writeInputStream(response, targetExt, (InputStream) tmp);
            return;
        }

        servletProperties templatePatterns;
        if (tmp == null) {
            // if no args given, then tp will be an empty Hashtable object (not null)
            templatePatterns = new servletProperties();
        } else if (tmp instanceof servletProperties) {
            templatePatterns = (servletProperties) tmp;

            if (templatePatterns.getOutgoingHeader() != null) {
                // handle responseHeader entries set by servlet
                ResponseHeader tmpouthdr = templatePatterns.getOutgoingHeader();
                for (String hdrkey : tmpouthdr.keySet()) {
                    if (!HeaderFramework.STATUS_CODE.equals(hdrkey)) { // skip default init response status value (not std. )
                        String val = tmpouthdr.get(hdrkey);
                        if (!response.containsHeader(hdrkey) && val != null) { // to be on the safe side, add only new hdr (mainly used for CORS_ALLOW_ORIGIN)
                            response.setHeader(hdrkey, tmpouthdr.get(hdrkey));
                        }
                    }
                }
                // handle login cookie
                if (tmpouthdr.getCookiesEntries() != null) {
                    for (Cookie c : tmpouthdr.getCookiesEntries()) {
                        response.addCookie(c);
                    }
                }
            }
        } else {
            templatePatterns = new servletProperties((serverObjects) tmp);
        }

        // handle YaCy http commands
        // handle action auth: check if the servlets requests authentication
        if (templatePatterns.containsKey(serverObjects.ACTION_AUTHENTICATE)) {
            if (!request.authenticate(response)) {
                return;
            }
            //handle action forward
        } else if (templatePatterns.containsKey(serverObjects.ACTION_LOCATION)) {
            String location = templatePatterns.get(serverObjects.ACTION_LOCATION, "");

            if (location.isEmpty()) {
                location = request.getPathInfo();
            }
            //TODO: handle equivalent of this from httpdfilehandler
            // final ResponseHeader headers = getDefaultHeaders(request.getPathInfo());
            // headers.setAdditionalHeaderProperties(templatePatterns.getOutgoingHeader().getAdditionalHeaderProperties()); //put the cookies into the new header TODO: can we put all headerlines, without trouble?

            response.setHeader(HeaderFramework.LOCATION, location);
            response.setStatus(HttpServletResponse.SC_FOUND);
            return;
        }

        if (targetFile.exists() && targetFile.isFile() && targetFile.canRead()) {

            sb.setConfig("server.servlets.called",
                    appendPath(sb.getConfig("server.servlets.called", ""), target));
            if (args != null && !args.isEmpty()) {
                sb.setConfig("server.servlets.submitted",
                        appendPath(sb.getConfig("server.servlets.submitted", ""), target));
            }

            // add the application version, the uptime and the client name to every rewrite table
            templatePatterns.put(servletProperties.PEER_STAT_VERSION, yacyBuildProperties.getVersion());
            templatePatterns.put(servletProperties.PEER_STAT_UPTIME,
                    ((System.currentTimeMillis() - sb.startupTime) / 1000) / 60); // uptime in minutes
            templatePatterns.putHTML(servletProperties.PEER_STAT_CLIENTNAME, sb.peers.mySeed().getName());
            templatePatterns.putHTML(servletProperties.PEER_STAT_CLIENTID, sb.peers.myID());
            templatePatterns.put(servletProperties.PEER_STAT_MYTIME,
                    GenericFormatter.SHORT_SECOND_FORMATTER.format());
            templatePatterns.put(servletProperties.RELATIVE_BASE, YaCyDefaultServlet.getRelativeBase(target));
            Seed myPeer = sb.peers.mySeed();
            templatePatterns.put("newpeer", myPeer.getAge() >= 1 ? 0 : 1);
            templatePatterns.putHTML("newpeer_peerhash", myPeer.hash);
            boolean authorized = sb.adminAuthenticated(legacyRequestHeader) >= 2;
            templatePatterns.put("authorized", authorized ? 1 : 0); // used in templates and other html (e.g. to display lock/unlock symbol)

            templatePatterns.put("simpleheadernavbar",
                    sb.getConfig("decoration.simpleheadernavbar", "navbar-default"));

            // add navigation keys to enable or disable menu items
            templatePatterns.put("navigation-p2p",
                    sb.getConfigBool(SwitchboardConstants.DHT_ENABLED, true) || !sb.isRobinsonMode() ? 1 : 0);
            templatePatterns.put("navigation-p2p_authorized", authorized ? 1 : 0);
            String submitted = sb.getConfig("server.servlets.submitted", "");
            boolean crawler_enabled = true; /*
                                            submitted.contains("Crawler_p") ||
                                            submitted.contains("ConfigBasic") ||
                                            submitted.contains("Load_RSS_p");*/
            boolean advanced_enabled = crawler_enabled || submitted.contains("IndexImportMediawiki_p")
                    || submitted.contains("CrawlStart");
            templatePatterns.put("navigation-crawlmonitor", crawler_enabled);
            templatePatterns.put("navigation-crawlmonitor_authorized", authorized ? 1 : 0);
            templatePatterns.put("navigation-advanced", advanced_enabled);
            templatePatterns.put("navigation-advanced_authorized", authorized ? 1 : 0);
            templatePatterns.put(SwitchboardConstants.GREETING_HOMEPAGE,
                    sb.getConfig(SwitchboardConstants.GREETING_HOMEPAGE, ""));
            templatePatterns.put(SwitchboardConstants.GREETING_SMALL_IMAGE,
                    sb.getConfig(SwitchboardConstants.GREETING_SMALL_IMAGE, ""));
            templatePatterns.put(SwitchboardConstants.GREETING_IMAGE_ALT,
                    sb.getConfig(SwitchboardConstants.GREETING_IMAGE_ALT, ""));
            templatePatterns.put("clientlanguage", localeSelection);

            String mimeType = Classification.ext2mime(targetExt, MimeTypes.Type.TEXT_HTML.asString());

            InputStream fis;
            long fileSize = targetFile.length();

            if (fileSize <= Math.min(4 * 1024 * 1204, MemoryControl.available() / 100)) {
                // read file completely into ram, avoid that too many files are open at the same time
                fis = new ByteArrayInputStream(FileUtils.read(targetFile));
            } else {
                fis = new BufferedInputStream(new FileInputStream(targetFile));
            }

            // set response header
            response.setContentType(mimeType);
            response.setStatus(HttpServletResponse.SC_OK);
            ByteArrayOutputStream bas = new ByteArrayOutputStream(4096);
            try {
                // apply templates
                TemplateEngine.writeTemplate(targetFile.getName(), fis, bas, templatePatterns);

                // handle SSI
                parseSSI(bas.toByteArray(), request, response);
            } finally {
                try {
                    fis.close();
                } catch (IOException ignored) {
                    ConcurrentLog.warn("FILEHANDLER",
                            "YaCyDefaultServlet: could not close target file " + targetFile.getName());
                }

                try {
                    bas.close();
                } catch (IOException ignored) {
                    /* Should never happen with a ByteArrayOutputStream */
                }
            }
        }
    }
}

From source file:org.jc.exercicios.download.DownloadServlet.java

/**
 * Realiza o download de uma nota fiscal previamente emitida. Para encontrar
 * uma nota fiscal, so necessrios o cpf/cnpj do cliente (cpf_cnpj), a data
 * de emisso (dt_emissao) e o nmero da nota (num_nf). Somente a verso em
 * xml da nota fiscal permanece disponvel para download.
 *
 * @param req//  w  w  w  .  ja va2s .c  o  m
 * @param resp
 * @throws ServletException
 * @throws IOException
 */
@Override
protected void doGet(final HttpServletRequest req, final HttpServletResponse resp)
        throws ServletException, IOException {
    boolean authenticated = req.authenticate(resp);
    if (authenticated) {
        String identificacao = StringUtils.defaultIfEmpty(req.getParameter("cpf_cnpj"), "");
        String data = StringUtils.defaultIfEmpty(req.getParameter("dt_emissao"), "");
        String numero = StringUtils.defaultIfEmpty(req.getParameter("num_nf"), "");
        File dir = new File(System.getProperty("nfe.dir"));
        if (identificacao.matches("\\d+") && numero.matches("\\d+")
                && data.matches("[0-9]{4}-[0-9]{2}-[0-9]{2}")) {
            File nfe = new File(new File(dir, identificacao), data + '_' + numero + ".xml");
            if (nfe.exists()) {
                resp.setContentType("text/xml");
                try (BufferedReader reader = new BufferedReader(new FileReader(nfe));
                        PrintWriter writer = resp.getWriter();) {
                    String line;
                    while ((line = reader.readLine()) != null) {
                        writer.write(line);
                        //                            writer.println();
                    }
                    writer.flush();
                }
                resp.setStatus(HttpServletResponse.SC_OK);
            }
        } else {
            String msg = String.format(
                    "Prezado cliente %s, no encontramos a nota nmero %s," + " na data %s.", identificacao,
                    numero, data);
            resp.sendError(HttpServletResponse.SC_NOT_FOUND, msg);
        }
    } else {
        resp.sendError(HttpServletResponse.SC_FORBIDDEN, "Voc no pode fazer download de notas fiscais!");
    }
}

From source file:xbdd.webapp.rest.BasicAuthFilter.java

@Override
public void doFilter(final ServletRequest request, final ServletResponse response,
        final FilterChain filterChain) throws IOException, ServletException {
    final HttpServletRequest httpRequest = (HttpServletRequest) request;
    final HttpServletResponse httpResponse = (HttpServletResponse) response;

    if (httpRequest.getUserPrincipal() == null) {
        final String basicAuth = httpRequest.getHeader(AUTHORIZATION_HEADER);

        if (basicAuth != null && StringUtils.startsWithIgnoreCase(basicAuth, BASIC_PREFIX)) {
            final String usernamePassword = new String(
                    Base64.decodeBase64(basicAuth.substring(BASIC_PREFIX.length()).trim()), "UTF-8");
            final String[] args = usernamePassword.split(BASIC_AUTH_SEPARATOR, 2);
            httpRequest.login(args[0], args[1]);
        } else {//from   w w w .j a v  a2s . c om
            httpRequest.authenticate(httpResponse);
            return;
        }
    }

    filterChain.doFilter(request, response);
}