Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  //
  //  ========================================================================
  //  Copyright (c) 1995-2012 Mort Bay Consulting Pty. Ltd.
  //  ------------------------------------------------------------------------
  //  All rights reserved. This program and the accompanying materials
  //  are made available under the terms of the Eclipse Public License v1.0
  //  and Apache License v2.0 which accompanies this distribution.
  //
  //      The Eclipse Public License is available at
 //      http://www.eclipse.org/legal/epl-v10.html
 //
 //      The Apache License v2.0 is available at
 //      http://www.opensource.org/licenses/apache2.0.php
 //
 //  You may elect to redistribute this code under either of these licenses.
 //  ========================================================================
 //
 
 package org.eclipse.jetty.security.authentication;
 
 
 

Version:
$Rev: 4793 $ $Date: 2009-03-19 00:00:01 +0100 (Thu, 19 Mar 2009) $ The nonce max age in ms can be set with the org.eclipse.jetty.security.SecurityHandler.setInitParameter(java.lang.String,java.lang.String) using the name "maxNonceAge"
 
 public class DigestAuthenticator extends LoginAuthenticator
 {
     private static final Logger LOG = Log.getLogger(DigestAuthenticator.class);
     SecureRandom _random = new SecureRandom();
     private long _maxNonceAgeMs = 60*1000;
     private ConcurrentMap<StringNonce_nonceCount = new ConcurrentHashMap<StringNonce>();
     private Queue<Nonce_nonceQueue = new ConcurrentLinkedQueue<Nonce>();
     private static class Nonce
     {
         final String _nonce;
         final long _ts;
         AtomicInteger _nc=new AtomicInteger();
         public Nonce(String noncelong ts)
         {
             =nonce;
             =ts;
         }
     }
 
     /* ------------------------------------------------------------ */
     public DigestAuthenticator()
     {
         super();
     }
 
     /* ------------------------------------------------------------ */
    
 
     @Override
     public void setConfiguration(AuthConfiguration configuration)
     {
         super.setConfiguration(configuration);
         
         String mna=configuration.getInitParameter("maxNonceAge");
         if (mna!=null)
         {
             synchronized (this)
             {
                 =Long.valueOf(mna);
             }
         }
    }
    
    /* ------------------------------------------------------------ */
    public synchronized void setMaxNonceAge(long maxNonceAgeInMillis)
    {
         = maxNonceAgeInMillis;
    }
    /* ------------------------------------------------------------ */
    public String getAuthMethod()
    {
        return .;
    }
    /* ------------------------------------------------------------ */
    public boolean secureResponse(ServletRequest reqServletResponse resboolean mandatoryUser validatedUserthrows ServerAuthException
    {
        return true;
    }
    
    /* ------------------------------------------------------------ */
    public Authentication validateRequest(ServletRequest reqServletResponse resboolean mandatorythrows ServerAuthException
    {
        if (!mandatory)
            return new DeferredAuthentication(this);
        HttpServletRequest request = (HttpServletRequest)req;
        HttpServletResponse response = (HttpServletResponse)res;
        String credentials = request.getHeader(.);
        try
        {
            boolean stale = false;
            if (credentials != null)
            {
                if (.isDebugEnabled()) 
                    .debug("Credentials: " + credentials);
                QuotedStringTokenizer tokenizer = new QuotedStringTokenizer(credentials"=, "truefalse);
                final Digest digest = new Digest(request.getMethod());
                String last = null;
                String name = null;
                while (tokenizer.hasMoreTokens())
                {
                    String tok = tokenizer.nextToken();
                    char c = (tok.length() == 1) ? tok.charAt(0) : '\0';
                    switch (c)
                    {
                        case '=':
                            name = last;
                            last = tok;
                            break;
                        case ',':
                            name = null;
                            break;
                        case ' ':
                            break;
                        default:
                            last = tok;
                            if (name != null)
                            {
                                if ("username".equalsIgnoreCase(name))
                                    digest.username = tok;
                                else if ("realm".equalsIgnoreCase(name))
                                    digest.realm = tok;
                                else if ("nonce".equalsIgnoreCase(name))
                                    digest.nonce = tok;
                                else if ("nc".equalsIgnoreCase(name))
                                    digest.nc = tok;
                                else if ("cnonce".equalsIgnoreCase(name))
                                    digest.cnonce = tok;
                                else if ("qop".equalsIgnoreCase(name))
                                    digest.qop = tok;
                                else if ("uri".equalsIgnoreCase(name))
                                    digest.uri = tok;
                                else if ("response".equalsIgnoreCase(name)) 
                                    digest.response = tok;
                                name=null;
                            }
                    }
                }
                int n = checkNonce(digest,(Request)request);
                if (n > 0)
                {
                    //UserIdentity user = _loginService.login(digest.username,digest);
                    UserIdentity user = login(digest.usernamedigestreq);
                    if (user!=null)
                    {
                        return new UserAuthentication(getAuthMethod(),user);
                    }
                }
                else if (n == 0) 
                    stale = true;
            }
            if (!DeferredAuthentication.isDeferred(response))
            {
                String domain = request.getContextPath();
                if (domain == null
                    domain = "/";
                response.setHeader(."Digest realm=\"" + .getName()
                        + "\", domain=\""
                        + domain
                        + "\", nonce=\""
                        + newNonce((Request)request)
                        + "\", algorithm=MD5, qop=\"auth\","
                        + " stale=" + stale);
                response.sendError(.);
                return .;
            }
            return .;
        }
        catch (IOException e)
        {
            throw new ServerAuthException(e);
        }
    }
    /* ------------------------------------------------------------ */
    public String newNonce(Request request)
    {
        Nonce nonce;
        
        do
        {
            byte[] nounce = new byte[24];
            .nextBytes(nounce);
            nonce = new Nonce(new String(B64Code.encode(nounce)),request.getTimeStamp());
        }
        while (.putIfAbsent(nonce._nonce,nonce)!=null);
        .add(nonce);
               
        return nonce._nonce;
    }

    

Parameters:
nstring nonce to check
request
Returns:
-1 for a bad nonce, 0 for a stale none, 1 for a good nonce
    /* ------------------------------------------------------------ */
    private int checkNonce(Digest digestRequest request)
    {
        // firstly let's expire old nonces
        long expired;
        synchronized (this)
        {
            expired = request.getTimeStamp()-;
        }
        
        Nonce nonce=.peek();
        while (nonce!=null && nonce._ts<expired)
        {
            .remove(nonce);
            .remove(nonce._nonce);
            nonce=.peek();
        }
        
       
        try
        {
            nonce = .get(digest.nonce);
            if (nonce==null)
                return 0;
            
            long count = Long.parseLong(digest.nc,16);
            if (count>.)
                return 0;
            int old=nonce._nc.get();
            while (!nonce._nc.compareAndSet(old,(int)count))
                old=nonce._nc.get();
            if (count<=old)
                return -1;
 
            return 1;
        }
        catch (Exception e)
        {
            .ignore(e);
        }
        return -1;
    }
    /* ------------------------------------------------------------ */
    /* ------------------------------------------------------------ */
    /* ------------------------------------------------------------ */
    private static class Digest extends Credential
    {
        private static final long serialVersionUID = -2484639019549527724L;
        final String method;
        String username = "";
        String realm = "";
        String nonce = "";
        String nc = "";
        String cnonce = "";
        String qop = "";
        String uri = "";
        String response = "";
        /* ------------------------------------------------------------ */
        Digest(String m)
        {
             = m;
        }
        /* ------------------------------------------------------------ */
        @Override
        public boolean check(Object credentials)
        {
            if (credentials instanceof char[])
                credentials=new String((char[])credentials);
            String password = (credentials instanceof String) ? (Stringcredentials : credentials.toString();
            try
            {
                MessageDigest md = MessageDigest.getInstance("MD5");
                byte[] ha1;
                if (credentials instanceof Credential.MD5)
                {
                    // Credentials are already a MD5 digest - assume it's in
                    // form user:realm:password (we have no way to know since
                    // it's a digest, alright?)
                    ha1 = ((Credential.MD5credentials).getDigest();
                }
                else
                {
                    // calc A1 digest
                    md.update(.getBytes(.));
                    md.update((byte':');
                    md.update(.getBytes(.));
                    md.update((byte':');
                    md.update(password.getBytes(.));
                    ha1 = md.digest();
                }
                // calc A2 digest
                md.reset();
                md.update(.getBytes(.));
                md.update((byte':');
                md.update(.getBytes(.));
                byte[] ha2 = md.digest();
                // calc digest
                // request-digest = <"> < KD ( H(A1), unq(nonce-value) ":"
                // nc-value ":" unq(cnonce-value) ":" unq(qop-value) ":" H(A2) )
                // <">
                // request-digest = <"> < KD ( H(A1), unq(nonce-value) ":" H(A2)
                // ) > <">
                md.update(TypeUtil.toString(ha1, 16).getBytes(.));
                md.update((byte':');
                md.update(.getBytes(.));
                md.update((byte':');
                md.update(.getBytes(.));
                md.update((byte':');
                md.update(.getBytes(.));
                md.update((byte':');
                md.update(.getBytes(.));
                md.update((byte':');
                md.update(TypeUtil.toString(ha2, 16).getBytes(.));
                byte[] digest = md.digest();
                // check digest
                return (TypeUtil.toString(digest, 16).equalsIgnoreCase());
            }
            catch (Exception e)
            {
                .warn(e);
            }
            return false;
        }
        public String toString()
        {
            return  + "," + ;
        }
    }
New to GrepCode? Check out our FAQ X