Can a server send to client both session token and session id? - session

Background:
I am performing some tests on an application which has a login feature. Client logs-in in the server, server sends it an authentication token and a user id. Client uses token and user id in next requests to authenticate itself.
I'm not much familiar with how such login sessions work. I'm confused about 1 thing that I need to confirm.
Question:
The way app is working is that both token and user id are sent in HTTP requests to retrieve sensitive data from server, but in some requests just user id is sent to retrieve sensitive data.
The confusion is, server needs to know that it is talking to an authenticated client. Servers usually verify it with session id or session token. When my client app is sending just "user id" then why is server responding to it, and giving it sensitive data...
In some apps, I have seen that both session id and user id have same value(separate entities but with same values), so probably in my app "user id" represents "session id". But why would server send both session token and session id...So, my question is
Can servers send both session token and session id, or they must(or mostly) send just one of them?
My main question is above one, following is a secondary question:
Are "session ids" and "user ids" usually same or different? If these are different, then is user id some session variable or something unrelated to session such as id of user in server DB?
P.S.: I'm not sure if it is the right site for this question. Let me know if it needs to be moved to some other stack exchange site.

To answer the question asked:
You may be confused about the role a session id plays. Session IDs and tokens are the same thing. A session id/token allows the server to perform some sort of look up which will indicate "requests with this session token are being performed by this user". So you don't need to send both the user id and the session token.
A little more information that you may not have asked for:
Session tokens do have some security concerns around them. They must be reasonably unique and should only be communicated over https. Also, remember that it is easy for a client to modify their cookies. So if a user id and a session token are sent, if the application blindly accepts the user id token then it may be possible for a user to log in, obtain a session token, and then change their user ID to some unfortunate user they wish to impersonate.
Now, perhaps you're thinking about authentication tokens? Session tokens can be thought of as a subset of authentications. They are predicated upon the server have a secret the client does not have access to. There's a few ways to do that, either create a reasonably unique value and store it with some extra information or perform some encryption of a value which only the server can decrypt.

Related

JSON web token vs session - how does authentication from multiple devises work in detail?

I have read a lot about json tokens vs session and still dont understand a few things.
benefit of using token is authentication across multiple devices.
Lets say user signs up on website, server generates session id, sends to client, client saves it in cookies or localstorage (so whenever user wants to log in again on website, client sends session id to server on each request, sever queries db and checks if its same id if yes sends response). Then same user, uses mobile app to log in, since session id is only stored inside computers browsers cookies/localstorage and not on mobile device or other computer, how would the log in from either different computer or mobile device happen?The server would send a different session id to each device the user logs in and then there is some sort of array stored on the server with ALL the users session ids?!
I also read that its much simpler with tokens as they are stateless. I just dont understand how that is relevant when it comes to multiple devices.
I read that for each request server checks using same signature as it used when it issued the token, if its valid. Client needs to send that token to server though with each request. So isnt that the same - different computer never stored the token inside cookies/localstorage so how would that work?!Would server need to create a different token? If thats the case, I dont get the difference and why session is less benefitial then tokens when it comes to multiple devices!
Also, I read: "Session cookies only work across a single domain, or on its subdomains. If they try to go to a third party, browsers tend to disable them....that wont happen with tokens". I dont understand what it means and how its related to multiple devices, also why cookies are relevant as json tokes ARE usually ALSO stored in cookies as well as session id?!
Sorry if its maybe too basic, I just read so much about that and just dont understand the basics.
there are some important differences between JWT and sessions.
Sessions are stored inside RAM of the server or a database to store where a user is or what he is doing. For example, you store the current page the user is working on.
BUT JWT is stateless. The server does not save the user state or his data to RAM or database. the server generates a key for the user including some important data for authentication(for example username, role, last access date) therefore the user must send his key with every request until his key expires and he must request for another one. Since the key only includes User Auth data, It can be used in every device(until it expires).
as you mentioned in mobile applications user gets multiple sessions so JWT mostly used in mobile or single-page applications. the user gets a key and state of user activity will be handled by mobile application.
Hope this helps.

OneLogin programmatic session cookie validation - No browser

I have the following scenario that I am curious if it is possible to implement. I need to use SSO and more specifically OneLogin to authenticate the user via custom UI from my Java standalone application. I know this can be done via Create Session Login Token and then Create session via token One Login API calls. With some parsing I can get the session cookie out of the last call and store it.
Now I need to programmatically hit the API server, which is to be build still and this server somehow needs to validate the session cookie that I am going to send along with request. The key word "Programatically" as in there will be no browser
OneLogin doesn't provide SDK to validate existing session cookie => it would be nice if I could, based on session cookie find out if it is still valid and what is the user name used for this session. If session is invalid API server would return unauthorized.
Is this even possible? Or is it possible in some other way?
Basically One Login is already used in our ecosystem and I have to continue using it
The app that will log user in and get the session cookie may not be the one calling the API server. This could be another java application that would receive the session
I guess what I am looking for is Validate Session equivalent from Open ID Connect API in general API
The session_token that is returned via that API has a short expiry is only intended to be used for making the Create Session request which returns session cookies.
It sounds like OpenId Connect might be the best option for this use case. If you have user credentials then you could use the Resource Owner Password Grant flow to authenticate the user and obtain an id_token.
The id_token is a JWT containing user details can then be verified for authenticity by checking its signature, audience and expiry claims. It can also hold other custom information about the user that may be used by your backend application.

Why do we need session , when we already have cookies?

I am new to web application , I am learning cookies and session, I understand HTTP is stateless protocol to make it stateful we use cookies at client side and session at server side.
When user requests a webpage it sends all the cookies available for that
browser on the PC.
If any one of the cookie matches with server side database , the server
shows the data , else sends set cookie with a session iD(optional to send
create session and send the session ID).
a. If server sends set cookie the client sends cookie in all respective
requests with the session id , only if the domain name matches with the
server to which the client sent .
Now my doubt is suppose I am working on an e-commerce site. And the server sends the number of items added to the cart till the user is not logging out , now it can be done using cookie alone why do we need session at all?
Is there something I am not understanding ?
These are separate concepts:
Cookie - Browser sends this with every request automatically
Header - Part of a HTTP request, the browser will only send data here if instructed.
Access token - Contains secret which may be a JWT (and identify the user) or a random set of characters
Session - a token bound to a user + device that authenticates the user. If the user doesn't have an access token, they can use the session to get a new token.
You can see that Cookie/Header are the where and access token/session token are the what.
The user needs to authenticate in your service. That means you need to be able to identify the user. That may be done with a JWT, session token, IP address, a signature, etc... And that is separate from how this data is transmitted to the service from the user.
So when you say why do you I need session when the user has cookies, these are totally unrelated. The session id may be saved in a cookie, that's just one option.
Whether or not the session id in a cookie corresponds to actual data on the server side is another completely separate question. Should the session token be a encrypted (or signed) object, like a JWT which contains user identifying information, or should that data be saved in a server side DB, and only transmit a random-string identifier. Who knows?
The answer is going to be based on what's critical for your application. Generally speaking, session tracking on the server side is a legacy concept, and the new hotness (which is old now), is to make the sessionId a JWT saved a HTTP Only cookie for security. And then passed on every request.
Lot's of services have sessions and access token management baked in, and for a working example and more about tokens, check out any one of many knowledge bases.
Because:
There may be, and probably is, sensitive data in that session, e.g. the user's id, identifying who the user is. If you just stored the user's id in a cookie, the user could manipulate it and easily pose as anyone else. There are of course ways to mitigate that, but simply not allowing the user to futz with the cookie contents (because it's just a meaningless session id) is the simplest.
It allows the server to manage session state; e.g. if a user suspects somebody is logged in as them on another device, they can invalidate all other sessions ("log me out everywhere" functionality).
You may be storing a lot of data, and sending it back and forth in a cookie on every request can become rather wasteful.
You may want to associate something like a shopping basket with the user's account, not just the user's browser, so when they log in on another device their shopping cart is following them around.
Yes, there are also perfectly fine cases were storing information just in a cookie is fine and preferable, especially since that allows you to scale your server more easily to a cluster of servers without having to worry about where the session information is stored. It depends on what information exactly you are storing.
The usual pattern is
the cookie contains only a unique session identifier (but no useful information itself)
the session storage (server-side) contains the associated data for this session. This can be a) very big and b) hidden from the user/browser and c) trustworthy (because the user cannot just modify it in the browser)
It is preferred to use sessions because the actual values are hidden from the client, and you control when the data expires and becomes invalid. If it was all based on cookies, a user (or hacker) could manipulate their cookie data and then play requests to your site.

What will be returned to identify user by server if username can be same?

I'm new to server developing,and there is a question:
when user logins,what will be returned by server to identify the user so that when user next logins they needn't to input username and password again,and what will be saved in server to record state of users,saved in memory or database.And will the solution will be different among mobile app and website?
I'm confused about this,anyone can teach me,thanks!
There exist many authentication mechanisms with different properties to authenticate a client to a server.
The easiest one is with Sessions and I suggest you to start with it. The basic idea is that when a user succesfully login, the server generates a big unique random number (usually with an expiration time) and send it back to the user. Both client and server store this value somewhere. Next time the user performs a request, it sends back the session id and in this way the server knows it is the user that previously logged in. This mechanism is supported in almost every language and you can handle it very easily.
Another interesting authentication mechanism is called JWT (Json Web Token). In this case the server generates a self-contained token that user uses for future requests. In this case the server doesn't have to store the token because the needed information is embedded in the token itself. You can find all the necessary information and resources here: https://jwt.io/ .
There are also other standards to perform authentication that are slightly more complicated. One of the most popular is OAuth (https://en.wikipedia.org/wiki/OAuth).
When user sends his username/password, generate a session token. Then, store that token at the client side (as a cookie if using a browser for example). On the server side, you can save it in presistent store (database) if you need to keep it for long time, or in memory (user session).
Afterwards, the user needs to send that token to identify himself instead of re-sending his username/password each time. The session token can be sent in several ways; through cookies, Authorization header, post body, etc.
Also, consider sending the session token through a secure connection (https) for security concern, and check for session expiry as well.
You have to use session storage.
An example, in common page :
<?php
session_start();
if(!isset($_SESSION)) {
//Redirection to login page
header('Location: loginPage.php');
} else {
//User is log
var_dump($_SESSION);
}
And in login page :
<?php
session_start();
//Your query for verifing is username and password matched
$isMatched = true;
if($isMatched) {
$_SESSION['userId'] = 45687; //Id of the user
//You can save what you want in this session
}
And on every page you can retrieve the data save with $_SESSION['theValueYouSet']

How to persist session data in an AngularJS application?

I have this web app written in AngularJs that uses cookies to authenticate the requests in a REST API.
Once the user logs in, the cookie is received and saved in the browser and all subsequent requests send the cookie along to the server. There is a 'User' service/object that saves the isLoggedIn and username values (for UI display/flow). Now, if I refresh the 'index' page, the app restarts. This means that my 'User' object will be cleared. I can check the existence of the cookie and, if it exists, I can re-set the User.isLoggeIn as true and go from there, but I still need to get the username, id, etc. So, my question is: should I create some sort of 'ping' endpoint in the API to verify if a cookie is valid? And if so, the API would send me back the user id and username... OR should I persist the user data in LocalStorage (or some similar cross-browser thing) and just assume the user is logged if the cookie exists? Any other subsequent requests to pages that need authentication would be automatically verified. So, this question really only applies to the scenario where the user refreshes the index page - hence, restarting the web app. I want to know the user data because I want to show a 'user homepage' instead of the 'public homepage'.
What do you think?
You should depend on the server for this. Creating something like GetCurrentUser method on the server. If the user is logged on this returns all the properties of the user.
You should even use this server api to get the user data after authentication completes. So the authentication become two step process first the user is authenticated, on success another call is made to server to get current users details.
Using client side local storage for this would not be ideal because you need to do lot of book keeping, in terms of cleaning the logged in user on log out or session expiration.
Also cookies from server would have expiration times an all, and making decision just based on cookie existing on local storage may not be optimal approach.

Resources