authorizationfactory.java

来自「Jive是基于JSP/JAVA技术构架的一个大型BBS论坛系统,这是Jive论坛」· Java 代码 · 共 303 行

JAVA
303
字号
/** * $RCSfile: AuthorizationFactory.java,v $ * $Revision: 1.7 $ * $Date: 2002/03/21 14:38:17 $ * * Copyright (C) 1999-2001 CoolServlets, Inc. All rights reserved. * * This software is the proprietary information of CoolServlets, Inc. * Use is subject to license terms. */package com.jivesoftware.forum;import com.jivesoftware.util.*;import com.jivesoftware.forum.util.SkinUtils;import javax.servlet.http.*;/** * An abstract class that defines a framework for providing authentication * services in Jive. The static getAuthorization(String,String), * getAuthorization(HttpServletRequest, HttpServeltResponse), and * getAnonymousAuthorization() methods should be called directly from * applications using Jive in order to obtain Authorization tokens.<p> * * Users of Jive that wish to change the AuthorizationFactory implementation * used to generate tokens can set the <code>AuthorizationFactory.className</code> * Jive property. For example, if you have altered Jive to use LDAP for user * information, you'd want to write a custom implementation of * AuthorizationFactory to make LDAP authorization queries. After changing the * <code>AuthorizationFactory.className</code> Jive property, you must restart * your application server.<p> * * The getAuthorization method that takes servlet request and response objects * as arguments can be used to implement single sign-on. Additionally, two * helper methods are provided for securely encrypting and decrypting login * information so that it can be stored as a cookie value to implement auto- * login.<p> * * Note: "AuthorizationFactory" is a misnomer and "AuthenticationFactory" would * be a more appropriate name. This will be fixed in a forthcoming release. * * @author Matt Tucker */public abstract class AuthorizationFactory {    /**      * Name of the key in a user's session that Authorization tokens are      * customarily stored at.      */    public static final String SESSION_AUTHORIZATION = "jive.authorization";    /**     * Name of the cookie used to store user info for auto-login purposes.     */    public static final String COOKIE_AUTOLOGIN = "jive.authorization.autologin";    /**     * The default class to instantiate is database implementation.     */    private static String className =        "com.jivesoftware.forum.database.DbAuthorizationFactory";    private static AuthorizationFactory factory = null;    private static Blowfish cipher = null;    /**     * Initializes encryption and decryption ciphers using the secret key     * found in the Jive property "cookieKey". If a secret key has not been     * created yet, it is automatically generated and saved.     */    static {        // Get the cookie password, stored as a Jive property. Obviously,        // protecting your jive_config.xml file is critical for making cookie        // encryption secure.        String keyString = JiveGlobals.getJiveProperty("cookieKey");        if (keyString == null) {            keyString = StringUtils.randomString(15);            JiveGlobals.setJiveProperty("cookieKey", keyString);        }        cipher = new Blowfish(keyString);    }    /**     * Returns the Authorization token associated with the specified username     * and password. If the username and password do not match the record of     * any user in the system, the method throws an UnauthorizedException.<p>     *     * When using most implementations of this class, authorization tokens     * should be cached. A convenient place to store a token is often in the     * HttpSession.     *     * @param username the username to create an Authorization with.     * @param password the password to create an Authorization with.     * @return an Authorization token if the username and password are correct.     * @throws UnauthorizedException if the username and password do not match     *      any existing user.     */    public static Authorization getAuthorization(String username,            String password) throws UnauthorizedException    {        loadAuthorizationFactory();        return factory.createAuthorization(username, password);    }    /**     * Returns the Authorization token associated with the information in a     * servlet requesst and response object. This is useful for systems that     * store login information in a user's session or as a cookie, and can also     * be used to implement single sign-on in Jive. If no authentication     * information is found, the method throws an UnauthorizedException.     *     * @param request an HttpServletRequest object.     * @param request an HttpServletResponse object.     * @throws UnauthorizedException if no authorization information is found.     */    public static Authorization getAuthorization(HttpServletRequest request,            HttpServletResponse response) throws UnauthorizedException    {        loadAuthorizationFactory();        return factory.createAuthorization(request, response);    }    /**     * Returns an anonymous user Authorization.     *     * @return an anonymous Authorization token.     */    public static Authorization getAnonymousAuthorization() {        loadAuthorizationFactory();        return factory.createAnonymousAuthorization();    }    /**     * Utility method that builds an encrypted String containing a username and     * password, which is useful for storing as a cookie. This is a     * cryptographically secure algorithm that uses a 56-bit DES key. The     * standard cookie name used by Jive for this information is stored in     * <tt>AuthorizationFactory.COOKIE_AUTOLOGIN</tt>.     *     * @param username the username to encode.     * @param password the password to encode.     * @return an ecrypted String containing the input parameters.     */    public static String encryptAuthInfo(String username, String password)    {        if (username == null || password == null) {            throw new NullPointerException("Username or password was null.");        }        return cipher.encryptString(username + '\002' + password);    }    /**     * Utility method that decrypts a String built by the encryptAuthInfo method     * containing a username and password. This is a cryptographically secure     * algorithm that uses a 56-bit DES key. The standard cookie name used by     * Jive for this information is stored in     * <tt>AuthorizationFactory.COOKIE_AUTOLOGIN</tt>.     *     * @param value the encrypted String.     * @return String[] containing the username at index 0 and the password at     *      index 1, or <code>{ null, null }</code> if value equals     *      <tt>null</tt> or the empty string.     */    public static String [] decryptAuthInfo(String value) {        // Check that the cookie value isn't null or zero-length        if (value == null || value.length() <= 0 ) {            return null;        }        // Decode the cookie value        value = cipher.decryptString(value);        if (value == null) {            return null;        }        int	pos = value.indexOf('\002');        String username = (pos < 0) ? "" : value.substring(0, pos);        String password = (pos < 0) ? "" : value.substring(pos + 1);        return new String[] { username, password };    }    /**     * Creates Authorization tokens for users. This method must be implemented     * by concrete subclasses of AuthorizationFactory.     *     * @param username the username to create an Authorization with.     * @param password the password to create an Authorization with.     * @return an Authorization token if the username and password are correct.     * @throws UnauthorizedException if the username and password do not match     *      any existing user.     */    protected abstract Authorization createAuthorization(String username,            String password) throws UnauthorizedException;    /**     * Creates Authorization tokens based on information from servlet request     * and response objects. This method is <b>optionally</b> implemented by     * concrete subclasses of AuthorizationFactory.<p>     *     * If this method is not overwriten by a concrete subclass of     * AuthorizationFactory, then the following default behavior will be used     * to search for login information:</ul>     *     *  <li> Look for an Authorization object in the session using the session     *      name <tt>AuthorizationFactory.SESSION_AUTHORIZATION</tt>. Return it     *      if found.     *  <li> Look for encrypted login information at the cookie value named     *      <tt>AuthorizationFactory.COOKIE_AUTOLOGIN</tt>. Return an     *      Authorization object built using that info if found.     *  <li> Throw an UnauthorizedException if the previous two steps failed.     *     * @param request an HttpServletRequest object.     * @param request an HttpServletResponse object.     * @throws UnauthorizedException if no authorization information is found.     */    protected Authorization createAuthorization(HttpServletRequest request,            HttpServletResponse response) throws UnauthorizedException    {        HttpSession session = request.getSession();        // Check 1: look for the Jive authentication token in the user's session.        Authorization authToken = (Authorization)session.getAttribute(                SESSION_AUTHORIZATION);        if (authToken != null) {            return authToken;        }        // Check 2: see if a cookie storing the username and password is there.        Cookie cookie = SkinUtils.getCookie(request, COOKIE_AUTOLOGIN);        if (cookie != null) {            try {                // We found a cookie, so get the username and password from it,                // create an Authorization token, then store it in the session.                String [] authInfo = decryptAuthInfo(cookie.getValue());                if (authInfo != null) {                    String username = authInfo[0];                    String password = authInfo[1];                    // Try to validate the user based on the info from the cookie.                    authToken = getAuthorization(username, password);                    session.setAttribute(SESSION_AUTHORIZATION, authToken);                    return authToken;                }                else {                    // We must have found an old cookie format, so delete it.                    SkinUtils.deleteCookie(response, cookie);                }            }            catch (UnauthorizedException ue) {                // Remove the authorization cookie as the exception indicates                // the username and/or password are no longer valid                SkinUtils.deleteCookie(response, cookie);                throw ue;            }        }        throw new UnauthorizedException();    }    /**     * Creates anonymous Authorization tokens. This method must be implemented by     * concrete subclasses AuthorizationFactory.     *     * @return an anonymous Authorization token.     */    protected abstract Authorization createAnonymousAuthorization();    /**     * Loads a concrete AuthorizationFactory that can be used generate     * Authorization tokens for authorized users.<p>     *     * By default, the implementation used will be an instance of     * DbAuthorizationFactory -- the standard database implementation that uses     * the Jive user table. A different factory can be specified by setting the     * Jive property "AuthorizationFactory.className". However, you must     * restart Jive for any change to take effect.     */    private static void loadAuthorizationFactory() {        if (factory == null) {            //Use className as a convenient object to get a lock on.            synchronized(className) {                if (factory == null) {                    //See if the classname has been set as a Jive property.                    String classNameProp = JiveGlobals.getJiveProperty(                            "AuthorizationFactory.className");                    if (classNameProp != null) {                        className = classNameProp;                    }                    try {                        Class c = Class.forName(className);                        factory = (AuthorizationFactory)c.newInstance();                    }                    catch (Exception e) {                        System.err.println("Exception loading class: " + e);                        e.printStackTrace();                    }                }            }        }    }}

⌨️ 快捷键说明

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