I have two separate Flask applications, one is an API with the domain "admin.company.com" and the second one is a dashboard under the domain "dashboard.company.com".
My main goal is to secure the api and enable authentication.
I set up authentication on the api and when I'm testing it via the swagger-ui it works good with no issues. I manage to authenticate myself and submit requests. On top of that, in the token_required() below I coded a section that expects to receive JWT and decode it:
def token_required(f):
#wraps(f)
def decorator(*args, **kwargs):
token = None
if 'jwt-token' in request.headers:
token = request.headers['jwt-token']
if not token:
return jsonify({'message': 'a valid token is missing'})
try:
current_user = False
# for authentication via the swagger-ui
if token == 'my_awesome_password':
current_user = 'admin'
else:
data = jwt.decode(token, app.secret_key)
current_user = 'admin' if data['public_id'] == 'admin' else False
if not current_user:
return jsonify({'message': 'token is invalid'})
except:
return jsonify({'message': 'token is invalid'})
return f(*args, **kwargs)
return decorator
The problem is with the dashboard application:
On the dashboard app, I configured the /login route to generate JWT (which needs to be sent to the api app in every HTTP request I made), then do a set_cookie() with httpOnly=True flag (for security purposes), but then how can the JavaScript access it when it has to make XHR requests? Having the httpOnly flag on makes it unreachable.
If using httpOnly=True is not the ideal way in this case, how can I tackle it and make sure the JWT will always be sent to the api app in the request headers?
I'm using PyJWT package.
Thanks for any help.
If you use JWTs for XHR requests, then you don't necessarily need to use cookies – the browser/consumer could store the token and attach it to every request. If you do want to use cookies (this is also a viable option) then you don't need to worry about attaching the JWT as the browser will do that automatically for the domains you specified in the set_cookie command.
Related
I am trying to use Python's Authlib package. For that I am defining a login endpoint and an authorized redirect endpoint. I am trying to secure the login endpoint, verify identity and pass it to the authorized endpoint so that tokens can be saved with user's identity.
class GithubLogin(Resource):
#classmethod
def get(cls):
response = custom_verify_jwt_in_request(request)
if response.status_code != 200:
return {"message": "Unauthorized"}, 401
redirect_uri = url_for("github.authorize", _external=True, _scheme=os.getenv("URL_SCHEME", "https"))
return oauth.github.authorize_redirect(redirect_uri, email=response['email'])
class GithubAuthorize(Resource):
#classmethod
def get(cls):
print(request.args)
# Here I can't find the email parameter I have supplied before the redirect.
Is there a way to handle this case? Preferably without having a dynamic redirect url because apparently it has security flaws.
Thanks!
I am not able to figure out how do I continue the request flow after refreshing the expired JWT token in my Flask application.
I am storing access token and refresh token in their respective cookies.
This is how my flow looks like right now:
Below is my decorator function that checks validity of the JWT token
def check_valid_jwt(f):
#wraps(f)
def wrapper():
print(request.cookies)
if 'access_token_cookie' in request.cookies:
print('Verify Signature')
# some code that verifies the JWT signature
print('Signature verification successful')
# some code that extracts claims from the token
if time.time() > claims['exp']:
print('Token is expired')
# some code that get the new access token using refresh token
# What am I supposed to do here after I get the refresh token and continue the request while adding the new token to access_token cookie?
return f()
return wrapper
Here is how my protected endpoint looks like:
#check_valid_jwt
def secretpage():
return render_template("/home/secret_page.html")
After I get the refresh token, I want to continue the flow of the request and add new access token in the cookie but if I add that in check_valid_jwt decorator function, secretpage handler will have no idea that a new access token has been issued.
How do I do it in such a way that if a new access token has been issued, it gets added to the response. Am I complete off here and this is not how Authentication flow works?
The best way is to create a middleware for JWT authentication instead of a decorator
from flask import Flask
class JWTAuthMiddleware(object):
def __init__(self, app):
self.app = app
def __call__(self, environ, start_response):
access_token = environ.get('HTTP_AUTHORIZATION', None)
# validate access token here and get new one if required by using refresh token
# you can also update the invalid token in the header here if you want
environ['HTTP_AUTHORIZATION'] = 'new access token'
return self.app(environ, start_response)
Now wrap the actual wsgi app with this one
app = Flask(__name__)
app.wsgi_app = JWTAuthMiddleware(app.wsgi_app)
I'm looking to propagate a JWT token between my services running in docker using the library flask-jwt-extended and I have an idea of how I would do this using something similar to this:
request.post(url, json={"access_token": access_token, "refresh_token": refresh_token)
But in my experience I need to return a response to do this.
I already have the frontend creating tokens and protecting my routes. I just want to use that token to do the same for the backend.
I want to be able to login from my frontend application and when I login that propagates the token throughout the other services. How do I approach this?
I will send the post request to a function that will look something similar to this:
#app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == "POST":
resp = jsonify({'login': True})
set_access_cookies(resp, request.json["access_token"])
set_refresh_cookies(resp, request.json["refresh_token"])
return resp, 200
Do I need to return that response?
Token sharing should be accomplished via signature trust. Make sure that your other services "know" the public key of the trusted signer.
Here's the basics:
Frontend requests token from backend via authorization api
Backend validates credentials, issues token using 'RSXXX' algorithm, eg. 'RS512'
Frontend passes token to all calls to any of your backend services.
When backend receives a token it verifies signature and "source" using the public key identity of the token before applying token payload to the requested operation.
All backend services and the frontend should have a configuration element which defines one or more trusted public keys used for token signing.
This article has some helpful information on using a public/private key pair with pyjwt:
https://blog.miguelgrinberg.com/post/json-web-tokens-with-public-key-signatures
I have been following this Flask pyjwt guide, however my web app is somewhat similar to Miguel's microblog example that uses render_template() and redirect(url_for(...)) for navigation.
I have implemented an encoding and decoding service in my application, however I do not know how to properly return the encoded JWT token to the user using redirect()
My code is as follows:
#app.route('/', methods=['GET', 'POST'])
def login():
login_form = LoginForm()
username = login_form.username.data
password = login_form.password.data
if is_user_valid(username, password):
return redirect(url_for('home'), auth_service.encode_token(username))
render_template('login.html', form=login_form)
My problem is placing the auth token inside the redirect method causes a page to appear saying "Redirecting... you should be redirected, if not click here", which I do not want. I do not particularly wish to change my redirect methods to something similar to make_response(jsonify(...)) as I would then need to handle these responses in the front end when this is a simple login page.
How should I be returning the auth token to the client correctly?
Typically you attach it to response headers which is what your redirect method returns.
response = redirect(url_for('home'))
response.headers['X-JWT-TOKEN'] = auth_service.encode_token(username)
return response
However, I'm not sure if this is gonna be very useful in your setup when using render_template, because you can not easily access these headers on the frontend.
You have two alternatives here:
Make your login endpoint an API. This way you can return the token for the client-side code to handle and store it somehow.
Drop the JWT and stick to using sessions. I know that this is not what you expected, but outside of building APIs JWT-based auth is not very helpful.
Maybe a stupid question here:
Is Requests(A python HTTP lib) support Django 1.4 ?
I use Requests follow the Official Quick Start like below:
requests.get('http://127.0.0.1:8000/getAllTracks', auth=('myUser', 'myPass'))
but i never get authentication right.(Of course i've checked the url, username, password again and again.)
The above url 'http://127.0.0.1:8000/getAllTracks' matches an url pattern of the url.py of a Django project, and that url pattern's callback is the 'getAllTracks' view of a Django app.
If i comment out the authentication code of the 'getAllTracks' view, then the above code works OK, but if i add those authentication code back for the view, then the above code never get authenticated right.
The authentication code of the view is actually very simple, exactly like below (The second line):
def getAllTracks(request):
if request.user.is_authenticated():
tracks = Tracks.objects.all()
if tracks:
# Do sth. here
Which means if i delete the above second line(with some indents adjustments of course), then the requests.get() operation do the right thing for me, but if not(keep the second line), then it never get it right.
Any help would be appreciated.
In Django authentication works in following way:
There is a SessionMiddleware and AuthenticationMiddleware. The process_request() of both these classes is called before any view is called.
SessionMiddleware uses cookies at a lower level. It checks for a cookie named sessionid and try to associate this cookie with a user.
AuthenticationMiddleware checks if this cookie is associated with an user then sets request.user as that corresponding user. If the cookie sessionid is not found or can't be associated with any user, then request.user is set to an instance of AnonymousUser().
Since Http is a stateless protocol, django maintains session for a particular user using these two middlewares and using cookies at a lower level.
Coming to the code, so that requests can work with django.
You must first call the view where you authenticate and login the user. The response from this view will contain sessionid in cookies.
You should use this cookie and send it in the next request so that django can authenticate this particular user and so that your request.user.is_authenticated() passes.
from django.contrib.auth import authenticate, login
def login_user(request):
user = authenticate(username=request.POST.get('username'), password=request.POST.get('password'))
if user:
login(request, user)
return HttpResponse("Logged In")
return HttpResponse("Not Logged In")
def getAllTracks(request):
if request.user.is_authenticated():
return HttpResponse("Authenticated user")
return HttpResponse("Non Authenticated user")
Making the requests:
import requests
resp = requests.post('http://127.0.0.1:8000/login/', {'username': 'akshar', 'password': 'abc'})
print resp.status_code
200 #output
print resp.content
'Logged In' #output
cookies = dict(sessionid=resp.cookies.get('sessionid'))
print cookies
{'sessionid': '1fe38ea7b22b4d4f8d1b391e1ea816c0'} #output
response_two = requests.get('http://127.0.0.1:8000/getAllTracks/', cookies=cookies)
Notice that we pass cookies using cookies keyword argument
print response_two.status_code
200 #output
print response_two.content
'Authenticated user' #output
So, our request.user.is_authenticated() worked properly.
response_three = requests.get('http://127.0.0.1:8000/hogwarts/getAllTracks/')
Notice we do not pass the cookies here.
print response_three.content
'Non Authenticated user' #output
I guess, auth keyword for Requests enables HTTP Basic authentication which is not what is used in Django. You should make a POST request to login url of your project with username and password provided in POST data, after that your Requests instance will receive a session cookie with saved authentication data and will be able to do successful requests to auth-protected views.
Might be easier for you to just set a cookie on initial authentication, pass that back to the client, and then for future requests expect the client to send back that token in the headers, like so:
r = requests.post('http://127.0.0.1:8000', auth=(UN, PW))
self.token = r.cookies['token']
self.headers = {'token': token}
and then in further calls you could, assuming you're in the same class, just do:
r = requests.post('http://127.0.0.1:8000/getAllTracks', headers=self.headers)