Parse an HTTP request Authorization header with Python

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

    If your response comes in a single string that that never varies and has as many lines as there are expressions to match, you can split it into an array on the newlines called authentication_array and use regexps:

    pattern_array = ['qop', 'realm', 'username', 'response', 'cnonce']
    i = 0
    parsed_dict = {}
    
    for line in authentication_array:
        pattern = "(" + pattern_array[i] + ")" + "=(\".*\")" # build a matching pattern
        match = re.search(re.compile(pattern), line)         # make the match
        if match:
            parsed_dict[match.group(1)] = match.group(2)
        i += 1
    

提交回复
热议问题