I have one website, where a user will login to his/her account, they will then be redirected to another website where they should be logged in automatically. Both website have access to the same database. A user will get authenticated with a token, but how do I pass that along to the other website.
Depending on the server technology there are various choices.
You don't tell what platform (windows, linux) is your server on and what web server (Apache, IIS) you use, which web technology you use (ASP.NET, PHP, Ruby, node.js) or framework you use (laravel, symfony, wordpress, ruby on rails). So it's pretty difficult to be precise.
Anyways.
For example on IIS you can choose to store session state in these ways:
InProc mode, which stores session state in memory on the Web server. This is the default.
SQLServer mode stores session state in a SQL Server database. This ensures that session state is preserved if the Web application is restarted and also makes session state available to multiple Web servers in a Web farm.
more...
For Apache/PHP running on Linux you can rsync the session folder across machines, or store the session state on the database.
As a last resort you can have a protected websocket that connects the web servers and allows both to query the other about session tokens.
what should be clear is that the session ID available to the client (cookie, local storage or whatever) is NOT the session state used by the webserver. Those are two different things.
What you want is called SSO (Single Sign-On).
To be clear: you have to move information directly between the servers without the aid of the client. This is important for security reasons and should not be confused with the session ID available to the client.
Furthermore, there's the problem of cross-domain. This only applies if the domains (URLs) of the two servers are different. For security reasons you cannot send cookies of one domain to the other. Or access the local storage of another domain from a page that has been loaded on the other. In other words, when you set the session ID in a cookie or local storage under one domain, it won't be accessible on the other domain.
But there's a way around the domain boundary, shown below.
In your case the database is probably the best option. You can do as follows.
on login on either side you store the session ID and a timestamp in a SQL table that points to both user's login data (one for the first server, the other for the second -- just in case you use heterogenous web technologies such as ASP.NET and PHP);
when you redirect the client from one domain (server) to the other, you have to ensure the session ID is passed along (without cookies or local storage) -- you can do that easily by putting the session ID into the query string of the URL, such as this:
www.otherdomain.com/landing_page.html?sid=75UFNE784324jEJIRO4234782394JKR
on the landing page of the other server you can now take that session ID, query it against the SQL table and retrieve the login information for that server.
I hope this helps you out a bit, it's maybe a bit confusing because it's a generic explanation without concrete code. But with a bit of attention you should be able to do it!
Related
I'm developing an app in React and Spring Boot + Spring Security. Right now, I've added HTTP Basic Auth for user authentication. The user inputs username and password in a login form, and I send them (of course over HTTPS) to my backend. If the user is authenticated, I send back success, and the frontend saves the credentials into local storage for future requests (i.e. no session server-side). Then whenever I navigate to a "secured" route in React, I check the local storage, and then use the credentials for my secured requests. When the user needs to logout, the app removes the credentials from local storage.
It's a very trivial security implementation, but unless I have XSS vulnerability, or there is downgrade to HTTP (for my domain, not possible - HSTS preloading), I don't think it's vulnerable. But the main problem I see with it is that I can't for example logout users remotely, which might come in handy at some point. Have I found myself in a dead-end? Is HTTP Basic Auth just not meant for stateless authentication with SPAs?
First, I would suggest not doing that. As you said, a downgrade to HTTP will expose credentials and a XSS vulnerability will make it possible for the attacker to steal the credentials of your users.
However, if you insist to store credentials in localStorage then you should ensure several things:
Credentials should be encrypted in localStorage, and your application (server side) will decrypt them and only then "use the credentials for your secured requests".
This way, a downgrade to HTTP will expose the traffic but the credentials are transferred after encryption.
Be extra-sensitive for XSS vulnerabilities and sanitize any user input (best practice regardless, but now the stakes are high). Stealing a session is different from stealing users' credentials where an attacker can steal all of your users' passwords over time, and execute a massive attack coming as legitimate requests from your users. This is in contrast to sessions with a timeout.
The localStorage is only accessible via scripts coming in through your own domain, so you're safe as long as the only frontend code running is your own.
But if any other code is executed, via injection or if you share the domain with someone else, they will be able to access the localStorage data.
For the second part of your question, logging out users remotely. You can implement it in a different way:
Upon a successful login, generate a completely random string unrelated to user credentials and store that in the database, along with an expiry date. Then, pass that string to be stored in localStorage.
From then on, so long as that local storage credential matches the database one and the timeout has not expired, you automatically consider them logged in.
This way, there is no risk concerning the exposure of the user's credentials from localStorage. However, with this temporary unique string essentially functioning as a sessionID, you will still to need to be aware of and take precautions against the risks associated with session hijacking.
Now, to end a user's session remotely, you can update the expiry date of that entry in the DB.
My NodeJS application is authenticating users via third-party app. Once the app gets the user data, a cookie is being created and sent to the client and then react is reading user data from that Cookie.
Is cookie better/worse than Web tokens? AFAIK No diff but i want to be sure.
Is there a better implementation?
Can a user modifies req.session info, or that stay in the backend(Node)?
Choosing between cookie and token-based approaches really depends on your use case. When using cookies, session id's are stored in the database. Therefore, with each request back-end will need to perform a database search to check if provided id is present. Using tokens, server only needs to process successful login requests and verify token's validity, which does not require a lot of resources and scales really well. Additionally, with tokens you may use your API outside the browser environment (cookies support is often very limited on other platforms).
If these points are not critical for your application, there is nothing wrong with using cookie-based authentication.
Good luck!
Quick Question: When you login to your account on a website what does it do to keep you logged in so you don't login again and again when you visit another page?
Cookies and Session are some of the traditional ways that authentication details are stored in browser. However through these approaches server has to keep track of logged in users and their cookies to validate. So there is some server operation in managing logged in users. However there's a new approach known as JSON Web Token aka JWT. Here server will generate an user specific token and sends into browser client on logging moment. Browser will store this token in HTML5 Local Storage or Session Storage and will be sending this token with every request! So here for every refresh browser code can check for the availability of this token in Local Storage or Session Storage. Advantage of this approach is that the server doesn't have to keep track of issued token and is able to extract data from token if needed. This JWT is widely used in authenticating Web applications developed using advanced Javascript frameworks : Angularjs or Reactjs(with supporting libraries)
Browsers will keep you logged in by using some sort of browser storage. (for example cookies or localStorage or...). This data is called session data.
Html pages are stateless, that means when you refresh a page, all data that came from the server previously, are removed, and have to be requested again.
Now to request a protected page, there has to be a way to tell the server that you are the user that is logged-in a few minutes ago! This is done by storing some encrypted data in browser, usually in cookies.
Browsers are designed in a way that automatically send a specific page's all cookies to server when the page is opened. Server has the exact encrypted data in files or database and compares it with browsers data. if they match, server will allow protected content to get viewed by user, so will send the requested content as response.
you can simply test this by clearing your browser cache after login and then refresh, you will see that you are logged out, and not allowed to see protected page.
It is all about sessions.
Source
In computer science, in particular networking, a session is a
semi-permanent interactive information interchange, also known as a
dialogue, a conversation or a meeting, between two or more
communicating devices, or between a computer and user
Web server session management
...
Hypertext Transfer Protocol (HTTP) is stateless: a client computer
running a web browser must establish a new Transmission Control
Protocol (TCP) network connection to the web server with each new HTTP
GET or POST request. The web server, therefore, cannot rely on an
established TCP network connection for longer than a single HTTP GET
or POST operation. Session management is the technique used by the web
developer to make the stateless HTTP protocol support session state.
For example, once a user has been authenticated to the web server, the
user's next HTTP request (GET or POST) should not cause the web server
to ask for the user's account and password again. For a discussion of
the methods used to accomplish this see HTTP cookie and Session ID
In situations where multiple web servers must share knowledge of
session state (as is typical in a cluster environment) session
information must be shared between the cluster nodes that are running
web server software. Methods for sharing session state between nodes
in a cluster include: multicasting session information to member nodes
(see JGroups for one example of this technique), sharing session
information with a partner node using distributed shared memory or
memory virtualization, sharing session information between nodes using
network sockets, storing session information on a shared file system
such as a distributed file system or a global file system, or storing
the session information outside the cluster in a database.
If session information is considered transient, volatile data that is
not required for non-repudiation of transactions and does not contain
data that is subject to compliance auditing then any method of storing session information
can be used. However, if session information is subject to audit
compliance, consideration should be given to the method used for
session storage, replication, and clustering.
In a service-oriented architecture, Simple Object Access Protocol or
SOAP messages constructed with Extensible Markup Language (XML)
messages can be used by consumer applications to cause web servers to
create sessions.
In raw php (most well known frameworks has session management middleware, so you shouldn't worry about it) if you want to manage a session, you have to include
session_start();
procedure on top of your pages. When you do this, you are creating a 24 minutes (1440 seconds) session (by default).
You can modify it to any integer from your php.ini file.
All session data in php stored in $_SESSION global. Hence, it is an array, so you can set session variables (aanything you want) like,
$_SESSION['user_name'] = 'ernesto';
$_SESSION['foo'] = 'bar';
...
At any time of your application, you can remove $_SESSION variables,
session_unset();
Assume, you've already set variables above,
print_r($_SESSION);
will print empty array as you've removed variables by unset procedure.
If you want completely to destroy a session,
session_destroy();
will do it for you.
use cookie you can learn: Cookie or Session you can learn Session
I have an application to which I log in using using javascript. After being authenticated, the server sends me a token, which I have to append to each ajax requests I make to the server so that the server knows that I am eligible to ask for information. However, my application is not single-page application which means that after clicking on links, the page gets reloaded and I need to re-authenticate.
Is it possible to safely save the token and access it again after page reload?
The options I have thought of are saving it in cookie or in local/session storage, however, I'm not sure whether these are safe enough.
Do you know of any other, safer way to save the token on client side? Or perhaps do you know whether the options I mentioned are safe enough to store such a sensitive information?
Thanks for any suggestion.
Edit: I can't change the server-side application, the token must be stored on the client.
Local Storage: is not the safer way to keep confidential/sensitive information.
Cookies: Well there is a lot written about stealing cookies and preventing Cross Site Scripting.
Session Storage: is safe but the question is which technology you are using on the server side.
Is it NodeJS or PHP or anything else??
I have used NodeJS and PHP both for authentication.
With Express.js you can maintain a session for each user and check/authenticate on every request/page load and validate whether it is a valid user/request or not.
And it also provides an active session check i.e, If a user is inactive for sometimes the session will be automatically destroyed/cleared/cleaned.
In addition with passport.js you can also implement this but it depends on your requirements.
Check this LINK
When you think the token is confidential then you should not think about saving it in client side.
Even if you are in a situation where you want to save such a confidential info in client side then the same what you mentioned is correct(Cookie,Local/session storage). Encrypt your token before save.
Local storage:
It is saving data under your domain. No other domain don't have access local storage information of your information.
Please correct me if I am wrong, accept it if I am correct.
I am trying to understand cookies and sessions professionally.
I know that when a browser connects to a server, the server "asks" the browser to "paste" a cookie with "phpsessid" in the client browser cookies folder.
Now that we have the "phpsessid", if the client enters the server the browser sends to the server the "phpsessid" and the server takes a look at the tmp folder and if we have a match it loads back every data the user has for this client, but I am kinda confused with the process.
I will be thankful if some one can help me understand those processes of creating a session and cookies - what is happening behind the scenes.
Let's go through this:
Cookies and sessions are both ways to preserve the application's state between different requests the browser makes. It's thanks to them that, for instance, you don't need to log in every time you request a page on StackOverflow.
Cookies
Cookies are small bits of data, (maximum of 4KB long), which hold data in a key=value pairs:
name=value; name2=value2
These are set either by JavaScript, or via the server using an HTTP header.
Cookies have an expiry datetime set, example using HTTP headers:
Set-Cookie: name2=value2; Expires=Wed, 19 Jun 2021 10:18:14 GMT
Which would cause the browser to set a cookie named name2 with a value of value2, which would expire in about 9 years.
Cookies are considered highly insecure because the user can easily manipulate their content. That's why you should always validate cookie data. Don't assume what you get from a cookie is necessarily what you expect.
Cookies are usually used to preserve login state, where a username and a special hash are sent from the browser, and the server checks them against the database to approve access.
Cookies are also often used in sessions creation.
Sessions
Sessions are slightly different. Each user gets a session ID, which is sent back to the server for validation either by cookie or by GET variable.
Sessions are usually short-lived, which makes them ideal in saving temporary state between applications. Sessions also expire once the user closes the browser.
Sessions are considered more secure than cookies because the variables themselves are kept on the server. Here's how it works:
Server opens a session (sets a cookie via HTTP header)
Server sets a session variable.
Client changes page
Client sends all cookies, along with the session ID from step 1.
Server reads session ID from cookie.
Server matches session ID from a list in a database (or memory etc).
Server finds a match, reads variables which are now available on $_SESSION superglobal.
If PHP does not find a match, it will start a new session, and repeat the steps from 1-7.
You can store sensitive information on a session because it is kept on the server, but be aware that the session ID can still be stolen if the user, let's say, logged in over an insecure WiFi. (An attacker can sniff the cookies, and set it as its own, he won't see the variables themselves, but the server will identify the attacker as the user).
That's the gist of it. You can learn more on the PHP manual on both subjects.