⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 remoteverifyservlet.java

📁 一套JAVA的CA证书签发系统.
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
/************************************************************************* *                                                                       * *  EJBCA: The OpenSource Certificate Authority                          * *                                                                       * *  This software is free software; you can redistribute it and/or       * *  modify it under the terms of the GNU Lesser General Public           * *  License as published by the Free Software Foundation; either         * *  version 2.1 of the License, or any later version.                    * *                                                                       * *  See terms of license at gnu.org.                                     * *                                                                       * *************************************************************************/ package se.anatom.ejbca.samples;import java.io.*;import java.util.*;import javax.servlet.*;import javax.servlet.http.*;import org.apache.log4j.Logger;/** * Servlet to authenticate a user. Simple database using a file to keep users in format: * instance;username;password;DN DN is in form: dn-c:dn-o:dn-ou:dn-ln:dn-gn:dn-cn where parts can * be left out as desired. Expects these parameters when called: (error 500 if any missing) *  * <ul> * <li> * user=&lt;username&gt; * </li> * <li> * password=&lt;password&gt; * </li> * <li> * version=&lt;major&gt;.&lt;minor&gt; * </li> * </ul> *  * <p> * Returns a logic token stating that user is authenticated followed by the information to use for * this user's certificate. * </p> * * @author Original code by Peter Neemeth * @version $Id: RemoteVerifyServlet.java,v 1.7 2004/04/16 07:39:02 anatom Exp $ */public class RemoteVerifyServlet extends HttpServlet {    private static Logger log = Logger.getLogger(RemoteVerifyServlet.class);    /** Status code for successful communication */    public static final String MSG_OK = "200 OK";    /** Status code for failed communication */    public static final String MSG_PROTOCOL_MISMATCH = "400 Wrong protocol version";    /** Status code for generic error */    public static final String MSG_GENERIC_ERROR = "500 ERROR (Missing parameter?) : ";    /** Name of user id parameter */    public static final String REQUEST_USERNAME = "username";    /** Name of password parameter */    public static final String REQUEST_PASSWORD = "password";    /** Name of version parameter */    public static final String REQUEST_VERSION = "version";    /** Token for protocol */    public static final String RESPONSE_END = "end";    /** Token for protocol */    public static final String RESPONSE_STATUS = "status";    /** Token for protocol */    public static final String RESPONSE_RESULT = "result";    /** Token for protocol */    public static final String RESPONSE_MESSAGE = "message";    /** Status code for granting of certificate. */    public static final String GRANT = "grant";    /** Status code for rejecting certificate request. */    public static final String REJECT = "reject";    /** Version of the protocol used when communicating back to requestor */    protected static final int PROTOCOL_VERSION_MAJOR = 1;    /** Version of the protocol used when communicating back to requestor */    protected static final int PROTOCOL_VERSION_MINOR = 0;    /**     * Basic structure containing users. Top level keyed on instance gives new Hashtable keyed on     * username with String[] = { password, result } as data.     */    protected static Hashtable users;    /**     * Delimiter between parts in DN     *      * <p>     * Can be controlled via properties file.     * </p>     */    protected static final String DNPART_DELIMITER = ":";    /**     * Separator between name and value in DN name = value     *      * <p>     * Can be controlled via properties file.     * </p>     */    protected static final String DNPART_NAME_VALUE_SEPARATOR = "=";    /**     * For easy export from Excel and others.     *      * <p>     * Can be controlled via properties file.     * </p>     */    protected static final String RECORD_SEPARATOR = ";";    /**     * Ignored lines in DBUSER_file start with this character.     *      * <p>     * Can be controlled via properties file.     * </p>     */    protected static final String LINE_COMMENT = ";";    /** What parameter to send when using GET to show status. */    protected static final String STATUS_KEY = "status";    /** Count total accesses */    protected static int countAccess = 0;    /** Count granted accesses */    protected static int countGranted = 0;    /** Count rejected accesses */    protected static int countRejected = 0;    /**     * Updates result with name-value-pairs extracted from dnPartsString     *     * @param result where the result is stuffed     * @param dnPartsString name-value-pairs separated by delimiter     */    void addUserDataToResult(AuthResult result, final String dnPartsString) {        if (dnPartsString == null) {            return;        }        Enumeration dnParts = new StringTokenizer(dnPartsString, DNPART_DELIMITER);        while (dnParts.hasMoreElements()) {            String dnPart = (String) dnParts.nextElement();            int separatorPosition = dnPart.indexOf(DNPART_NAME_VALUE_SEPARATOR);            String dnName = dnPart.substring(0, separatorPosition);            String dnValue = dnPart.substring(separatorPosition + 1); // skip separator            result.add(dnName, dnValue);            debugLog("addUserDataToResult: result=" + result);        }    }    /**     * Authenticate a user given a querystring. <b>This is the only method a customer should have     * to rewrite/override.</b>     *     * @param username containing parsed username from requestor     * @param password containing parsed password from requestor     *     * @return status + certificate contents in an AuthResult     */    protected AuthResult authenticateUser(String username, String password) {        AuthResult result = new AuthResult();        String[] userData = findUserData(username);        if (userData == null) {            result.reject();            result.setReason("Failed to authenticate credentials.");            debugLog("authenticateUser: No such user. REJECTING");        } else {            debugLog("authenticateUser: Got userData for user '" + username + "'");            if (password.equals(userData[0])) {                debugLog("authenticateUser: Password matched. GRANTING");                result.grant();                addUserDataToResult(result, userData[1]);            } else {                debugLog("authenticateUser: Password missmatch. REJECTING");                result.reject();                result.setReason("Failed to authenticate credentials.");            }        }        return result;    }    /**     * Logs extensively to the log.     *     * @param s What to log     */    protected void debugLog(final String s) {        log.debug(s);    }    /**     * logs info.     *     * @param s What to log     */    protected void infoLog(final String s) {        log.info(s);    }    /**     * logs error     *     * @param s What to log     */    protected void errorLog(final String s) {        log.error(s);    }    /**     * logs error and stacktrace.     *     * @param s What to log     * @param e DOCUMENT ME!     */    protected void errorLog(final String s, java.lang.Exception e) {        log.error(s, e);    }    /**     * Allows for checking status of.     *     * @param req javax.servlet.http.HttpServletRequest     * @param res javax.servlet.http.HttpServletResponse     *     * @exception javax.servlet.ServletException The exception description.     */    protected void doGet(HttpServletRequest req, HttpServletResponse res)        throws ServletException, IOException {        res.setContentType("text/plain");        ServletOutputStream out = res.getOutputStream();        // Keep this for logging.        String remoteAddr = req.getRemoteAddr();        // Extract information about request type and how we were called.        // Also suitable for logging.        String method = req.getMethod();        String path = req.getServletPath();        out.print("You called from " + remoteAddr);        out.println(" using " + method + " as method.");        try {            Hashtable params = HttpUtils.parseQueryString(req.getQueryString());            if (params.containsKey(STATUS_KEY)) {                out.println("\n");                out.println((new Date()).toString() + " RemoteVerify status: ");                out.println("Accesses: " + countAccess);                out.println("Granted: " + countGranted);                out.println("Rejected: " + countRejected);                if (users != null) {                    out.println("Number of users in database: " + users.size());                } else {                    out.println("No users in database.");                }                out.println("\n");                out.println("Protocol version: " + PROTOCOL_VERSION_MAJOR + "." +                    PROTOCOL_VERSION_MINOR);                out.println("Database loaded from: " + getInitParameter("dbfilename"));                out.println((new Date()).toString() + " DONE.");            }        } catch (IllegalArgumentException ignored) {            out.println("Couldn't parse that request. Check parameters and try again.");        }        out.println("Request done.");    }    /**     * Accepts requests and dispatches to authenticateUser in this object.     *      * <p>     * Returns one of the following cases. (Apart from status being the first line, order is not     * specified.)     *      * <ul>     * <li>     * A granted reply:     * <pre>     *   status=200 OK

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -