How to implement optional two factor authentication with passportjs - express

I have implemented an API in Express with passportjs local strategy for authentication, now I would like to enforce security by adding the possibility for the user to log in using two factor authentication, for that it exists passport-totp strategy, I read about it and saw some working example, but I didn't find out yet what I want to implement. I would like on a same route (let's say /login) to check if the authenticating user has the 2fa previously enabled (this would be handled by user settings) or not, if it is enabled then having it authenticated only if the user complete the authentication by following the 2fa additionnal verification, if it is not enabled, having the user authenticated by they simple login/password credentials.
If anyone could explain to me how to do it (the big picture) or if you know any example of look a like implementation, I would be very pleased !
Thank you

I ended by dropping passport-totp, implementing simple authentication flow with local strategy and added a custom layer to handle second factor

Related

Securely using JSON web tokens to programmatically authenticate a user from one system into another

My team and I have been working on a web application for our clients that uses JSON web tokens for authentication and authorization. Using Azure AD as our identity provider, we verify a user's identity and generate a signed JWT with the user's permissions in it. The JWT then gets included in the authorization header of all subsequent requests to the APIs. Pretty standard stuff as far as JWTs go.
We're now being asked to provide the capability to link directly into our system from another third-party web application without forcing the user to reauthenticate. I'm trying to figure out if there's a way to do so without creating a massive security loophole.
The way I picture this working would be to implement an endpoint for programmatic authentication in our system that accepts a cryptographically signed payload with an API key and the user's ID or email address. The third-party system would have a private key with which to sign the payload, and we'd have a public one to verify the signature. If the request is legitimate, we'd issue a token for the specified user, and they could use that to link to whatever they like.
I'm already getting yelled at by at least one person that this is a complete joke from a security standpoint because, among other things, it completely bypasses AAD authentication. I believe the third-party system in question does use AAD for authentication, but that's not really relevant either way because we're trusting them implicitly whether they've authenticated their users or not. Either way I take his point.
I'm not a security expert and I don't claim to know whether there even is a proper way to do this kind of thing, but from my vantage it doesn't really seem all that much less secure than any other mechanism of authentication and authorization using JWTs. Is that true? Are we nuts for even trying? Is there a way to do it that's more secure? What should I know about this that I demonstrably don't already?
Thanks in advance for the help. At the very least I hope this spurs some helpful conversation.
Single Sign-On (SSO) enables users to enter their credentials once to sign in and establish a session which can be reused across multiple applications without requiring to authenticate again. This provides a seamless experience to the user and reduces the repeated prompts for credentials.
Azure AD provides SSO capabilities to applications by setting a session cookie when the user authenticates the first time. The MSAL.js library allows applications to leverage this in a few ways.
MSAL relies on the session cookie to provide SSO for the user between different applications.
Read more in this documentation.

Auth0 embedded login flow

We are trying to implement Auth0 in our next+fastify based application. The login page is custom and we want to integrate the login using the embedded login from the fastify server.
I am naive to oAuth and Auth0, I have a few doubts around it:
How do we verify the token? Do we verify the JWT and maintain the token on or fastify server or should we always the validate the token on Auth0 endpoint? I tried calling the userinfo endpoint which resulted in rate limiting. So, I interpret if we just verify the JWT on server instead of sending to Auth0 server. Also we send and maintain the JWT in cookies to validate the client always. Is the understading correct?
Is embedded login safe enough to be used in production? Are there any risk associated around it?
Is the approach correct? Is there any alternative way to implement the login flow? We also need to integrate reset password and rest of the functionality. I have read the SDK docs and it seems to have support for all.
Thanks a lot in advance
There are several options to validate a token issued by auth0, they recommend you to take advantage of middleware to verify the token. Multiple frameworks have their own middleware to check and validate JWT. It's as easy as integrate middleware with your application and perform validation when you need it. Check this:
https://auth0.com/docs/tokens/json-web-tokens/validate-json-web-tokens
In my opinion, it is always better to go with the Universal Login option of auth0, since embedded login sometimes incur into the cross origin authentication issue. Remember, when a user tries to log into your application using auth0, it redirects the user to another domain that differs from the one serving your application. In my experience, using the universal login provides you more information about the login process of your users, and that makes the process of debugging errors and auth processes easier. You can read more about login with auth0 here:
https://auth0.com/docs/login/embedded-login
https://auth0.com/docs/login/embedded-login/cross-origin-authentication
Yep, you can integrate the reset password process, which is almost entirely handled by auth0 itself. As I said earlier, we use Universal Login for our applications since it provides more control over the authentication flow. That doesn't mean you can't use Embedded login, it is a very good option too, but it seems more focused in UX rather than control auth flow.
Check this link if you still have doubts about the best approach: https://auth0.com/docs/universal-login/universal-vs-embedded-login

Difference between frontend user authetication and backend user authentication

I was recently asked the difference between frontend user authetication and backend user authentication ( during an interview ). I could not come up with an answer to his question. He asked me if the authentication you see on the web all the time is done at frontend or backend, I answered backend. Then he asked what is frontend authetication then, I could not answer.
I googled to find out, but could not get exact difference between the two, what is done at frontend vs what is done at backend. How, where and why each of them are used?
Any help would be appreciated.
EDIT : I read something related Here. It talks about something called dual authentication. Still, I am not able to understand the concept of frontend authentication.
My understanding is that after a user is authenticated on the backend, a unique cookie is issued to the browser. This might be considered frontend authentication, as it allows users to continue using a site without having to log in to every single page. The website recognizes the user from the cookie data for each subsequent call, subject to whatever limitations are put in place.
A simple example would be a cookie that stores the username and password, but obviously that wouldn't be very secure. More sophisticated methods would involve encryption, SSL, various flags (secure, http-only, expiry-date), and so on.
The question is subjective and can have too many interpretations based on context.There's a type of user to system authentication and system to system authentication. The closest analogy of front end authentication in this case will be user to system authentication irrespective of the underlying protocol and whether or not an explicit back end stack being used. Whenever two systems have to authenticate against each other without a user involved can be analogous to Backend Authentication. Again this is subjective and very contextual

Microservice Authentication strategy

I'm having a hard time choosing a decent/secure authentication strategy for a microservice architecture. The only SO post I found on the topic is this one: Single Sign-On in Microservice Architecture
My idea here is to have in each service (eg. authentication, messaging, notification, profile etc.) a unique reference to each user (quite logically then his user_id) and the possibility to get the current user's id if logged in.
From my researches, I see there are two possible strategies:
1. Shared architecture
In this strategy, the authentication app is one service among other. But each service must be able to make the conversion session_id => user_id so it must be dead simple. That's why I thought of Redis, that would store the key:value session_id:user_id.
2. Firewall architecture
In this strategy, session storage doesn't really matter, as it is only handled by the authenticating app. Then the user_id can be forwarded to other services. I thought of Rails + Devise (+ Redis or mem-cached, or cookie storage, etc.) but there are tons of possibilities. The only thing that matter is that Service X will never need to authenticate the user.
How do those two solutions compare in terms of:
security
robustness
scalability
ease of use
Or maybe you would suggest another solution I haven't mentioned in here?
I like the solution #1 better but haven't found much default implementation that would secure me in the fact that I'm going in the right direction.
Based on what I understand, a good way to resolve it is by using the OAuth 2 protocol (you can find a little more information about it on http://oauth.net/2/)
When your user logs into your application they will get a token and with this token they will be able to send to other services to identify them in the request.
Example of Chained Microservice Design
Resources:
http://presos.dsyer.com/decks/microservice-security.html
https://github.com/intridea/oauth2
https://spring.io/guides/tutorials/spring-security-and-angular-js/
Short answer : Use Oauth2.0 kind token based authentication, which can be used in any type of applications like a webapp or mobile app. The sequence of steps involved for a web application would be then to
authenticate against ID provider
keep the access token in cookie
access the pages in webapp
call the services
Diagram below depicts the components which would be needed. Such an architecture separating the web and data apis will give a good scalability, resilience and stability
You can avoid storing session info in the backend by using JWT tokens.
Here's how it could look like using OAuth 2.0 & OpenID Connect. I'm also adding username & password login to the answer as I assume most people add it as a login option too.
Here are the suggested components of the solution:
Account-service: a microservice responsible for user creation & authentication. can have endpoints for Google, Facebook and/or regular username & password authentication endpoints - login, register.
On register - meaning via register endpoint or first google/fb login, we can store info about the user in the DB.
After the user successfully logs in using either of the options, on the server side we create a JWT token with relevant user data, like userID. To avoid tampering, we sign it using a token secret we define(that's a string).
This token should be returned as httpOnly cookie alongside the login response. It is recommended that it's https only too for security. This token would be the ID token, with regards to the OpenID connect specification.
Client side web application: receives the signed JWT as httpOnly cookie, which means this data is not accessible to javascript code, and is recommended from a security standpoint. When sending subsequent requests to the server or to other microservices, we attach the cookie to the request(in axios it would mean to use withCredentials: true).
Microservices that need to authenticate the user by the token:
These services verify the signature of the JWT token, and read it using the same secret provided to sign the token. then they can access the data stored on the token, like the userID, and fetch the DB for additional info about the user, or do whichever other logic. Note - this is not intended for use as authorization, but for authentication. for that, we have refresh token & access token, which are out of scope of the question.
I have recently created a detailed guide specifically about this subject, in case it helps someone: https://www.aspecto.io/blog/microservices-authentication-strategies-theory-to-practice/
One more architecture perspective is to use nuget-package (library) which actually do authentication/token validaton. Nuget-package will be consumed by each microservice.
One more benefit is that there is no code duplication.
you can use idenitty server 4 for authentication and authorisation purpose
you must use Firewall Architecture hence you have more control over secutiry , robustness ,scalability and ease of use

Flask-HttpAuth and Flask-Login

I am creating a small REST service. I am looking for different authentication methods.
For sites I used the module Flask-Login. It seems the session authentication. The module Flask-HttpAuth provides the http and digest authentication methods. I am little bit confused.
Do they complement each other?
What is better to use for what is a reason?
Thank you.
For a REST service you do not need Flask-Login. Typically in web services you do not store client state (what Flask-Login does), instead you authenticate each and every request. Flask-HTTPAuth does this for you.
You would use both only if you have an application that has a web component and a REST API component. In that case Flask-Login will handle the web app routes, and Flask-HTTPAuth will handle the API routes.
Disclaimer: I'm the author of Flask-HTTPAuth.
You can setup Basic Auth for Flask in a very simple way, without further modules, using decorators.
Take a look at: http://flask.pocoo.org/snippets/8/.
With flask-restful, just add method_decorators = [required_auth] to the Resource class attributes.
You can extend the snippet above, to allow for example user retrieval from a database.
Note that in a REST architecture, requests are stateless: you don't use sessions, but send identification tokens along with every request (see http://broadcast.oreilly.com/2009/12/principles-for-standardized-rest-authentication.html).
Yes they complement each other.
You can also take a look at Flask-security, an all-in-one lib:
https://pythonhosted.org/Flask-Security/
Session based authentication
Role management
Password encryption
Basic HTTP authentication
Token based authentication
Token based account activation (optional)
Token based password recovery / resetting (optional)
User registration (optional)
Login tracking (optional)
JSON/Ajax Support