How to make Django REST JWT Authentication scale w

2019-04-01 05:57发布

I currently have a Django app that is simply a bunch of REST APIs (backed by a database of course). I am managing my authentications with Django REST framework JWT. It's working fine. Whenever a user logs in, one of my API returns a token that the consuming application stores for later usage. So far so good.

However, in the future, this solution will need to scale. And instead of having a single server running the Django app, I can forsee a situation when I will need multiple Webservers. Of course all those webservers will be connected to the same Database. But since the token is not stored in the Database, how will this work with mulitple web servers? A token issued by one server won't be valid on another.

So how have other people solved this problem??

2条回答
我欲成王,谁敢阻挡
2楼-- · 2019-04-01 06:24

Depends on how frequently you think the database will be hit. My first instinct would be to cache the token and use memcached for that. Django has good support for that. Things are a little different (configuration-wise) if you are using a cloud platform like GAE/Python or AWS but solutions exist for both and not terribly hard.

查看更多
萌系小妹纸
3楼-- · 2019-04-01 06:29

In short you do NOT need to worry about scaling with JWT

Detail explanation:

First let's understand the implementation difference between the default token authentication provided by Django-Rest-Framework(DRF) and the token provided by DRF-JWT

Token provided by DRF

rest_framework.authentication.TokenAuthentication

Token creation:

1) Create token

Token.objects.create(user=user)

2) Store the token created at step1 at the database

3) Return the token to the client

Token authentication:

1)Check if the token pass by the client exist in the database

2)If the token exist, this means that the user is authenticated

Token provided by DRF-JWT

rest_framework_jwt.authentication.JSONWebTokenAuthentication

Token creation:

1) Create token

body = base64encode(header) + "." + base64encode(payload)

signature = HMACSHA256_encode(body, 'secret_key') #secret key is usually specify in your settings.py

token = body + "." + signature

2) Return the token to the client

Token authentication:

1)Decode the token

token_segment = token.split('.')

body = token_segment[0] + "." + token_segment[1]

signature = token_segment[2]

decode_body = HMACSHA256_decode(signature, 'secret_key')

2)If decode_body is equal to body, the user is authenticated

Conclusion

From the mechanism above, we can safely conclude that the JWT approach is more scalable because it just depends solely on secret_key, and every webserver should have the secret_key under settings.py

So to answer your question, you do not need to worry about scaling it :)

查看更多
登录 后发表回答