View Javadoc

1   package com.bradmcevoy.http.http11.auth;
2   
3   import com.bradmcevoy.http.Auth;
4   import com.bradmcevoy.http.AuthenticationHandler;
5   import com.bradmcevoy.http.DigestResource;
6   import com.bradmcevoy.http.Request;
7   import com.bradmcevoy.http.Resource;
8   import org.slf4j.Logger;
9   import org.slf4j.LoggerFactory;
10  
11  /**
12   *
13   * @author brad
14   */
15  public class DigestAuthenticationHandler implements AuthenticationHandler {
16  
17      private static final Logger log = LoggerFactory.getLogger( DigestAuthenticationHandler.class );
18      private final NonceProvider nonceProvider;
19      private final DigestHelper digestHelper;
20  
21  
22      public DigestAuthenticationHandler( NonceProvider nonceProvider ) {
23          this.nonceProvider = nonceProvider;
24          this.digestHelper = new DigestHelper(nonceProvider);
25      }
26  
27      public DigestAuthenticationHandler() {
28          this.nonceProvider = new SimpleMemoryNonceProvider( 60*60*24 ); // one day
29          this.digestHelper = new DigestHelper(nonceProvider);
30      }
31  
32      public boolean supports( Resource r, Request request ) {
33          Auth auth = request.getAuthorization();
34          if( auth == null ) {
35              return false;
36          }
37          boolean b;
38          if( r instanceof DigestResource ) {
39              DigestResource dr = (DigestResource) r;
40              if( dr.isDigestAllowed()) {
41                  b = Auth.Scheme.DIGEST.equals( auth.getScheme() );
42              } else {
43                  log.trace("digest auth is not allowed");
44                  b = false;
45              }
46          } else {
47              log.trace( "resource is not an instanceof DigestResource" );
48              b = false;
49          }
50          return b;
51      }
52  
53      public Object authenticate( Resource r, Request request ) {
54          DigestResource digestResource = (DigestResource) r;
55          Auth auth = request.getAuthorization();
56          DigestResponse resp = digestHelper.calculateResponse(auth, r.getRealm(), request.getMethod());
57          if( resp == null ) {
58              log.debug("requested digest authentication is invalid or incorrectly formatted");
59              return null;
60          } else {
61              Object o = digestResource.authenticate( resp );
62              return o;
63          }
64      }
65  
66      public String getChallenge( Resource resource, Request request ) {
67  
68          String nonceValue = nonceProvider.createNonce( resource, request );
69          return digestHelper.getChallenge(nonceValue, request.getAuthorization(), resource.getRealm());
70      }
71  
72      public boolean isCompatible( Resource resource ) {
73          return ( resource instanceof DigestResource );
74      }
75  }
76