SAML2.0 Authentication with Node.js and SPA - node.js

I've been scratching my head for about 2 days on how to solve what seemed to be a simple task, but it's starting to drive me crazy.
I have an application where users will use SAML 2.0 to authenticate.
I have a react-application set up for the front-end, and was thinking I was gonna use JWT to secure the rest-api communication between front-end and backend.
When a user signs in, the flow is the following:
User accesses www.server.com/ and gets served the static HTML with react-application
User clicks 'Sign in' and accesses www.server.com/login
passport-saml redirects user to saml identity provider. User logs in.
User calls back to www.server.com/callback with a SamlResponse in the req.body which is decoded by passport-saml and put into req.user.
If the user doesn't already exist, I create the user in the database.
I create a JWT.
What should I do next? The problem is that the user is not in the react-application when calling back from the identity provider, so I've lost all state in the application, so whatever I reply with will get sent to the browser.
Is there any way I could force the browser to give me the SamlResponse which the identityprovider is calling back with? Then I could send it to the server as a http-request from the react-application.

After some thinking, I came up with the following solution which worked quite nicely for me.
SAML has something called RelayState which is a property that the Service Provider has to respond with. So now the process looks like this:
User accesses http://frontendserver.com and gets server the static page with the React application (not signed in.).
User clicks 'Login' and gets redirected to http://backendserver.com/login/?RelayState=http://frontendserver.com which authenticates via passport-saml and redirects user to SP. So I pass the origin of the request in RelayState.
User calls back to http://backendserver.com/callback with the SamlResponse, which includes the RelayState.
I create a token, and redirect the user to RelayState/#token.
I can then parse the url in the React application, and add the token as a header for any further requests.
This might've seemed like the obvious way to do it, but it took me quite a while to figure out that this would work.

I know this question is for Node backend, but I found an article of the implementation for a PHP/Apache webserver backend here and I think it can help someone trying to understand the flow of the process of how this type of thing works.

Related

Can anyone outside use my api to make requests?

I am currently learning full stack dev, and have made a simple application with React on the front end, and set up a very simple REST api on my express web server that handles certain routes.
For example api/users returns a list of users from my database and returns responses as JSON data. api/blogs can return a list of blogs in JSON with a get request, or post a blog with a post request.
I have learned and been able to implement very basic user tokenization with JWT, and so only logged in users with a valid token can make a post of a blog for example. This is done by adding their token with bearer as a Authentication header in the request, which the server verifies. This makes sense to me, however I am very confused on how the backend works or if I am doing something critically wrong.
If I go to my main page for my application, and type api/blogs it opens up a page displaying JSON data. Anyone can basically view this from my application by going to api/endpoint
I am also assuming anyone from outside can use something like Postman to send a post request to my database assuming they have the token which they got since my token is saved in storage.
This is incredibly weird to me Is this just how these things work? Or am I failing to understand something crucial?
if I wanted to progress forward and learn more about this, where or what do I do?
You have described how users authenticate to your application (with a bearer token), but what steps does your application take before issuing such a token?
Does your application keep a database of users and their passwords?
If yes, can anyone sign up by inventing a user name and password?
Do you verify an email address before admitting a new user?
Or does your application rely on an external OpenID Connect service (for example, login with your Google or Facebook account)?
If yes, can anyone with a Google or Facebook account sign up for your application?
Or must an application admin (that is, you) put the user on an "allow-list"?
To summarize: Unless you take special precautions, anyone from outside can sign up to your application and subsequently use it.

React app using msal-react, how to automatically authenticate user

I'm working on a react app where the pages can be used both by authenticated and anonymous users. The pages show more features for the authenticated users.
If a user previously has signed in and revists the website, I want the user to be automatically authenticated, and am struggling to achieve this.
I'm using redirect methods because I don't believe popup is working well on phones (is that assumption correct?).
I have tried storing the homeAccountId in local storage and use that to get the account used and then calling login in the msal instance. I also set up a addEventCallback and listen for EventType.LOGIN_SUCCESS which I use to set some internal state about the logged in user.
I have tried using MsalAuthenticationTemplate but strangely this doesn't invoke a login. I have also tried to detect if this is a "first run" and then invoking the login, but that doesn't work all the time. Sometime I get a SSO error indicating I should provide a login_hint or sid which is not possible because I use B2C.
If I don't do anything the user can click the login button and if the user has a valid cookie with B2C the user is logged in without providing credentials which is a strange behavior for the user because my website indicate the user is not authenticated (and show no logout button).
So I can't really get this to work and are wondering if somebody has a concept for achieving this?
Please checkout the msal-react samples which all demonstrate the behavior you're looking for. The MsalAuthenticationTemplate would be the recommended way to do this and if you're still having issues getting this to work after reviewing the samples I would recommend opening an issue on our repo with code snippets so we can take a closer look at what's going on.
Also using localStorage, if you're not already, would help to maintain application state between browser sessions. sessionStorage is the default.
As for B2C not asking for credentials; server state is separate from client state. You can be signed in on the server without the application knowing about it. Until your application makes a request to the B2C server your application will show that a user is not signed in. If a session already exists on the server when you make a login request, the server may redirect you back to your application without asking for credentials again.

How to let frontend know your server has successfully retrieved an access token

I've been studying the OAuth 2.0 authorization code flow and am trying to write a React application with an Express backend that displays what a user would see on their own Instagram profile. I'm trying to do so with minimal external libraries (i.e. not using passport-js) and without bringing a database into the mix.
This is my flow as of now:
Resource owner clicks an <a> tag on the React application (port 3000) which redirects them to the /auth/instagram endpoint of my Express server (port 8000)
res.redirect(AUTHORIZATON_URL) sends them to Instagram's authorization server
Resource owner consents and the authorization code is sent back to the predefined redirect-url /auth/instagram/callback with the authorization code set as a query parameter
I strip the authorization code off the url and make a POST request to https://api.instagram.com/oauth/access_token to grab the access token
Now that I have the access token, how do I reach out to the React frontend to let them know that everything worked and that the user was successfully authenticated?
From what I've read, this is where the idea of sessions and cookies come into play, but I haven't had luck finding documentation on how to achieve what I want without bringing in third party libraries.
In the end, I would like for my app to support multiple users viewing their profiles simultaneously. Since I imagine passing the access token to the frontend defeats the purpose of securely retrieving it on the backend, I'm guessing I will somehow need to pass a session id between the frontend and backend that is somehow linked to an access token.
Any ideas as to what my next steps should be are greatly appreciated, as well as any articles or documentation you see fit. Thanks!
Since you're doing the OAuth authentication on the server side, you have to pass some parameter to the redirect_uri, identifying the user session (see: Adding a query parameter to the Instagram auth redirect_uri doesn't work? );
When the redirect uri is called from the authority server, you will know which user was authorized. To notify the browser there are two options: 1) Notify the client using web sockets; 2) Pull the state from the client using a timer triggered function;

Steam authentication API, passing data back to Angular

I have this problem with Express(NodeJS)/Angular web app where I rely on Steam's login authentication. Essentially when the user clicks "Login" he's redirected to the Steam authentication(Steam's website), once logged in the user is redirected back to a specific route on my backend called /verify. Once the user hits /verify there are session variables containing necessary user data to access. Therefore I use JWT to generate a token with this data to send back to the client(Angular in this case).
The problem is sending this token back to the frontend(the client) to save in local storage.
Any help is highly appreciated! Currently, I pass the token via a query string with a redirect back to the frontend, but this doesn't seem like a good solution.
Maybe I should stick to server-side sessions and write HTTP routes to GET user data. The problem with this approach is once again the client is completely unaware when the user authenticates himself on the backend, since the only callback is triggered is on the backend.
EDIT:
Tried another approach, however once again unsure of it's the right way to go both code-wise and security-wise.
Redirect the user to the Steam authentication page.
Wait for the authentication callback on server side, in my case it hits the route '/verify'.
Once at /verify the session cookie is already set, therefore I redirect the user back to my Angular app to a specific route called '/login'.
On /login the user requests a token based on the session cookie on the server, the token in my case is a JSON Web Token(JWT).
Once the token is saved in local storage I simply redirect the user to any page in my Angular app.
If this is the wrong way to do it, please let me know!

How do you handle navigation in a token-secured web application?

I have a rather conceptual question, I'm sure it's fairly stupid, but I can't figure it out.
So I am building a simple node.js app to learn, I want to make a web app which is has a set of REST web APIs for everything (including authentication), and then the presentation.
For authentication I am using token-based auth with PassportJS.
So when a user wants to access the site, he'll obtain a token from the authentication API, in turn he'll need to pass this token in a HTTP Header on each request to the app.
My question is, how is this handled in the code? When the app gets the token (for example from a login page which hits the auth API), should it attempt to store it in the local machine (for example LocalStorage, or Cookie) and then on each new page fetch it and use it in a Header? Should each page's javascript attempt to load the token from the local storage automatically? I tried looking for an example, but haven't found a complete one that deals with how you handle navigation when you're depending on sending a header on every single request (that you want authenticated).
Thanks!
Once the user is authenticated return a secure session cookie which will be stored by the user's browser. Now on every request, this cookie will be sent by the browser to your application automatically, which you can check in your backend code (typically controller) to verify the existence of user session.

Resources