I use the Python/Django write the backend, use Django-Rest-Framework write the APIs, I also used the rest_auth
, allauth
, see my settings.py
:
INSTALLED_APPS = [
...
'corsheaders',
'rest_framework',
'rest_framework.authtoken',
'rest_framework_docs', # API docs
'rest_auth',
'allauth',
'allauth.account',
but when the frontend access the APIs, it will must add the Authorization
in the
Request Header, otherwise can not access success:
as a example:
var that = this
// login
that.$http.post(Urls.users.login(), params).then((response) => {
that.$Cookies.set('token', response.data.key);
}).catch((response) => { // if the header do not have `Authorization`, there will go to there directly, and pay attention: the response is undefined.
}
)
You add 'rest_framework.authtoken'
to INSTALLED_APPS
and set
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAuthenticatedOrReadOnly',
),
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.TokenAuthentication',
)
}
in settings.py.
Then DjangoRestFramework
will check you identity when you ask server with unsafe method like post\patch\delete
.You login
method is handle by post
method which will ask identity.But you get your token
after login
.
Two way to handle you problem, one is set:
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.AllowAny',
),
which is not recommend.second way is set permissions for your login
method like:
from rest_framework.permissions import AllowAny
@list_route(methods=['POST'], permission_classes=[AllowAny])
def login(self, request):
pass