1

I am pretty new to Django, but I want to learn how to implement a DRF Token Authentication with Angularjs. Some of the tutorials I have found haven't been too helpful in showing how to set it up, along with their source code etc...

Also, for production purposes, is it more practical to use a third party package? Or set up my own (it's for a personal project, so time contribution is not an issue).

My Buggy Code for Token Auth: Github

Shah
  • 178
  • 1
  • 1
  • 11
  • You want token authentication with AngularJS? Is this app going to be deployed on a mobile phone with secure token storage? If not, why not use sessions, username/password authentication, and CSRF protection? If you're new to web app development, I believe that token authentication is not the path one normally takes when interacting with users. Token Authentication with DRF is more used for mobile apps or non-users and non-browsers talking to DRF. – Ross Rogers Sep 10 '15 at 17:54
  • I looked into that first, but someone had mentioned to me that because of the 'stateless' nature of the REST api, I should be using Tokens. Is that right (if it makes sense?) – Shah Sep 10 '15 at 22:44
  • A token is like a full set of keys for impersonating a person. No username. No password. The token lets you act like the person until the administrator ( or some process/API that you will have to write) goes into token table and revokes or deletes the token. So, you have to guard that token with your life and if anyone steals the token, they can impersonate your user. – Ross Rogers Sep 11 '15 at 01:35
  • Meanwhile, a django session has a default timeout of [2 weeks](https://docs.djangoproject.com/en/1.8/ref/settings/#std:setting-SESSION_COOKIE_AGE). The session ID stored in your site's cookie is protected by the browser against drive by [XSS](http://bit.ly/1l6sxyp) by external, malicious sites. If they do end up acquiring the Session ID by physical access to the machine, browser vulnerability, or [man in the middle attack](http://bit.ly/KeB2ty) , it is valid for 2 weeks, instead of indefinitely or when you finally catch on to the intruder. If you're doing a website, sessions are the way to go. – Ross Rogers Sep 11 '15 at 01:41

2 Answers2

1

In settings.py

INSTALLED_APPS = (
    ...
    'rest_framework.authtoken'
)
REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework.authentication.TokenAuthentication',
    ],
}

In signals.py

from django.conf import settings
from django.db.models.signals import post_save
from django.dispatch import receiver
from rest_framework.authtoken.models import Token

@receiver(post_save, sender=settings.AUTH_USER_MODEL)
def create_auth_token(sender, instance=None, created=False, **kwargs):
    if created:
        Token.objects.create(user=instance)

In views.py

class ExampleAuthToken(APIView):
    def post(self, request, format=None):
        username = request.data.get("username")
        password = request.data.get("password")
        try:
            user = User.objects.get(username=username)
        except User.DoesNotExist:
            user = User.objects.create_user(username=username)
            user.set_password(password)
            user.save()
        content = {
            'user': unicode(user.username),
            'token': unicode(user.auth_token),
        }
        return Response(content)

In urls.py

urlpatterns = [
    url(r'^authtoken/', ExampleAuthToken.as_view(), name='authtoken'),
]

To call using the angularjs;

var credentials = {
  username: "root",
  password: "root123"
};

$.post("http://localhost:8000/authtoken/", credentials {
    success: function(data){
          console.log(data);
    }
}
Seenu S
  • 3,381
  • 6
  • 30
  • 45
  • So I implemented your code, but I keep getting the 403 Forbidden response. I am sending a POST via $resource. Is there something that I may be missing? I can upload code – Shah Sep 10 '15 at 20:01
  • You are missing the csrf_token while posting. Try to send csrf token. – Seenu S Sep 10 '15 at 20:02
  • Try this link to add csrf token http://stackoverflow.com/questions/12823524/how-to-create-a-post-request-including-csrf-token-using-django-and-angularjs – Seenu S Sep 10 '15 at 20:45
  • I followed what the more recent post was with adding $httpProvider.defaults.xsrfCookieName = 'csrftoken'; and the same for HeadersName = 'X-CSRFToken' to my config file, but I still get the error. I've been trying to find out what the problem is to no avail. – Shah Sep 10 '15 at 22:45
0

I would definitely use a library. For token authentication there is the nifty django-rest-framework-jwt - it's straightforward to install and setup. To help with Angular JS looks like there is drf-angular-jwt (which uses DRF-JWT but I have not used it).

djq
  • 14,810
  • 45
  • 122
  • 157