Django REST framework JWT checks user from database with every request - django

I'm using Django REST framework JWT library for authentication in my django application. And I thought the whole idea of using JSON Web Token Authentication was NOT having a database trip in every request.
But it still retrieves user's data (which is stored in the token's PAYLOAD) from database per request.
What am I doing wrong?

The webtoken mechanism and the server authentication internals are rather orthogonal.
The web token just allows the holder to say who they are. It is similar to holding a user's username and password, except the token can be revoked without the user having to learn a new password. This authentication technique has nothing to do with whether the server will do a database access.
If you wish to eliminate a DB access during authentication on the server, you can use some sort of authentication caching mechanism like django-cached_authentication_middleware.

Related

How to integrate Facebook Login in django-graphql-jwt?

We have a django project that uses the Graphene-Django library to implement a GraphQL API in our project. This backend is accessed by our mobile apps. For the authentication of the apps, we use the django-graphql-jwt library, which is a JSON Web Token library in Django with GraphQL approach.
Now we want to implement the Facebook Login in our system and with it the authentication happens in Facebook. After authentication, what will be sent to our backend from the mobile app is only the email of the user. How can I register and authenticate the user in django-graphql-jwt without the password? Or is there a better workflow for this?
After authentication, what will be sent to our backend from the mobile app is only the email of the user.
Hey Al Ryan, this seems like a faulty implementation of OAuth, what you get back from facebook is a token you send that token to your server, and it will send it back to facebook to verify it's not faked, then only user can be logged in.
Otherwise anyone can call the server with a email and act as that user.
This is a library with social auth and JWT support, see if this helps.
I'm also sharing solution from my project
Create a facebookAuth named graphql mutation
Above mutation will take two params access_token and access_verifier
Send a GET request to this url f"https://graph.facebook.com/me?fields=name,email&access_token={access_token}"
If json response has a key errors, stop user from logging in.
Otherwise above response will contain email, use it to create/get a User object.
Now you simply need to return the JWT token from your mutate function.
To generate access and refresh tokens call this function jwt_encode, imported as from dj_rest_auth.utils import jwt_encode
above will return tuple access_token, refresh_token
Note I have used dj_rest_auth instead of django-graphql-jwt, but it's pretty equivalent you just need a function to sign the JWT, rest all is custom logic so better write yourself.
PS: OAuth is a sensitive entry-point for attackers so implement is securely, you can contact at atul7555[at]gmail.com for any assistance.

Is saving user's id and login token in local storage a good idea?

I am developing Django + React project and I'm caught with this security approach concerning login and managing views for the logged in user.
I am using django-rest-framework or DRF for my RESTful API. And I'm using django-rest-knox for authenticating user logins since I am implementing Token-based authentication (instead of session-based which uses CSRF).
Question: Is it a good idea to save user's id and token in local storage?
Currently, I have a /auth/login/ API endpoint that handles the backend logic of logging in user and returns JSON response of login details upon successful login (including user id and token).
In my frontend, I use redux and redux-persist so the user's login details are kept even when the site is refreshed. The way redux-persist do it is that it saves the response in local storage. This means that the user id and token can be accessed and changed anytime thru dev tools.
If user will then make a POST request to an API that requires a Token authentication header, the frontend will look into that local storage for the token value to be supplied to the request header.
If user will then make a POST request to an API where the user id is required in the request data, the frontend will also look for the id in the local storage.
Localstorage is not safe, especially for storing tokens and ids. Any user can go to the browser's developer tools, see and also edit its contents, for example.
You could check on Django's sessions, so you can store data securely at server side and keep its contents associated with a specific user. There is a great tutorial at Mozilla that explains sessions in a clearer way than the official documentation.

Understanding the Client's Responsibilities in OAuth 2.0

I've been trying to learn the inner workings of OAuth 2.0 in my own RESTful app, and I can't seem to find any good explanation of how my Javascript client handles the process.
At this point, I have the client (an Angular 2 SPA) ask the user for their username and password (running Django Rest Framework along with Django Oauth Toolkit). The client makes an AJAX post to the server (specifically to /o/token), and using the resource owner password credentials flow is authenticated and receives the response with the token.
Now, assuming I'm doing everything correctly up to this point, I'm unsure how to properly handle the token from that point forward.
At this point, I'm having my Angular app save the token in a variable and attach the authorization header (with the token) to the calls made to the API. This works as far as granting the correct permissions, but im having a hard time understanding how to maintain persistence of the header (so if the user navigates to a different page, the token is still callable). Initially I stored it in a cookie, but I have concerns with security.
So, first, am I understanding all this correctly? What kind of security concerns should I take into account here? And, of course, how can I save the token on the client?
Yes, you need to store access tokens as user session data because they should be persistent. For example if user leaves your site and then reopens he expects to see himself logged in.
It will be better if you make your sessions server-side: user-agent will store only session ID and all user data will be in your database. User don't need his access token, only your application does.
Instructions for implementation of server-side sessions for Django look pretty simple:
If you want to use a database-backed session, you need to add 'django.contrib.sessions' to your INSTALLED_APPS setting.
Once you have configured your installation, run manage.py migrate to install the single database table that stores session data.

Secure authentication between ReactJS and Django

Been reading and watching quite a bit, and asking a lot of questions regarding ReactJS and Django.
This particularly helped me to understand the the flow of data from Django REST Framework to ReactJS and from ReactJS to Django REST Framework.
Django Forms and Authentication with Front-end Framework (AngularJS/ReactJS)
However, the one thing I am trying to understand is authentication to the Django REST Framework. I understand from the documentation that it has built in authentication. Since this is sensitive data, I would obviously want it protected people retrieving it just by going to http://www.my_site.com/info/api.
I would need to setup ReactJS to be the only thing that can request data from the API whether that is through a key or username/password credentials. I am just curious how this is handled? Obviously I don't want that hard coded in ReactJS because it will compile with the rest of ReactJS.
Here's how I'd approach it: I'd use a JSON Web Token (JWT) for authentication and authorization.
You'd use your back-end to protect ALL API requests from invalid JWT's except for routes where a user won't have a token (ie, registration/log-in pages).
Here's how the flow of the application will go:
A new user registers to your app with standard credentials such as email and password.
Your back-end will create a new user, sign a new JWT token (usually with the user's ID). You'll probably use a third-party library to sign/verify tokens (I don't have experience in the Django community but I am sure a quick Google search will give you answers). Your back-end will send back this token. This is the only time the back-end will receive email, passwords or any other sensitive information on registration.
From this point on React will only use this token for authorization. React will save this token somewhere (ie, localStorage) and send this token along with the other parts of a request to the API routes you created with your back-end. You'll send this token in the authorization headers in the request.
Your back-end will validate this token using a third-party library. If it's invalid the request stops and an unauthorized error is returned. If it's valid the request continues.
This achieves the following:
Your API routes are protected against unauthenticated users
Each request to your API is verified for authorized users which protects anyone from requesting any part of your API.
You can further solidify this by only allowing requests for users to modify their own data. For example, protect Suzy's profile from being modified by people other than herself by only allowing her token with her ID to modify her account/data.
Important Note- Your backend will never save these tokens in storage. It will verify the token on each request. Read more about JSON Web Tokens (JWT) and how it works.
Django Rest Framework has built-in token authentication and a third party package for JWT Token Auth.
If you the standard token auth would work for you, then it could be pretty simple with drf-redux-auth. If you need JWT for some reason, as suggested by Keith above, you could easily fork the above...

How do I implement form based login with mysql in a RESTful web service?

I am developing hybrid mobile Application using phonegap(jquery mobile framework) and jersey rest java webservice.
How to do login and logout using mysql and rest webservice and maintain session of perticular user on every page like traditional webapplication(get username on every page).
i am totally stuck.can anyone provide sample example or any solution.
you can do in below way.
create session table contains column [id, token, userid, loggedintime]
on login call a rest like /rest/user/login?username=uname&password=pwd
which return a token to user. maintain that token at client side. you may use cookie or sessionstorage whichever supported by mobile device.
now create one Filter with path /* so each request pass through it, and in filter check that the users token is valid or not, if not than redirect to login. you can explicitly pass that token to server in queryparam or pathparam.
on logout delete entry from session table, and redirect user to login page again.
there are many way to do this thing but this is a simpler way.
It's simple, you store the username and password in your client and send them with every request. (On the server side you can have an (username, password) -> (identity, permissions) in-memory cache which can make things faster.) You need a secure connection: HTTPS. Without that you won't do REST auth.
Login is simple you show a prompt to the user, in which she can give the username and password, so you can store them in the memory of the client. By logout you can simply close the client (by browsers navigate away), or remove the username and password from the memory of it. (It is not secure to permanently store the username and password without proper encryption on the client side.)