I implement a web application (with Python Django - to the extent that matters). Users can log in normally with username and password, but in addition I want to provide an API which users use to script the interaction with my site.
For the API authentication my plan was to do something like this:
- In the database I create table with 'tokens' - i.e. random strings which point to the user database.
- The user gets a token string.
- For every API call the user passes the token string along with their request
In the API implementation the code:
- Verify the token.
- Log the correct user in and execute the API function as the user matching the token.
- Log the user out again.
- Return the result
Does this make sense? On the one hand it seems very simple - on the other hand it feels quite homemade, something I have heard is not recommended when it comes to security related topics?
CodePudding user response:
I would wholeheartedly recommend looking at django-rest-framework
https://www.django-rest-framework.org/
It literally does all of that and more!
Nope, not a sales person, just a developer :)
It handles quite literally any use case you can think of, and I would be happy to discuss at great length any its not suitable for.
It handles:
- Authentication
- Parsing
- Encoding
- View or object level permissions
- Object serialisation
- Object creation
- Object deletion
- Automatically generated documentation
- Several authentication methods, including custom managed methods
- And a bunch of other stuff that makes writing API's in Django much easier
All in all it supports most if not all use cases.
EDIT
It is worth noting that there is a very good reason DRF has short lived access tokens. That is because of security.
Let's say a malicious actor gets hold of your short lived access token, thats a lot better than a "long life" one as you described.
It's worth weighing up security and ease of access, security and protecting your users should always paramount.
Futhermore, I would recommend taking a look at DRF Knox, which is recommended in the authentication section of the DRF docs: