Token Authentication for RESTful API: should the t

2019-01-09 21:42发布

I'm building a RESTful API with Django and django-rest-framework.

As authentication mechanism we have chosen "Token Authentication" and I have already implemented it following Django-REST-Framework's documentation, the question is, should the application renew / change the Token periodically and if yes how? Should it be the mobile app that requires the token to be renewed or the web-app should do it autonomously?

What is the best practice?

Anybody here experienced with Django REST Framework and could suggest a technical solution?

(the last question has lower priority)

8条回答
【Aperson】
2楼-- · 2019-01-09 22:36

Thought I'd give a Django 2.0 answer using DRY. Somebody already built this out for us, google Django OAuth ToolKit. Available with pip, pip install django-oauth-toolkit. Instructions on adding the token ViewSets with routers: https://django-oauth-toolkit.readthedocs.io/en/latest/rest-framework/getting_started.html. It's similar to the official tutorial.

So basically OAuth1.0 was more yesterday's security which is what TokenAuthentication is. To get fancy expiring tokens, OAuth2.0 is all the rage these days. You get an AccessToken, RefreshToken, and scope variable to fine tune the permissions. You end up with creds like this:

{
    "access_token": "<your_access_token>",
    "token_type": "Bearer",
    "expires_in": 3600,
    "refresh_token": "<your_refresh_token>",
    "scope": "read"
}
查看更多
相关推荐>>
3楼-- · 2019-01-09 22:38

You can leverage http://getblimp.github.io/django-rest-framework-jwt

This library is able generate token that has an expiration date

To understand the difference between DRF default token and the token provide by the DRF take a look at:

How to make Django REST JWT Authentication scale with mulitple webservers?

查看更多
登录 后发表回答