7

I'm trying to write a Python 3.5 Flask application that redirects a user to an OAuth URL, for authentication / authorization. As part of that redirection, I have to include the Authorization header. The built-in redirect() method in Flask doesn't seem to support adding HTTP headers.

What's the proper way of handling this in such an application?

jonrsharpe
  • 107,083
  • 22
  • 201
  • 376
  • Have you tried using https://pythonhosted.org/Flask-OAuth/? – jonrsharpe May 31 '16 at 19:26
  • @jonrsharpe I haven't given that a try, no. I was trying to understand the raw process, but I may end up incorporating something like that eventually. It says it's only compatible with oAuth 1.0a, and there are quite a few oAuth 2.0 services out there. –  May 31 '16 at 19:27
  • If you want to implement it yourself, there's an OAuth 2 example for Flask here: https://github.com/reddit/reddit/wiki/OAuth2-Python-Example. It doesn't appear to be redirecting, though. – jonrsharpe May 31 '16 at 19:31
  • I see that, yeah. Any ideas on what the proper method of redirecting would be, including HTTP headers? I'll take a look at the source for the Flask-oAuth package. –  May 31 '16 at 19:35

1 Answers1

9

You will need to build your own response object to add headers. You can check out the docs here: http://docs.python-requests.org/en/master/api/#requests.Response

A simple example for your use case would be something like:

response = Response(headers={'Authorization': 'whatever'},
                    is_redirect=True,
                    url="https://your-redirected-url.com")
return response

Edit: Further info

Also, I would check out https://github.com/lepture/flask-oauthlib if you are interested in using a library. It has support for oAuth1 and oAuth2 and it is relatively easy to setup with a standard Flask app.

Edit: Another way of doing it

This morning I remembered a simpler way to do this. You can call the redirect function and it will return a flask Response object. Then you are able to set the headers on that newly created object.

response = redirect('https://url')
response.headers = {'authorization': 'whatever'}  
return response
pech0rin
  • 4,031
  • 3
  • 17
  • 19
  • Thanks, but according to Python 3.5's requests library, the Response() class is not callable. Therefore, I can't instantiate it. Any thoughts? –  Jun 01 '16 at 06:27
  • The above answer is using flasks Response class. I will update with an additional solution that does not create it's own Response object. – pech0rin Jun 01 '16 at 13:41
  • 1
    The above answer is using an addon module, not the flasks Response class. – Bob Jordan Nov 28 '16 at 08:19
  • Some update ? I need the same thing, i need to get the username and password and add the others data to get a token, but it looks hard – Luis Souza Jul 20 '18 at 00:55
  • I'm using python3 and I get this error: TypeError: __init__() got an unexpected keyword argument 'is_redirect' – Vladimir Despotovic Jun 06 '21 at 20:25