test_httpauth.py :  » Web-Server » CherryPy » CherryPy-3.1.2 » cherrypy » test » Python Open Source

Home
Python Open Source
1.3.1.2 Python
2.Ajax
3.Aspect Oriented
4.Blog
5.Build
6.Business Application
7.Chart Report
8.Content Management Systems
9.Cryptographic
10.Database
11.Development
12.Editor
13.Email
14.ERP
15.Game 2D 3D
16.GIS
17.GUI
18.IDE
19.Installer
20.IRC
21.Issue Tracker
22.Language Interface
23.Log
24.Math
25.Media Sound Audio
26.Mobile
27.Network
28.Parser
29.PDF
30.Project Management
31.RSS
32.Search
33.Security
34.Template Engines
35.Test
36.UML
37.USB Serial
38.Web Frameworks
39.Web Server
40.Web Services
41.Web Unit
42.Wiki
43.Windows
44.XML
Python Open Source » Web Server » CherryPy 
CherryPy » CherryPy 3.1.2 » cherrypy » test » test_httpauth.py
from cherrypy.test import test
test.prefer_parent_path()

import md5, sha

import cherrypy
from cherrypy.lib import httpauth

def setup_server():
    class Root:
        def index(self):
            return "This is public."
        index.exposed = True

    class DigestProtected:
        def index(self):
            return "Hello %s, you've been authorized." % cherrypy.request.login
        index.exposed = True

    class BasicProtected:
        def index(self):
            return "Hello %s, you've been authorized." % cherrypy.request.login
        index.exposed = True

    class BasicProtected2:
        def index(self):
            return "Hello %s, you've been authorized." % cherrypy.request.login
        index.exposed = True

    def fetch_users():
        return {'test': 'test'}

    def sha_password_encrypter(password):
        return sha.new(password).hexdigest()
    
    def fetch_password(username):
        return sha.new('test').hexdigest()

    conf = {'/digest': {'tools.digest_auth.on': True,
                        'tools.digest_auth.realm': 'localhost',
                        'tools.digest_auth.users': fetch_users},
            '/basic': {'tools.basic_auth.on': True,
                       'tools.basic_auth.realm': 'localhost',
                       'tools.basic_auth.users': {'test': md5.new('test').hexdigest()}},
            '/basic2': {'tools.basic_auth.on': True,
                        'tools.basic_auth.realm': 'localhost',
                        'tools.basic_auth.users': fetch_password,
                        'tools.basic_auth.encrypt': sha_password_encrypter}}
            
    root = Root()
    root.digest = DigestProtected()
    root.basic = BasicProtected()
    root.basic2 = BasicProtected2()
    cherrypy.tree.mount(root, config=conf)
    cherrypy.config.update({'environment': 'test_suite'})

from cherrypy.test import helper

class HTTPAuthTest(helper.CPWebCase):

    def testPublic(self):
        self.getPage("/")
        self.assertStatus('200 OK')
        self.assertHeader('Content-Type', 'text/html')
        self.assertBody('This is public.')

    def testBasic(self):
        self.getPage("/basic/")
        self.assertStatus(401)
        self.assertHeader('WWW-Authenticate', 'Basic realm="localhost"')

        self.getPage('/basic/', [('Authorization', 'Basic dGVzdDp0ZX60')])
        self.assertStatus(401)
        
        self.getPage('/basic/', [('Authorization', 'Basic dGVzdDp0ZXN0')])
        self.assertStatus('200 OK')
        self.assertBody("Hello test, you've been authorized.")

    def testBasic2(self):
        self.getPage("/basic2/")
        self.assertStatus(401)
        self.assertHeader('WWW-Authenticate', 'Basic realm="localhost"')

        self.getPage('/basic2/', [('Authorization', 'Basic dGVzdDp0ZX60')])
        self.assertStatus(401)
        
        self.getPage('/basic2/', [('Authorization', 'Basic dGVzdDp0ZXN0')])
        self.assertStatus('200 OK')
        self.assertBody("Hello test, you've been authorized.")

    def testDigest(self):
        self.getPage("/digest/")
        self.assertStatus(401)
        
        value = None
        for k, v in self.headers:
            if k.lower() == "www-authenticate":
                if v.startswith("Digest"):
                    value = v
                    break

        if value is None:
            self._handlewebError("Digest authentification scheme was not found")

        value = value[7:]
        items = value.split(', ')
        tokens = {}
        for item in items:
            key, value = item.split('=')
            tokens[key.lower()] = value
            
        missing_msg = "%s is missing"
        bad_value_msg = "'%s' was expecting '%s' but found '%s'"
        nonce = None
        if 'realm' not in tokens:
            self._handlewebError(missing_msg % 'realm')
        elif tokens['realm'] != '"localhost"':
            self._handlewebError(bad_value_msg % ('realm', '"localhost"', tokens['realm']))
        if 'nonce' not in tokens:
            self._handlewebError(missing_msg % 'nonce')
        else:
            nonce = tokens['nonce'].strip('"')
        if 'algorithm' not in tokens:
            self._handlewebError(missing_msg % 'algorithm')
        elif tokens['algorithm'] != '"MD5"':
            self._handlewebError(bad_value_msg % ('algorithm', '"MD5"', tokens['algorithm']))
        if 'qop' not in tokens:
            self._handlewebError(missing_msg % 'qop')
        elif tokens['qop'] != '"auth"':
            self._handlewebError(bad_value_msg % ('qop', '"auth"', tokens['qop']))

        # Test a wrong 'realm' value
        base_auth = 'Digest username="test", realm="wrong realm", nonce="%s", uri="/digest/", algorithm=MD5, response="%s", qop=auth, nc=%s, cnonce="1522e61005789929"'

        auth = base_auth % (nonce, '', '00000001')
        params = httpauth.parseAuthorization(auth)
        response = httpauth._computeDigestResponse(params, 'test')
        
        auth = base_auth % (nonce, response, '00000001')
        self.getPage('/digest/', [('Authorization', auth)])
        self.assertStatus(401)

        # Test that must pass
        base_auth = 'Digest username="test", realm="localhost", nonce="%s", uri="/digest/", algorithm=MD5, response="%s", qop=auth, nc=%s, cnonce="1522e61005789929"'

        auth = base_auth % (nonce, '', '00000001')
        params = httpauth.parseAuthorization(auth)
        response = httpauth._computeDigestResponse(params, 'test')
        
        auth = base_auth % (nonce, response, '00000001')
        self.getPage('/digest/', [('Authorization', auth)])
        self.assertStatus('200 OK')
        self.assertBody("Hello test, you've been authorized.")
            
if __name__ == "__main__":
    setup_server()
    helper.testmain()
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.