How to authenticate users using GET request in FastAPI? - python

I am new to APIs and I need to be able to authenticate users using a GET request, in order to automate processes in airflow.
Is it possible to authenticate using GET request? For example:
hhtp://localhost:8000/transformar?user:password

In general, it is a very bad idea to do password authentication in a GET request. The obvious reason is that you have the username and password in the URL params (after ?).
The standard way of doing it is having a login API something like
POST http://localhost:8000/login and provide the username and password in form-data. When you authenticate the user, you can return a token. This can be an API Key of a JWT token, etc.
Now, using this token you want to send any following requests. So, in the next GET request, place this token in your header under "Authentication". Once you verify the token, you can return response data or, otherwise, raise a 403 Unauthorised error.
FastAPI provides proper documentation on how to implement this here.

Related

Django Rest API: Using both token authentication and session authentication

I've tried to implement two ways of logging into the Django API: token-based authentication and session authentication.
Token based authentication works fine when session based authentication isn't implemented, but when I activate session based authentication, the token based authentication endpoint only returns ""CSRF Failed: CSRF token missing or incorrect".
Now, I know with session based authentication I need to set the csrf header, but is there a way to bypass this for specific endpoints, or for when a token auth header has been included in the request?
Thanks for any answers :)

Authenticate an API call correctly with requests and sessions

I want to call my own API in a custom view I wrote. Normally I use JWT authentication with my API calls. In this specific view though, I'd like to use a different authentication.
I want to enable logged in users to make a successful get call (without a token). Not logged in users should not be able to make that call. I tried this with Basic Authentication and Session Authentication but don't really get it tow work.
Here is my view that makes the API call:
def visualize_buildings(request, id):
passed_id = id
endpoint = 'linktomyendpoint' + str(passed_id)
response = requests.get(endpoint)
building_group_data = response.json()
# print(building_group_data)
if 'buildings' in building_group_data:
building_data = building_group_data['buildings']
context = {'building' : building_data}
return render(request, 'building_group_visualize_api.html', context)
else:
return HttpResponseNotFound("Ups. We are sorry but no Building Group was found with that id")
Here my API view:
class BuildingGroupRetrieveAPIView(RetrieveAPIView):
authentication_classes = [JSONWebTokenAuthentication,
SessionAuthentication, BasicAuthentication]
serializer_class = BuildingGroupSerializer
queryset = BuildingGroup.objects.all()
The view works with if I send a token in the headers. But how can I use Session Authentication with that? I tried getting username and password from the request and then pass it to the API call. But that doesn't work because I can't decode the password from the request (which makes sense).
So I tried to follow this: https://2.python-requests.org/en/master/user/advanced/ but I still can't authenticate my request.
Can anyone point me into the right direction? Help is very much appreciated! Thanks in advance!
Session ids are saved as a cookie on the user's device and they will be sent to the server as a header name Cookie. So if you want to use cookies instead of the JWT token then you should send your request with the session id as a cookie header.
This is the header that lets Django know your session-id when you visit the site directly:
Cookie: csrftoken=some-csrf-token; sessionid=your-session-id
Now to make your request contain something like that:
cookies = {'sessionid': 'your-session-id'}
response = requests.get(endpoint, cookies=cookies)
Note that Django might still through an error for csrf token based on your settings.
You can find your session-id on your browser. If you don't know where and how to access them, just google it. it's different based on the browser you use.

User authentication for Flask API on mobile

I am making an API in Flask for a simple jQuery mobile + PhoneGap app to be packaged and downloaded. As I understand, all the calls to the database should be made with JavaScript, AJAX, and JSON. Since the app is about the user, and all of the views draw data from the logged user, I am not sure how to proceed with the authentication. As I understand, the workflow should be:
user logs in (json encoded username and password)
server generates token with expiration (i.e. 24h) for that user
this token is saved on the mobile app as a cookie or in localstorage
all of the calls to the server are done with this token which identifies the current user: /api/token=12345
when the toke expires, a new login prompt is required
I thought of implementing this with Flask-Security's authentication token. Is there a more straightforward way of accomplishing this?
Flask-JWT seems like a pretty straight-forward solution.
Then on the front end you can just add an HTTP interceptor to add X-Auth-Token to the headers or something.

Keep User authenticated using Django Rest and Phonegap?

I have read multiple tutorials on authentication but I am just as confused. I am trying to log a user in using an html form on the client device, which means I'm not using Django templates. Does it work like the following?
I send a post to rest backend with username, password combo
Django rest checks to see if valid user, and sends token back?
I save token in local storage, and send with every request of user?
What do I send from the front end to make this happen?
Yes, send a post request to a RESTful backend with username and password combo
Django authenticates the username and password and logs the user in which sets a sessionid associated with the user which I believe you are referring to as a token. This is done via the login() method. https://docs.djangoproject.com/en/dev/topics/auth/default/#django.contrib.auth.login
Normally Django would set a sessionid as a coookie or session variable on the client's machine, but I'd imagine you could save it in local storage and then retrieve it each time and validate it's a valid sessionid on each request but it's easier to just let Django's middleware take care of everything by just using sessions.

django rest Framework authentications

I have developed an API using django rest framework and have used Token based authentication, Now I have trying to use it from separate project. How I can login using userid and password and get token in response and use token in header in all next url calls.
From Shell I have checked token for one of the user and tested api from terminal and it's working like,
http://127.0.0.1:8000/corporate/company/ -H 'Authorization: Token 9f4702dfddbf89e0346b2ffd10fd69173c178273'
But how to use this token in http calls?
I have included rest_framework.authtoken in installed app and included url in urls.py as:
url(r'^api-token-auth/', 'rest_framework.authtoken.views.obtain_auth_token')
Now I have trying to get it accessed from another project, where I have made one of the login form? Now the Question is where to post form and what fields should be there in form. If I have posted form then token will be returned in response then how Can I parse and use in headers on next calls?
I have gone through tutorial and API guide but no help. On how to access api in my project while Api is ready and login is working through browser-able api url.
Django rest framerwork supports many auth options. You can use Basic Auth if you want.
If you want to use the token you will need to set an http header with the correct token for your user.
From the docs you need to set it as (replace 99... with yours)
Authorization: Token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b

Categories