0

For logging in, I'm doing something like:

function setHeader(xhr) {
        // as per HTTP authentication spec [2], credentials must be
        // encoded in base64. Lets use window.btoa [3]
        xhr.setRequestHeader("Authorization", "Basic " + btoa(username + ':' + password));
    }

    $.ajax({type: "POST",  url: AUTH_URL,  beforeSend: setHeader}).
        fail(function(resp){
          console.log('bad credentials.')
        }).
        done(function(resp){
        });

after which, I'm storing the Session in local storage.

However, for logging out, I'm unable to figure out how to use this session to send with the request header, so that django's : request.logout() logs out the user having that session id

Saurabh Verma
  • 6,328
  • 12
  • 52
  • 84

2 Answers2

1

For login you can add view similar to this one:

import json
import requests
from django.shortcuts import render_to_response
from django.http import HttpResponseRedirect

@csrf_protect
def login(request):
    if request.method == "POST":
        login = requests.post('http://your_url/api-token-auth/', data={'username': request.POST['username'], 'password': request.POST['password']})
        response = json.loads(login.text)
        if response.status_code == 200:
            token = response['token']
            request.session.flush()
            request.session['user'] = request.POST['username']

            if request.session.test_cookie_worked():
                request.session.delete_test_cookie()

            return HttpResponseRedirect("/")

        else:
            error = "Error"
    request.session.set_test_cookie()
    return render_to_response("login.html", {"error": error}, RequestContext(request))

For logout all you have to do in your view is:

def logout(request):
    request.session.flush()
    return HttpResponseRedirect('/')

On your API side, you have to define api-token-auth in urls: here is the tutorial for more informations

url(r'^api-token-auth/', 'rest_framework.authtoken.views.obtain_auth_token')

This way you will get your token for communication with the API. Beside TokenAuthentication you can define and SessionAuthentication. More about that you can find in the above tutorial

Sasa
  • 1,172
  • 1
  • 15
  • 24
  • My request.session object is empty. My doubt is - how do I form the request object at the client side, which will be send to Django REST API – Saurabh Verma Oct 27 '14 at 12:09
  • Storing request object at the client side could be dangerous. Someone can hijack your request and present himself as you. – Sasa Oct 27 '14 at 12:14
  • So I should somehow store the request object per logged in user at the server side ? If yes, can you please suggest a way to do that ? – Saurabh Verma Oct 27 '14 at 12:15
1

You are using HTTP Basic Authentication, which does not define a way to log users out. It is not tied to the Django session, so you can't clear that. You could potentially clear out the token from session storage, and send an invalid token, though the browser may opt to send the original credentials (untested).

There are quite a few questions about it on Stack Overflow. Your best bet looks like sending invalid credentials, hoping that the user's browser will invalidate any saved ones.

You may be able to use a form of token-based authentication, such as TokenAuthentication or OAuth, which will not be intercepted by the browser. This way you will not need to worry about logging users out, as the authentication is tied directly to requests made with the token.

Community
  • 1
  • 1
Kevin Brown-Silva
  • 40,873
  • 40
  • 203
  • 237