summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--CHANGES.rst6
-rw-r--r--cherrypy/lib/auth_basic.py53
-rw-r--r--cherrypy/lib/auth_digest.py98
-rw-r--r--cherrypy/test/test_auth_basic.py44
-rw-r--r--cherrypy/test/test_auth_digest.py131
-rw-r--r--cherrypy/test/test_httpauth.py195
-rw-r--r--docs/basics.rst6
7 files changed, 226 insertions, 307 deletions
diff --git a/CHANGES.rst b/CHANGES.rst
index 2ab90a96..ccbcccaa 100644
--- a/CHANGES.rst
+++ b/CHANGES.rst
@@ -1,3 +1,9 @@
+v14.2.0
+------------
+
+* :issue:`1680` via :pr:`1683`: HTTP Basic Auth supports :rfc:`7617` UTF-8
+ charset decoding where possible. Uses latin1 as a fallback.
+
v14.1.0
-------
diff --git a/cherrypy/lib/auth_basic.py b/cherrypy/lib/auth_basic.py
index 44eb9b14..59e95f3c 100644
--- a/cherrypy/lib/auth_basic.py
+++ b/cherrypy/lib/auth_basic.py
@@ -1,14 +1,9 @@
# This file is part of CherryPy <http://www.cherrypy.org/>
# -*- coding: utf-8 -*-
# vim:ts=4:sw=4:expandtab:fileencoding=utf-8
+"""HTTP Basic Authentication tool.
-import binascii
-
-import cherrypy
-from cherrypy._cpcompat import base64_decode
-
-
-__doc__ = """This module provides a CherryPy 3.x tool which implements
+This module provides a CherryPy 3.x tool which implements
the server-side of HTTP Basic Access Authentication, as described in
:rfc:`2617`.
@@ -20,11 +15,19 @@ as the credentials store::
basic_auth = {'tools.auth_basic.on': True,
'tools.auth_basic.realm': 'earth',
'tools.auth_basic.checkpassword': checkpassword,
+ 'tools.auth_basic.accept_charset': 'UTF-8',
}
app_config = { '/' : basic_auth }
"""
+import binascii
+import unicodedata
+
+import cherrypy
+from cherrypy._cpcompat import base64_decode, ntob, ntou, tonative
+
+
__author__ = 'visteya'
__date__ = 'April 2009'
@@ -44,9 +47,10 @@ def checkpassword_dict(user_password_dict):
return checkpassword
-def basic_auth(realm, checkpassword, debug=False):
+def basic_auth(realm, checkpassword, debug=False, accept_charset='utf-8'):
"""A CherryPy tool which hooks at before_handler to perform
- HTTP Basic Access Authentication, as specified in :rfc:`2617`.
+ HTTP Basic Access Authentication, as specified in :rfc:`2617`
+ and :rfc:`7617`.
If the request has an 'authorization' header with a 'Basic' scheme, this
tool attempts to authenticate the credentials supplied in that header. If
@@ -66,6 +70,8 @@ def basic_auth(realm, checkpassword, debug=False):
"""
+ fallback_charset = 'ISO-8859-1'
+
if '"' in realm:
raise ValueError('Realm cannot contain the " (quote) character.')
request = cherrypy.serving.request
@@ -77,15 +83,38 @@ def basic_auth(realm, checkpassword, debug=False):
with cherrypy.HTTPError.handle((ValueError, binascii.Error), 400, msg):
scheme, params = auth_header.split(' ', 1)
if scheme.lower() == 'basic':
- username, password = base64_decode(params).split(':', 1)
+ decoded_params = base64_decode(params)
+ decoded_params = ntob(decoded_params)
+
+ last_err = None
+ for charset in (accept_charset, fallback_charset):
+ try:
+ decoded_params = tonative(decoded_params, charset)
+ break
+ except ValueError as ve:
+ last_err = ve
+ else:
+ raise last_err
+
+ decoded_params = ntou(decoded_params)
+ decoded_params = unicodedata.normalize('NFC', decoded_params)
+ decoded_params = tonative(decoded_params)
+ username, password = decoded_params.split(':', 1)
if checkpassword(realm, username, password):
if debug:
cherrypy.log('Auth succeeded', 'TOOLS.AUTH_BASIC')
request.login = username
return # successful authentication
+ charset = accept_charset.upper()
+ charset_declaration = (
+ (', charset="%s"' % charset)
+ if charset != fallback_charset
+ else ''
+ )
# Respond with 401 status and a WWW-Authenticate header
- cherrypy.serving.response.headers[
- 'www-authenticate'] = 'Basic realm="%s"' % realm
+ cherrypy.serving.response.headers['www-authenticate'] = (
+ 'Basic realm="%s"%s' % (realm, charset_declaration)
+ )
raise cherrypy.HTTPError(
401, 'You are not authorized to access that resource')
diff --git a/cherrypy/lib/auth_digest.py b/cherrypy/lib/auth_digest.py
index b604bf6d..92265c5a 100644
--- a/cherrypy/lib/auth_digest.py
+++ b/cherrypy/lib/auth_digest.py
@@ -1,17 +1,9 @@
# This file is part of CherryPy <http://www.cherrypy.org/>
# -*- coding: utf-8 -*-
# vim:ts=4:sw=4:expandtab:fileencoding=utf-8
+"""HTTP Digest Authentication tool.
-import time
-from hashlib import md5
-
-from six.moves.urllib.request import parse_http_list, parse_keqv_list
-
-import cherrypy
-from cherrypy._cpcompat import ntob
-
-
-__doc__ = """An implementation of the server-side of HTTP Digest Access
+An implementation of the server-side of HTTP Digest Access
Authentication, which is described in :rfc:`2617`.
Example usage, using the built-in get_ha1_dict_plain function which uses a dict
@@ -23,16 +15,27 @@ of plaintext passwords as the credentials store::
'tools.auth_digest.realm': 'wonderland',
'tools.auth_digest.get_ha1': get_ha1,
'tools.auth_digest.key': 'a565c27146791cfb',
+ 'tools.auth_digest.accept_charset': 'UTF-8',
}
app_config = { '/' : digest_auth }
"""
+import time
+from hashlib import md5
+
+from six.moves.urllib.parse import unquote_to_bytes
+from six.moves.urllib.request import parse_http_list, parse_keqv_list
+
+import cherrypy
+from cherrypy._cpcompat import ntob, tonative
+
+
__author__ = 'visteya'
__date__ = 'April 2009'
def md5_hex(s):
- return md5(ntob(s)).hexdigest()
+ return md5(ntob(s, 'utf-8')).hexdigest()
qop_auth = 'auth'
@@ -41,6 +44,9 @@ valid_qops = (qop_auth, qop_auth_int)
valid_algorithms = ('MD5', 'MD5-sess')
+FALLBACK_CHARSET = 'ISO-8859-1'
+DEFAULT_CHARSET = 'UTF-8'
+
def TRACE(msg):
cherrypy.log(msg, context='TOOLS.AUTH_DIGEST')
@@ -135,6 +141,21 @@ def H(s):
return md5_hex(s)
+def _try_decode_map_values(param_map, charset):
+ global FALLBACK_CHARSET
+
+ for enc in (charset, FALLBACK_CHARSET):
+ try:
+ return {
+ k: tonative(v, enc)
+ for k, v in param_map.items()
+ }
+ except ValueError as ve:
+ last_err = ve
+ else:
+ raise last_err
+
+
class HttpDigestAuthorization (object):
"""Class to parse a Digest Authorization header and perform re-calculation
@@ -144,7 +165,10 @@ class HttpDigestAuthorization (object):
def errmsg(self, s):
return 'Digest Authorization header: %s' % s
- def __init__(self, auth_header, http_method, debug=False):
+ def __init__(
+ self, auth_header, http_method,
+ debug=False, accept_charset=DEFAULT_CHARSET[:],
+ ):
self.http_method = http_method
self.debug = debug
scheme, params = auth_header.split(' ', 1)
@@ -157,6 +181,11 @@ class HttpDigestAuthorization (object):
# make a dict of the params
items = parse_http_list(params)
paramsd = parse_keqv_list(items)
+ paramsd = {
+ k: unquote_to_bytes(v)
+ for k, v in paramsd.items()
+ }
+ paramsd = _try_decode_map_values(paramsd, accept_charset)
self.realm = paramsd.get('realm')
self.username = paramsd.get('username')
@@ -307,24 +336,43 @@ class HttpDigestAuthorization (object):
return digest
-def www_authenticate(realm, key, algorithm='MD5', nonce=None, qop=qop_auth,
- stale=False):
+def _get_charset_declaration(charset):
+ global FALLBACK_CHARSET
+ charset = charset.upper()
+ return (
+ (', charset="%s"' % charset)
+ if charset != FALLBACK_CHARSET
+ else ''
+ )
+
+
+def www_authenticate(
+ realm, key, algorithm='MD5', nonce=None, qop=qop_auth,
+ stale=False, accept_charset=DEFAULT_CHARSET[:],
+):
"""Constructs a WWW-Authenticate header for Digest authentication."""
if qop not in valid_qops:
raise ValueError("Unsupported value for qop: '%s'" % qop)
if algorithm not in valid_algorithms:
raise ValueError("Unsupported value for algorithm: '%s'" % algorithm)
+ HEADER_PATTERN = (
+ 'Digest realm="%s", nonce="%s", algorithm="%s", qop="%s"%s%s'
+ )
+
if nonce is None:
nonce = synthesize_nonce(realm, key)
- s = 'Digest realm="%s", nonce="%s", algorithm="%s", qop="%s"' % (
- realm, nonce, algorithm, qop)
- if stale:
- s += ', stale="true"'
- return s
+
+ stale_param = ', stale="true"' if stale else ''
+
+ charset_declaration = _get_charset_declaration(accept_charset)
+
+ return HEADER_PATTERN % (
+ realm, nonce, algorithm, qop, stale_param, charset_declaration,
+ )
-def digest_auth(realm, get_ha1, key, debug=False):
+def digest_auth(realm, get_ha1, key, debug=False, accept_charset='utf-8'):
"""A CherryPy tool which hooks at before_handler to perform
HTTP Digest Access Authentication, as specified in :rfc:`2617`.
@@ -359,7 +407,9 @@ def digest_auth(realm, get_ha1, key, debug=False):
msg = 'The Authorization header could not be parsed.'
with cherrypy.HTTPError.handle(ValueError, 400, msg):
auth = HttpDigestAuthorization(
- auth_header, request.method, debug=debug)
+ auth_header, request.method,
+ debug=debug, accept_charset=accept_charset,
+ )
if debug:
TRACE(str(auth))
@@ -386,7 +436,11 @@ def digest_auth(realm, get_ha1, key, debug=False):
return
# Respond with 401 status and a WWW-Authenticate header
- header = www_authenticate(realm, key, stale=nonce_is_stale)
+ header = www_authenticate(
+ realm, key,
+ stale=nonce_is_stale,
+ accept_charset=accept_charset,
+ )
if debug:
TRACE(header)
cherrypy.serving.response.headers['WWW-Authenticate'] = header
diff --git a/cherrypy/test/test_auth_basic.py b/cherrypy/test/test_auth_basic.py
index cb3b344f..d7e69a9b 100644
--- a/cherrypy/test/test_auth_basic.py
+++ b/cherrypy/test/test_auth_basic.py
@@ -34,13 +34,25 @@ class BasicAuthTest(helper.CPWebCase):
return "Hello %s, you've been authorized." % (
cherrypy.request.login)
+ class BasicProtected2_u:
+
+ @cherrypy.expose
+ def index(self):
+ return "Hello %s, you've been authorized." % (
+ cherrypy.request.login)
+
userpassdict = {'xuser': 'xpassword'}
userhashdict = {'xuser': md5(b'xpassword').hexdigest()}
+ userhashdict_u = {'xюзер': md5(ntob('їжа', 'utf-8')).hexdigest()}
def checkpasshash(realm, user, password):
p = userhashdict.get(user)
return p and p == md5(ntob(password)).hexdigest() or False
+ def checkpasshash_u(realm, user, password):
+ p = userhashdict_u.get(user)
+ return p and p == md5(ntob(password, 'utf-8')).hexdigest() or False
+
basic_checkpassword_dict = auth_basic.checkpassword_dict(userpassdict)
conf = {
'/basic': {
@@ -51,13 +63,21 @@ class BasicAuthTest(helper.CPWebCase):
'/basic2': {
'tools.auth_basic.on': True,
'tools.auth_basic.realm': 'wonderland',
- 'tools.auth_basic.checkpassword': checkpasshash
+ 'tools.auth_basic.checkpassword': checkpasshash,
+ 'tools.auth_basic.accept_charset': 'ISO-8859-1',
+ },
+ '/basic2_u': {
+ 'tools.auth_basic.on': True,
+ 'tools.auth_basic.realm': 'wonderland',
+ 'tools.auth_basic.checkpassword': checkpasshash_u,
+ 'tools.auth_basic.accept_charset': 'UTF-8',
},
}
root = Root()
root.basic = BasicProtected()
root.basic2 = BasicProtected2()
+ root.basic2_u = BasicProtected2_u()
cherrypy.tree.mount(root, config=conf)
def testPublic(self):
@@ -69,7 +89,10 @@ class BasicAuthTest(helper.CPWebCase):
def testBasic(self):
self.getPage('/basic/')
self.assertStatus(401)
- self.assertHeader('WWW-Authenticate', 'Basic realm="wonderland"')
+ self.assertHeader(
+ 'WWW-Authenticate',
+ 'Basic realm="wonderland", charset="UTF-8"'
+ )
self.getPage('/basic/',
[('Authorization', 'Basic eHVzZXI6eHBhc3N3b3JX')])
@@ -93,3 +116,20 @@ class BasicAuthTest(helper.CPWebCase):
[('Authorization', 'Basic eHVzZXI6eHBhc3N3b3Jk')])
self.assertStatus('200 OK')
self.assertBody("Hello xuser, you've been authorized.")
+
+ def testBasic2_u(self):
+ self.getPage('/basic2_u/')
+ self.assertStatus(401)
+ self.assertHeader(
+ 'WWW-Authenticate',
+ 'Basic realm="wonderland", charset="UTF-8"'
+ )
+
+ self.getPage('/basic2_u/',
+ [('Authorization', 'Basic eNGO0LfQtdGAOtGX0LbRgw==')])
+ self.assertStatus(401)
+
+ self.getPage('/basic2_u/',
+ [('Authorization', 'Basic eNGO0LfQtdGAOtGX0LbQsA==')])
+ self.assertStatus('200 OK')
+ self.assertBody("Hello xюзер, you've been authorized.")
diff --git a/cherrypy/test/test_auth_digest.py b/cherrypy/test/test_auth_digest.py
index 8f71a8dc..0387e33e 100644
--- a/cherrypy/test/test_auth_digest.py
+++ b/cherrypy/test/test_auth_digest.py
@@ -5,9 +5,19 @@
import cherrypy
from cherrypy.lib import auth_digest
+from cherrypy._cpcompat import ntob
from cherrypy.test import helper
+from six.moves.urllib.parse import quote as urlencode
+
+
+def _fetch_users():
+ return {'test': 'test', 'йюзер': 'їпароль'}
+
+
+get_ha1 = cherrypy.lib.auth_digest.get_ha1_dict_plain(_fetch_users())
+
class DigestAuthTest(helper.CPWebCase):
@@ -26,15 +36,12 @@ class DigestAuthTest(helper.CPWebCase):
return "Hello %s, you've been authorized." % (
cherrypy.request.login)
- def fetch_users():
- return {'test': 'test'}
-
- get_ha1 = cherrypy.lib.auth_digest.get_ha1_dict_plain(fetch_users())
conf = {'/digest': {'tools.auth_digest.on': True,
'tools.auth_digest.realm': 'localhost',
'tools.auth_digest.get_ha1': get_ha1,
'tools.auth_digest.key': 'a565c27146791cfb',
- 'tools.auth_digest.debug': 'True'}}
+ 'tools.auth_digest.debug': True,
+ 'tools.auth_digest.accept_charset': 'UTF-8'}}
root = Root()
root.digest = DigestProtected()
@@ -42,60 +49,38 @@ class DigestAuthTest(helper.CPWebCase):
def testPublic(self):
self.getPage('/')
- self.assertStatus('200 OK')
+ assert self.status == '200 OK'
self.assertHeader('Content-Type', 'text/html;charset=utf-8')
- self.assertBody('This is public.')
+ assert self.body == b'This is public.'
- def testDigest(self):
+ def _test_parametric_digest(self, username, realm):
self.getPage('/digest/')
- self.assertStatus(401)
+ assert self.status_code == 401
- value = None
- for k, v in self.headers:
- if k.lower() == 'www-authenticate':
- if v.startswith('Digest'):
- value = v
- break
+ msg = 'Digest authentification scheme was not found'
+ www_auth_digest = tuple(filter(
+ lambda kv: kv[0].lower() == 'www-authenticate'
+ and kv[1].startswith('Digest '),
+ self.headers,
+ ))
+ assert len(www_auth_digest) == 1, msg
- if value is None:
- self._handlewebError(
- 'Digest authentification scheme was not found')
-
- value = value[7:]
- items = value.split(', ')
+ items = www_auth_digest[0][-1][7:].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']))
-
- get_ha1 = auth_digest.get_ha1_dict_plain({'test': 'test'})
+ assert tokens['realm'] == '"localhost"'
+ assert tokens['algorithm'] == '"MD5"'
+ assert tokens['qop'] == '"auth"'
+ assert tokens['charset'] == '"UTF-8"'
+
+ nonce = tokens['nonce'].strip('"')
# Test user agent response with a wrong value for 'realm'
- base_auth = ('Digest username="test", '
- 'realm="wrong realm", '
+ base_auth = ('Digest username="%s", '
+ 'realm="%s", '
'nonce="%s", '
'uri="/digest/", '
'algorithm=MD5, '
@@ -104,36 +89,34 @@ class DigestAuthTest(helper.CPWebCase):
'nc=%s, '
'cnonce="1522e61005789929"')
+ encoded_user = urlencode(username, 'utf-8')
auth_header = base_auth % (
- nonce, '11111111111111111111111111111111', '00000001')
+ encoded_user, realm, nonce,
+ '11111111111111111111111111111111', '00000001',
+ )
auth = auth_digest.HttpDigestAuthorization(auth_header, 'GET')
# calculate the response digest
- ha1 = get_ha1(auth.realm, 'test')
+ ha1 = get_ha1(auth.realm, auth.username)
response = auth.request_digest(ha1)
- # send response with correct response digest, but wrong realm
- auth_header = base_auth % (nonce, response, '00000001')
- self.getPage('/digest/', [('Authorization', auth_header)])
- 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_header = base_auth % (
- nonce, '11111111111111111111111111111111', '00000001')
- auth = auth_digest.HttpDigestAuthorization(auth_header, 'GET')
- # calculate the response digest
- ha1 = get_ha1('localhost', 'test')
- response = auth.request_digest(ha1)
- # send response with correct response digest
- auth_header = base_auth % (nonce, response, '00000001')
+ encoded_user, realm,
+ nonce, response, '00000001',
+ )
self.getPage('/digest/', [('Authorization', auth_header)])
- self.assertStatus('200 OK')
- self.assertBody("Hello test, you've been authorized.")
+
+ def test_wrong_realm(self):
+ # send response with correct response digest, but wrong realm
+ self._test_parametric_digest(username='test', realm='wrong realm')
+ assert self.status_code == 401
+
+ def test_ascii_user(self):
+ self._test_parametric_digest(username='test', realm='localhost')
+ assert self.status == '200 OK'
+ assert self.body == b"Hello test, you've been authorized."
+
+ def test_unicode_user(self):
+ self._test_parametric_digest(username='йюзер', realm='localhost')
+ assert self.status == '200 OK'
+ assert self.body == ntob(
+ "Hello йюзер, you've been authorized.", 'utf-8',
+ )
diff --git a/cherrypy/test/test_httpauth.py b/cherrypy/test/test_httpauth.py
deleted file mode 100644
index eed3666c..00000000
--- a/cherrypy/test/test_httpauth.py
+++ /dev/null
@@ -1,195 +0,0 @@
-from hashlib import md5, sha1
-
-import cherrypy
-from cherrypy._cpcompat import ntob
-from cherrypy.lib import httpauth
-
-from cherrypy.test import helper
-
-
-class HTTPAuthTest(helper.CPWebCase):
-
- @staticmethod
- def setup_server():
- class Root:
-
- @cherrypy.expose
- def index(self):
- return 'This is public.'
-
- class DigestProtected:
-
- @cherrypy.expose
- def index(self):
- return "Hello %s, you've been authorized." % (
- cherrypy.request.login)
-
- class BasicProtected:
-
- @cherrypy.expose
- def index(self):
- return "Hello %s, you've been authorized." % (
- cherrypy.request.login)
-
- class BasicProtected2:
-
- @cherrypy.expose
- def index(self):
- return "Hello %s, you've been authorized." % (
- cherrypy.request.login)
-
- def fetch_users():
- return {'test': 'test'}
-
- def sha_password_encrypter(password):
- return sha1(ntob(password)).hexdigest()
-
- def fetch_password(username):
- return sha1(b'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(b'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)
-
- def testPublic(self):
- self.getPage('/')
- self.assertStatus('200 OK')
- self.assertHeader('Content-Type', 'text/html;charset=utf-8')
- 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.")
diff --git a/docs/basics.rst b/docs/basics.rst
index 1d2ff290..8603cff3 100644
--- a/docs/basics.rst
+++ b/docs/basics.rst
@@ -780,7 +780,8 @@ SSL or within a closed network.
'/protected/area': {
'tools.auth_basic.on': True,
'tools.auth_basic.realm': 'localhost',
- 'tools.auth_basic.checkpassword': validate_password
+ 'tools.auth_basic.checkpassword': validate_password,
+ 'tools.auth_basic.accept_charset': 'UTF-8',
}
}
@@ -815,7 +816,8 @@ basic one explained above.
'tools.auth_digest.on': True,
'tools.auth_digest.realm': 'localhost',
'tools.auth_digest.get_ha1': auth_digest.get_ha1_dict_plain(USERS),
- 'tools.auth_digest.key': 'a565c27146791cfb'
+ 'tools.auth_digest.key': 'a565c27146791cfb',
+ 'tools.auth_digest.accept_charset': 'UTF-8',
}
}