Parse an HTTP request Authorization header with Python

前端 未结 10 565
情书的邮戳
情书的邮戳 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:40

    I would recommend finding a correct library for parsing http headers unfortunately I can't reacall any. :(

    For a while check the snippet below (it should mostly work):

    input= """
     Authorization: Digest qop="chap",
         realm="testrealm@host.com",
         username="Foob,ear",
         response="6629fae49393a05397450978507c4ef1",
         cnonce="5ccc069c403ebaf9f0171e9517f40e41"
    """
    
    field, sep, value = input.partition(":")
    if field.endswith('Authorization'):
       protocol, sep, opts_str = value.strip().partition(" ")
    
       opts = {}
       for opt in opts_str.split(",\n"):
            key, value = opt.strip().split('=')
            key = key.strip(" ")
            value = value.strip(' "')
            opts[key] = value
    
       opts['protocol'] = protocol
    
       print opts
    

提交回复
热议问题