Richard
Richard

Reputation: 65560

Understanding SessionAuthentication in django-rest-framework?

I am using Django v1.8 and django-rest-framework v3.2.2. I have a site with a public-facing API, which is also consumed by my own site (on the same domain) as the Ajax back-end to a JavaScript application, using GET only.

I want public users of this API to be asked for a key parameter in the URL, which I will issue manually. But I also want my JavaScript application to be able to use the API, in a way that means that other users can't just steal the key and use it.

I have set up my custom key authentication as described here, and it's working well.

However, I'm unclear on how the JavaScript application should use the API. Obviously I could just pass a dedicated key parameter in the URL, but then won't other users trivially be able to spot the key and use it?

I think I need SessionAuthentication, but how do I even start to make this work? I can't see any instructions in the DRF documentation about how I need to change my JavaScript calls to use it.

Also I don't understand how SessionAuthentication allows the Ajax app to authenticate without other users being able to see and copy the authentication.

Very grateful for any advice.

Upvotes: 1

Views: 1616

Answers (1)

Linovia
Linovia

Reputation: 20986

I think I need SessionAuthentication, but how do I even start to make this work? I can't see any instructions in the DRF documentation about how I need to change my JavaScript calls to use it.

SessionAuthentication is the Django's one. It uses session to authenticate a user. It's mostly transparent for ajax request as the browser will send the cookie automatically. However, if you're posting data, you need to make sure you send the CSRF token in both headers and post body.

Also I don't understand how SessionAuthentication allows the Ajax app to authenticate without other users being able to see and copy the authentication.

As said above, it uses cookies for that. They are part of the headers and thus usually not seen on the urls. To make sure no-one else can steal user's session you need to run the site through https. This isn't much different from regular websites.

Upvotes: 1

Related Questions