Parse an HTTP request Authorization header with Python

前端 未结 10 578
情书的邮戳
情书的邮戳 2020-12-30 06:47

I need to take a header like this:

 Authorization: Digest qop=\"chap\",
     realm=\"testrealm@host.com\",
     username=\"Foobear\",
     response=\"6629fae         


        
10条回答
  •  北荒
    北荒 (楼主)
    2020-12-30 07:30

    If those components will always be there, then a regex will do the trick:

    test = '''Authorization: Digest qop="chap", realm="testrealm@host.com", username="Foobear", response="6629fae49393a05397450978507c4ef1", cnonce="5ccc069c403ebaf9f0171e9517f40e41"'''
    
    import re
    
    re_auth = re.compile(r"""
        Authorization:\s*(?P[^ ]+)\s+
        qop="(?P[^"]+)",\s+
        realm="(?P[^"]+)",\s+
        username="(?P[^"]+)",\s+
        response="(?P[^"]+)",\s+
        cnonce="(?P[^"]+)"
        """, re.VERBOSE)
    
    m = re_auth.match(test)
    print m.groupdict()
    

    produces:

    { 'username': 'Foobear', 
      'protocol': 'Digest', 
      'qop': 'chap', 
      'cnonce': '5ccc069c403ebaf9f0171e9517f40e41', 
      'realm': 'testrealm@host.com', 
      'response': '6629fae49393a05397450978507c4ef1'
    }
    

提交回复
热议问题