Download Install Tutorial Docs FAQ Tools WikiLicense Team IRC Planet Involvement Shop Book

root/tags/cherrypy-3.0.0/cherrypy/test/test_httpauth.py

Revision 1468 (checked in by lawouach, 2 years ago)

Fix for #615

  • Property svn:eol-style set to native
Line 
1 from cherrypy.test import test
2 test.prefer_parent_path()
3
4 import md5
5
6 import cherrypy
7 from cherrypy.lib import httpauth
8
9 def setup_server():
10     class Root:
11         def index(self):
12             return "This is public."
13         index.exposed = True
14
15     class DigestProtected:
16         def index(self):
17             return "This is protected by Digest auth."
18         index.exposed = True
19
20     class BasicProtected:
21         def index(self):
22             return "This is protected by Basic auth."
23         index.exposed = True
24
25     def fetch_users():
26         return {'test': 'test'}
27
28     conf = {'/digest': {'tools.digest_auth.on': True,
29                         'tools.digest_auth.realm': 'localhost',
30                         'tools.digest_auth.users': fetch_users},
31             '/basic': {'tools.basic_auth.on': True,
32                        'tools.basic_auth.realm': 'localhost',
33                        'tools.basic_auth.users': {'test': md5.new('test').hexdigest()}}}
34     root = Root()
35     root.digest = DigestProtected()
36     root.basic = BasicProtected()
37     cherrypy.tree.mount(root, config=conf)
38     cherrypy.config.update({'environment': 'test_suite'})
39
40 from cherrypy.test import helper
41
42 class HTTPAuthTest(helper.CPWebCase):
43
44     def testPublic(self):
45         self.getPage("/")
46         self.assertStatus('200 OK')
47         self.assertHeader('Content-Type', 'text/html')
48         self.assertBody('This is public.')
49
50     def testBasic(self):
51         self.getPage("/basic/")
52         self.assertStatus('401 Unauthorized')
53         self.assertHeader('WWW-Authenticate', 'Basic realm="localhost"')
54
55         self.getPage('/basic/', [('Authorization', 'Basic dGVzdDp0ZX60')])
56         self.assertStatus('401 Unauthorized')
57        
58         self.getPage('/basic/', [('Authorization', 'Basic dGVzdDp0ZXN0')])
59         self.assertStatus('200 OK')
60         self.assertBody('This is protected by Basic auth.')
61
62     def testDigest(self):
63         self.getPage("/digest/")
64         self.assertStatus('401 Unauthorized')
65        
66         value = None
67         for k, v in self.headers:
68             if k.lower() == "www-authenticate":
69                 if v.startswith("Digest"):
70                     value = v
71                     break
72
73         if value is None:
74             self._handlewebError("Digest authentification scheme was not found")
75
76         value = value[7:]
77         items = value.split(', ')
78         tokens = {}
79         for item in items:
80             key, value = item.split('=')
81             tokens[key.lower()] = value
82            
83         missing_msg = "%s is missing"
84         bad_value_msg = "'%s' was expecting '%s' but found '%s'"
85         nonce = None
86         if 'realm' not in tokens:
87             self._handlewebError(missing_msg % 'realm')
88         elif tokens['realm'] != '"localhost"':
89             self._handlewebError(bad_value_msg % ('realm', '"localhost"', tokens['realm']))
90         if 'nonce' not in tokens:
91             self._handlewebError(missing_msg % 'nonce')
92         else:
93             nonce = tokens['nonce'].strip('"')
94         if 'algorithm' not in tokens:
95             self._handlewebError(missing_msg % 'algorithm')
96         elif tokens['algorithm'] != '"MD5"':
97             self._handlewebError(bad_value_msg % ('algorithm', '"MD5"', tokens['algorithm']))
98         if 'qop' not in tokens:
99             self._handlewebError(missing_msg % 'qop')
100         elif tokens['qop'] != '"auth"':
101             self._handlewebError(bad_value_msg % ('qop', '"auth"', tokens['qop']))
102
103             # now let's see if what
104         base_auth = 'Digest username="test", realm="localhost", nonce="%s", uri="/digest/", algorithm=MD5, response="%s", qop=auth, nc=%s, cnonce="1522e61005789929"'
105
106         auth = base_auth % (nonce, '', '00000001')
107                
108         params = httpauth.parseAuthorization(auth)
109         response = httpauth._computeDigestResponse(params, 'test')
110        
111         auth = base_auth % (nonce, response, '00000001')
112         self.getPage('/digest/', [('Authorization', auth)])
113         self.assertStatus('200 OK')
114         self.assertBody('This is protected by Digest auth.')
115            
116 if __name__ == "__main__":
117     setup_server()
118     helper.testmain()
Note: See TracBrowser for help on using the browser.

Hosted by WebFaction

Log in as guest/cpguest to create tickets