How to authenticate Android user POST request with Django REST API?

At the moment I have the Django REST API, and all this is very difficult for the web application in which I implemented User Auth in the backend. The login_required clause is good for a cookie based web application.

Now I have an Android app that needs to access the same API. I can log in to my account. I need to know how to authenticate each user when they make a GET / POST request to my views?

There are several solutions in my research: 1) sessions supported by cookies 2) Send username and password with each GET / POST request (maybe this is not safe).

Any ideas?

+4
source share
3 answers

It looks like you are using the Django REST Framework, and then TokenAuthentication might be appropriate. From the docs:

This authentication scheme uses a simple HTTP token protocol authentication scheme. Token identification is suitable for client-server settings, such as native desktop and mobile clients

You do not need to pre-generate tokens, as clients can request them using the built-in obtain_auth_token view, which you configure in your urls.py.

Once the client has received the token for the session, it can provide it on subsequent API calls using the Authorization: HTTP header.

Check out the docs for more info: http://www.django-rest-framework.org/api-guide/authentication/#tokenauthentication

+8
source

Implementing Basic Authentication (BA) HTTP is the easiest method to provide access control to web resources because it does not require cookies, a session ID, and a login page. Rather, Basic HTTP authentication uses static standard HTTP headers, which means that no handshakes should be performed pending

To learn more and get an idea of ​​what you need to do on the server and client side, follow these steps:

http://en.wikipedia.org/wiki/Basic_access_authentication

I used different REST java frameworks and all of them provide simple APIs to add and add a basic header extension.

Django provides some useful snippets of code:

http://djangosnippets.org/snippets/243/

+3
source

You might want to use the Django Sessions middleware, which will set a cookie with django session_id. For the following requests, the session middleware will set the attribute of the request object called by the user, and then you can check if the user is authenticated request.user.is_authenticated () (or login_required decorator). In addition, you can set the session timeout to anything you like in the settings.

This middleware is included in django's default settings.

0
source

Source: https://habr.com/ru/post/1497953/


All Articles