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

📄 digestauthfilter.java

📁 很棒的web服务器源代码
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
    protected synchronized boolean checkRealm() {	acquireRealm() ;	return true;// (ipmatcher != null) ;    }    /**     * Get the list of allowed users.     */    public String[] getAllowedUsers() {	return (String[]) getValue(ATTR_ALLOWED_USERS, null) ;    }    /**     * Get the list of allowed groups.     */    public String[] getAllowedGroups() {	return (String[]) getValue(ATTR_ALLOWED_GROUPS, null) ;    }    /**     * Get the algorithm used     */    public String getAlgorithm() {	return (String) getValue(ATTR_ALGORITHM, "MD5") ;    }    /**     * Lookup a user by its name.     * @param name The user's name.     * @return An AuthUser instance, or <strong>null</strong>.     */    public synchronized ResourceReference lookupUser (String name) {	if ( rr_realm == null )	    acquireRealm() ;	try {	    AuthRealm realm = (AuthRealm) rr_realm.lock();	    return realm.loadUser(name) ;	} catch (InvalidResourceException ex) {	    return null;	} finally {	    rr_realm.unlock();	}    }    /*     * Is this user allowed in the realm ?     * First check in the list of allowed users (if any), than in the list     * of allowed groups (if any). If no allowed users or allowed groups     * are defined, than simply check for the existence of this user.     * @return A boolean <strong>true</strong> if access allowed.     */    protected boolean checkUser(AuthUser user) {	String allowed_users[] = getAllowedUsers() ;	// Check in the list of allowed users:	if ( allowed_users != null ) {	    for (int i = 0 ; i < allowed_users.length ; i++) {		if (allowed_users[i].equals(user.getName()))		    return true ;	    }	}	// Check in the list of allowed groups:	String allowed_groups[] = getAllowedGroups() ;	if ( allowed_groups != null ) {	    String ugroups[] = user.getGroups() ;	    if ( ugroups != null ) {		for (int i = 0 ; i < ugroups.length ; i++) {		    for (int j = 0 ; j < allowed_groups.length ; j++) {			if ( allowed_groups[j].equals(ugroups[i]) ) 			    return true ;		    }		}	    }	}	// If no users or groups specified, return true	if ((allowed_users == null) && (allowed_groups == null)) 	    return true ;	return false ;    }    /**     * Catch set value on the realm, to maintain cached values.     */    public void setValue(int idx, Object value) {	super.setValue(idx, value);	if ( idx == ATTR_REALM ) {	    // Initialize the filter challenge:	    challenge = HttpFactory.makeChallenge("Digest");	    challenge.setAuthParameter("realm", getRealm());	}	if ( idx == ATTR_NONCE_TTL ) {	    if ( value instanceof Integer)		nonce_ttl = ((Integer) value).intValue();	}    }    /**     * Authenticate the given request.     * We first check for valid authentication information. If no      * authentication is provided, than we try to map the IP address to some     * of the ones we know about. If the IP address is not found, we challenge     * the client for a password.     * <p>If the IP address is found, than either our user entry requires an     * extra password step (in wich case we challenge it), or simple IP     * based authentication is enough, so we allow the request.     * @param request The request to be authentified.     * @exception org.w3c.tools.resources.ProtocolException if authentication     * failed     */    public void authenticate (Request request) 	throws ProtocolException     {	// Are we being edited ?	if ( ! checkRealm() )	    return ;	// Internal requests always allowed:	Client client = request.getClient() ;	if ( client == null )	    return ;	// check for nonce validity	Date d = new Date();	if ((d.getTime() - prev_date) / 1000 > nonce_ttl) {	    prev_date = d.getTime();	    updateNonce();	}	DigestAuthContext dac = null;	// Check authentication according to auth method:	if ((request.hasAuthorization() && ! request.isProxy())	    || (request.isProxy() && request.hasProxyAuthorization())) {	    try {		dac = new DigestAuthContext(request);	    } catch (DigestAuthFilterException ex) {		dac = null;	    }	    if (dac != null) {		ResourceReference rr_user = 		    (ResourceReference)lookupUser(dac.dac_user) ;		try {		    AuthUser user = (AuthUser) rr_user.lock();		    // This user doesn't even exists !		    if ( user != null ) {			// If it has a password check it			if (user.definesAttribute("password") ) {			    if (dac.authenticate(user.getName(), 						 loaded_realm, 						 user.getPassword())) {				request.setState(STATE_AUTHUSER, dac.dac_user);				request.setState(STATE_AUTHTYPE, "Digest");				request.setState(STATE_AUTHCONTEXT, dac);				return;			    }			}		    }		} catch (InvalidResourceException ex) {		} finally {		    rr_user.unlock();		}	    }	}				// Every possible scheme has failed for this request, emit an error	Reply e = null;	HttpChallenge new_c;	if (dac != null && dac.stale) {	    new_c = challenge.getClone();	    if (new_c != null)		new_c.setAuthParameter("stale","true", false);	    else		new_c = challenge;	} else	    new_c = challenge;	if ( request.isProxy() ) {	    e = request.makeReply(HTTP.PROXY_AUTH_REQUIRED);	    e.setProxyAuthenticate(new_c);	} else {	    e = request.makeReply(HTTP.UNAUTHORIZED);	    e.setWWWAuthenticate (new_c);	}	HtmlGenerator g = new HtmlGenerator("Unauthorized");	g.append ("<h1>Unauthorized access</h1>"		  + "<p>You are denied access to this resource.");	e.setStream(g);	throw new HTTPException (e);    }    /**     * update the nonce string     */    private void updateNonce() {	updateNonce(getResource());    }    private synchronized void updateNonce(FramedResource fr) {	HTTPFrame htf;	if (fr instanceof HTTPFrame) {	    htf = (HTTPFrame) fr;	    try {		MessageDigest md = MessageDigest.getInstance(getAlgorithm());		md.update((new Date()).toString().getBytes());		try {		    md.update(htf.getETag().getTag().getBytes());		} catch (Exception ex) {		    // hum... try without it		    md.update(htf.getURLPath().getBytes());		}		byte b[] = md.digest();		if (nonce != null) 		    old_nonce = nonce;		nonce = StringUtils.toHexString(b);		challenge.setAuthParameter("nonce", nonce);	    } catch (NoSuchAlgorithmException algex) {		// bad algorithm, prevent access by firing an error/*		Reply error = request.makeReply(HTTP.INTERNAL_SERVER_ERROR) ;		error.setContent("The algorithm specified in the "+				 "DigestAuthFilterprocess filter "+				 "is not available, you are then unable to "+				 "access protected space");		throw new HTTPException(error);*/	    }	}    }    /**     * Add the appropriate cache control directives on the way back.     * @param request The request that has been processed.     * @param reply The original reply.     * @return Always <strong>null</strong>.     */    public ReplyInterface outgoingFilter(RequestInterface request,					 ReplyInterface reply)     {	Request req = (Request) request;	Reply rep = (Reply) reply;	if ( getPrivateCachability() ) {	    rep.setMustRevalidate(true);	} else if ( getSharedCachability() ) {	    rep.setProxyRevalidate(true);	} else if ( getPublicCachability() ) {	    rep.setPublic(true);	}	if (req.hasState(AuthFilter.STATE_AUTHCONTEXT)) {	    DigestAuthContext dac;	    dac =(DigestAuthContext)req.getState(AuthFilter.STATE_AUTHCONTEXT);	    if (dac.stale) {		rep.addAuthenticationInfo("nextnonce", nonce);	    }	}	return null;    }    /**     * Initialize the filter.     */    public void initialize(Object values[]) {	super.initialize(values) ;	if ( getRealm() != null ) {	    // Initialize the filter challenge:	    challenge = HttpFactory.makeChallenge("Digest");	    challenge.setAuthParameter("realm", getRealm());	    updateNonce();	    challenge.setAuthParameter("domain", getURLPath());	    challenge.setAuthParameter("algorithm", getAlgorithm(), false);	}    }}

⌨️ 快捷键说明

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