How to prevent user login from multiple devices in Django REST? - reactjs

I am working on a subscription based platform, where user buys a subscription plan and then he/she can get access to the content.
Tech Stack: React in Frontend and Django REST Framework in Backend
I want to find a way to prevent user login from multiple devices or multiple tabs from a browser. There should be one session per user.
I have researched about it but could not find anything suitable. Some are using session authentication scheme to store the user session and adding middlewares and prevent multiple logins.
But i am using JWT token Authentication scheme. I am storing JWT token in front end.
How should i implement in such case which not having session authentication? Any leads?

Related

Authentication and Authorization in React app

In a .NET app I can add authentication and authorization using web.config and/or IIS. I can also use [Authorize (Roles = "RoleABC")] in a MVC app's controller or action. And even extend the AuthorizationAttribute
I'm looking into creating a React app for intranet use, and reading these tutorials (ReactJS and MS), but can't find authentication/authorization details.
Even though the app will be Single Page App, I still would like to authenticate and authorize users for certain options within the app, just like I can do in MVC app.
Is the only option to do that way is creating Blazor app instead?
For authentication and authorization, you should use auth tokens (like JWT). Your backend should create an auth token when a client logs in to the system and sends it to the client. Your server also should send the authenticated user information to the client (react app) so that you can render correct pages according to the user type. For example, you can render the admin page for an admin type of user, and the guest page for a guest type of user. You can save this user data as JSON in Redux. Hence you can access the user data from any component of your react. Also, in your backend, you must restrict the endpoints according to the auth token which is sent by the client. In the backend of my app, I follow the below steps:
Authentication check -> Authorization check -> controller (endpoint) -> result
React isn't opinionated on this, so it's up to you to design the implementation. A basic way to do this is:
Log in and obtain an authorized JWT token from the backend and include the account ID when you sign it
Store the JWT token in localStorage, store the account info in Redux
Conditionally limit routes based on account info (ie. admin group) on the front end
Have every auth-required API call include the JWT token in the x-auth-token header, then on the backend use middleware to check if it's still valid. You can then also decode the account ID in order to check its privileges so that you can limit API access
This may be helpful: https://medium.com/#faizanv/authentication-for-your-react-and-express-application-w-json-web-tokens-923515826e0#5f52
Not sure whether you still need this - I personally feel we should have something bridging the authZ gap between server and client to make it easy. So I spent a few days on a github project for this purpose, here it is: authzyin.
What I tried to do is to leverage policy based authorization from asp.net core - which I think it's very cool - and automatically bring the same definition to the client to use in React via hooks.
For authentication I am using msal.js against AAD - so authN is done on the client and jwt bearer token auth is used for all requests.
It has a client lib and a server lib which can be used together or separately. Of course it might still be lacking some features - please feel free to take it as a reference (contribution is also welcome).

Angular/NodeJs Webapp, JWT Auth or Session Auth?

For a webapp which kind of Auth? Pros/Cons?
The app should be a webapp for FE we plan to use Angular, for BE we plan to use NodeJS.
The app will have public routes and private routes depending by role of user, and we plan to develop also an Android and iOS app too.
I see there are two approaches:
JSON Web Token
Session
I read some post that did not recommend the JWT instead of Session.
some consideration:
JWT
cons
needs a server side check for invalidate some token (so the approach are not stateles)
user information: if I put them inside the payload could generate an heavy headers and, if user information change (i.e. role) I need to change the token (and invalidate the previous). If I use only User ID inside Payload I have to load everytime from DB or cache system (i.e. Redis).
pro
API with JWT Auth seems easy to be used via web or native mobile app
Session (i.e. Express Session with Redis)
cons
session set a cookie with the session ID, it seems to be difficult to use this approach in mobile native app.
Could you confirm or add other pros/cons and suggest the best approach?
Using Socket.io (With server session/cache) instead REST API could be a valid alternative to the previous approaches?

Why is token based authentication better for Single Page Applications?

Okay so this might be a very rookie-ish or naive question but I tried searching the internet and have resorted to stack overflow only after not finding anything fruitful. I have been reading about Token based authentication as well as Cookie based authentication. I have come across the opinion that token based authentication is better for Single page web applications but cannot clearly understand why. I will be using nodejs and angularjs to accomplish the same.
I guess that with Token based authentication as well as Cookie based authentication you mean Token authentication vs Session authentication because a token can be stored in a cookie
See this
With session based authentication the server maintains a sessions per each connected user. Client authenticates with its credentials and receives a session_id (which can be stored in a cookie) and attaches this to every subsequent outgoing request. So this could be considered a "token" as it is the equivalent of a set of credentials. This approach requires heavy server resources
Token based authentication is stateless and does not require server storage because the issued token (mainly JWT is used) contains the relevant user info and is signed with the server private key, so it is non-falsifiable. The token is stored in client side (cookie, localStorage, etc), attached to every request and validated by the server. Tokens are also suitable for REST APIs that do not require to maintain the state between each request
Forms based applications use session based authentication, and SPA often use token based authentication by the inherent advantages.
Note also that a SPA with session based authentication only will attach cookies to the outgoing request if the applicacion is located in the same domain that the server
SPAs tend to have many faces: the logged in view, the logged out view, or the restricted view. It’s all about access control. Your users are all getting the same app but they may not have the same levels of access. You’ll find yourself building access control logic for your front end and your back end.
Because tokens contain all this information, they are very portable: they can be used by your UI and your backend to make decisions. You can share them with partner services as a means of building Single Sign On services that delegate users to the correct application.
Hope this link will give you more information..
Token Based Authentication for Single Page Apps (SPAs)

Returning Permissions From Web Api to AngularJs client

I am building an application with a set of user types. I have a .Net MVC 5 Web Api web service and an angularjs SPA. I would like to have my SPA display pages relative to the user type logged in. I am authenticating with bearer tokens which I then store in localStorage.
I have thought of making web api, return the token with the user's claims and roles, I can then use this information to decide what pages to display to the user, however, I worry that the user can easily alter this information.
Could you please advise how I can achieve this without introducing a security exploit.
Thanks in advance.
In the server side which is your controller, you should add some authorization filter. Resolve the token to the requesting user and verify authorization. Implement some caching so you are not querying the database (or some user store) each time. You don't have control on the client-side. They can alter however they want in the display and compose their request. So that is why it is important to put these authentication/authorization in each request.

What is the best way of authenticating an user in an angular application with .net web API?

There are 2 ways for storing authenticated users details & send the same for each web API call.
Save in Cookie.
Save in Local Storage.
In my case, user details will be used in my Web API & I just need a few(around 4 values) details of user. So for me storing user details in browser is suitable. But, no matter if I am using Local storage or Cookie storage, end user can see userDetails (like UserID, tenantID etc. which are values in my DB). So there is a security issue.
To overcome this security issue, if I will use some angular encoding-decoding algorithm, my application will be slow. Is there any work around?
I am using Web API 2 with Owin. It uses a token based authentication and works pretty well, here is the link for my implementation they follow best practices:
http://bitoftech.net/2014/06/01/token-based-authentication-asp-net-web-api-2-owin-asp-net-identity/
You use a bearer auth token that is sent through to client and api to verify the users. You can also have stuff like refresh tokens for additional layers of security using the interceptor services in your angular app. So the benefit of this is, is that you do not need to store your usernames / hashed passwords etc. using local storage or cookies but only the auth token and this is then sent through to the API to verify the current user.

Resources