Python3 using requests to grab HTTP Auth Data

Ian Kelly ian.g.kelly at gmail.com
Thu Feb 2 14:37:54 EST 2017


On Wed, Feb 1, 2017 at 5:22 PM, Νίκος Βέργος <me.on.nzt at gmail.com> wrote:
> ================================
> # Give user the file requested
>
> print('''<meta http-equiv="refresh" content="5;url=http://superhost.gr/data/files/%s">''' % realfile)
>
> authuser = os.environ.get( 'REMOTE_USER', 'Άγνωστος' )
> print( authuser )
> ================================
>
> Trying this, feels liek i'm almost there except that when printing the value of authuser variable it default to "Άγνωστος" meaning not there.
>
> is there any other way i can grab what the user gave a auth login info?

Hold on, are those consecutive lines within the same script?

I think you need to better understand the HTTP request cycle. The
browser sends a request to your server, the server runs your CGI which
builds a response, and then the server sends the response back to the
browser. At that point the CGI is done with this request.

The <meta> tag that you're printing is part of that response. The
browser can't do anything with it until it sees it. When it does, it
will perform the refresh which creates a second request to the server
at the new URL. If the server's response to the second request is a
401 Unauthorized, then the browser shows the username/password dialog
and after the user enters those it will make a /third/ request
containing that info, also to the new URL.

Your script which ran on the first request is trying to get the
REMOTE_USER from the authentication data that was passed to that first
request, but there wasn't any. The user didn't enter any until the
third request, at which point your script was long since finished
running.

If you want the user to authenticate to your script and not just
whatever file you're redirecting them to, then you need to configure
the server to require authorization for the script and not just the
redirect target. Most likely you would do this with an .htaccess
directive as Michael Torrie already suggested. Once that's done, then
as soon as your script is invoked you'll be able to get the
REMOTE_USER. The <meta> tag has nothing to do with requesting auth and
you only need it if you want the browser to perform a delayed redirect
to that file.



More information about the Python-list mailing list