How authorize web application and manage sessions - express

I am building a single page react app that uses redux as state manager and an express node js as backend server, but I don't know what is the best way to authorize my users in the application!
If it was a php or express-js website, I could use PHPSESSION or express-session to manage users sessions data but now the single page web application is separated from the backend and I can't manage sessions like before!
My idea is to make a session id for each new web request, then save it for client in local storage, then in the server store all needed informations in a database and when application have an API call, send that id in request header. Then we can check authorizations by using that implemented session.
But I thought if there was a simpler way to handle this problem that has no need to make a session implementation by myself.
(I don't want to use third party services like firebase or okta or save all session data in client part like JWT.)

At the end i implemented a custom session manager ( SessionMush ) so the client send a request to server and get a token id then use it to access its session in server.
Each session should be accessible by an identification token ( here knows as sid ) so the application can save that token to access and use that session. A server side state for your application can be use for saving clients auth state or any temporarily data about clients that you want to use them on server side so in your application you will save that identification token and then with each request you will send it in http headers then the server will know who you are and what was you did before on the application based on that saved session data in database (server side state for that id) so it can serve the needed information for you based on the client identity and it's state on the server. It created to be used as a express middleware and mongodb as data store.
When your application have no session and it loaded for the first time it sends a request to the server to gain an identity for itself When the request received to the server, server analyze the request and it'll find out that there is not exist any session id (sid) so it will make a new one for this request and add it to response header part so when the server decide to send the response it will send that created session informations too. The client should save that informations to use that session for its other requests. it can send that id in the request header part to show its identification. A session can be expire too when it doesn't used for a threshold time. so when the server get wrong or expired session it will behave to it like a request without any session so it will create a session for that request and send its informations like what we explained before.

Related

State parameter in OAuth2.0 code flow server-side

I have a scenario where I need to implement OAuth 2.0 authorization code flow on the server side - the user authorizes a backend service against Microsoft, the service receives a token, saves it in a database and uses it to perform daily background jobs on the user's data. The token itself is neither needed nor received in the frontend app.
The backend service is an asp.net 5 app with an api and a hosted service. The frontend app only does the initial request to the api, which results in a redirect to Microsoft. The oauth callback url is pointed to the api endpoint which receives the code, gets a token and redirects to the frontend app upon success/failure.
The question is, how to implement state parameter against CSRF attacks in this scenario? E.g. to prevent someone posting some else's code to the callback endpoint. In the usual code flow, the frontend app would generate a state parameter and store it in local storage (described here), and compare it in the redirect upon returning to the frontend app.
In my case it is the api that needs to generate a state parameter, store it and check it in the callback url. I don't have a user session and the api is load balanced, so I need an external storage, but the solution should be similar. My plan was:
In the endpoint that redirects to oauth2 login, generate a guid that acts as the state,
Store it in a DistributedCache as the key with the value of some extra user data (id, name, etc) that the endpoint receives,
Pass the guid in the state query parameter (?state=asd123) to the redirect url,
In the callback endpoint retrieve the state and check whether such a key exists in the cache,
If it is, the request is valid and I can use the extra data attached to the key.
All the tutorials I could find deal with the frontend app and local storage, so my idea feels hackish and I wouldn't want to risk when it comes to security by implementing some random algorithms. Do I need to pass that extra user data in state or is it fine to rely on it being present in the cache if the request is valid? Is there a more standard secure way of doing this?
Here is a sequence diagram of the described login flow in case it is helpful:

SSO: is it OK to cache the SSO token for some time and thus not contact the auth server on every request?

For single sign on (SSO) I have a single auth server (with user table) and multiple resource server (various web applications).
So far I have implemented JWT using Oauth 2.0 and got the access token from the auth server.
I understand from the OAuth 2.0 spec that the resource server now have to communicate with the Auth server to validate the token. Which is simple and can be done by just sending GET request to auth server at the endpoint users/me to get the user object along with other user scope.
Now coming to my point is the frequency of the Auth server call from the resource server. Calling auth server for each incoming request to resource server is not efficient and will create slowness because of the extra round trip.
How often should resource server communicate with the auth server? If not on each request then how do I persist the auth information?
I was thinking of using session on resource server but I am not sure if that is correct way to go.
If your access token contains expiry time, then you can restrict consecutive requests to your resource server for that much time. You can cache access token once obtain and other requests first lookup in cache, also you can periodically check whether access token is still valid or not.

Is it nessesarry to send credentials on every single request to MVC Web Api?

I am about to create my first restfull web service where i chose MVC WEB API to be the "provider". After reading about authentication i am a little confused.
My requirements is that on call to any url of webservice i want client to be authenticated, except sign in url.
I understand the flow this way: after client is signed, webservice returns a authenticationtoken which client have to store, and send to the server on every request in the headers. But where is this token stored on the webservice?
I am very confused at which flow of actions i have to implement if i want to avoid users to pass login parameters on every single request.
Typically how this works is that the user's authentication token will be stored in a cookie. Once you authenticate the user, you will create a 'session' for them server side. There will be a 'session token' that corresponds with this session.
When the user signs in, you will create a new session for them. This will send them a new cookie. Every future request they make will contain this cookie. You will then use this cookie to identify the user's session. From it, you can draw their username, etc.
It sounds like what you really want is the .net State management (https://msdn.microsoft.com/en-us/library/75x4ha6s(v=vs.140).aspx). You should look into using this, and see how you can apply it to your current needs.
In the long run, once you've got proper user session tokens, you will not need to send their credentials with every request. The session token will be good enough to identity the user upon every request that they make.

Backbone & REST API : Session Handling

I am in the midst of planning a saas app and have been stuck trying to figure out how I want to handle my session management. Here's the scenario:
Server 1: REST API, Rails 4 w/ rails-api gem
Server 2: Front-end, Rails 4, BackboneJS/MarionetteJS
These servers, eventually, will be part of a cluster of similar servers.
The applications are separate because there will also be a mobile app using the REST API and we plan on having 3rd party applications tie into our database via the API.
I've boiled it down to 2 scenarios:
1) Use access_tokens only for authentication on the front-end:
User logs in and sends over email and password over https
They are authenticated via the api and it returns an access_token
All future requests made on the front-end use this access token
2) User database sessions on the front-end and then access_tokens for api calls
User logs in and is authenticated via devise on the frontend server (storing session info in the DB)
An access_token is generated for them and added to the Backbone app initialization for future api requests
I favor #2 simply because every time the user changes the page, I can easily see if they are still authenticated and if not, boot them back to the login page.
But #1 keeps things easy in the sense that the frontend server deals with just that: the frontend stuff.
Does any suggest one method over another? Why?
Does anyone have any other alternatives?
Thanks all!
You're reinventing the wheel by doing using an access_token. Devise already generates a cookie and sends it back when signing in. Just parse this cookie out when the client logs in:
User logs in with backbone app (post request is sent to API server)
Devise does it's thing and authenticates the user, generates the session_id and sends it back in an HTTP Set-cookie header.
backbone app parses the cookie out and caches the session_id value (think of this as your access_token)
each subsequent api call sends the cookie value in an HTTP Cookies header as session_id=cookie-value-here
Note your session cookie name is custom to your app and can be configured in an initializer via:
# /config/initializers/session_store.rb
YourRailsApp:Application.config.session_store :cookie_store, :key => '_your_rails_app_session'

REST API authentication - Will this be sufficient?

I have been trying to wrap my brain around authentication on a REST API.
I've tried to think of a way to successfully authenticate users, keeping in mind that users can access all data on the client, and I've come up with this idea.
Client sends username and password to the server
Server checks if they match a user.
If it does, we create a hashed string with user_id+e-mail+currentTime+salt
and stores this in a database-table with an expiration date.
Server returns hashed string to client
Client sends random request to server including key
Server checks if key is correct and if it's expired
Is this a proper way to do it, and do you see any security flaws?
You're effectively storing session state on the server, which is something you shouldn't be doing on a RESTful API.
Authentication on a RESTful API should simply follow whatever is the standardized authentication method for the underlying protocol. Instead of reinventing HTTP authentication, you should simply require clients to authenticate through HTTP Basic Auth on every request, using the Authorization header. Obviously, all your client-server interactions should be done over SSL.
If you really need some authentication token with an expire date, you can have a resource that provides it once the client is authenticated with basic (like a signed timestamp) but clients should still send that in the Authorization header, with a custom realm, and no state should be stored on the server.