passport js vs firebase authentication system - reactjs

Is there any valid reason to use passport js based authentication using express js in backend over firebase authentication system in frontend using react?
just explored passport js and want to know before using in a MERN Stack project

PassportJS is just an authentication middleware that can be used with different authentication strategies. If I understood you correctly you might be comparing Passport's local strategy with Firebase auth's username/password one, in this case:
My answer would be a classical "IT DEPENDS", first I will answer the first part:
Why use Firebase-auth (or any other third-party authentication service)
Authentication is hard, and you may not want to deal with it on your own (most of the time).
If you are planning to use a "local" authentication strategy with a username/email and a password, you might need to consider and maintain a set of best practices to avoid having a broken-authentication system, you will need to encrypt your passwords and ensure that they're safe on at-rest and in-transit, you also want to ensure that your system uses libraries or logic to avoid timing attacks. Also, you may need to consider forcing some rules on password lengths and that they're not too weak (ex: they belong to a list of most-known passwords)...
Besides these, you may also want to implement password recovery mechanisms, email change, and maybe "Email confirmation" logic which might be tricky sometimes.
Did I forget to mention reCaptcha and 2FA? Bots are getting smarter nowdays.
I definitely missed some other best practices or risks that should be considered when not using a managed service like Firebase-auth.
These services are built by people who only care about "Authentication" for you.
Firebase-auth is not the only service, you may want to look into other options like auth0.
Of course, this option is not the cheapest in terms of cost and flexibility. Firebase auth has a generous free tier, but it will be paid when your application grows, see: https://firebase.google.com/pricing.
So, if you go with this option, consider organizing your application code to be easily decoupled from Firebase in case you wanted to migrate from it someday.
Why use Passport-local
Using the middleware on your own means that you will have more flexibility in managing your different authentication strategies and you will only pay an extra cost of maintaining your application's authentication logic (which might be high as you need to keep in mind the best practices and risks)
Other considerations
This depends on your use case, and your team:
You may look into some services that handle the authentication out of the box like Keycloak
Use Passport.js as a core library but with strategies like Auth0's (https://www.passportjs.org/packages/passport-auth0/)

Related

secure keys or sensitive data in angular2 nativescript

I am curious to know of available options, that a developer can use to secure sensitive information inside the mobile application. This is to prevent anyone from breaking the app and use keys for some nefarious purposes. Example of sensitive data includes passwords of APIs, which app can use seamlessly in the background to retrieve data.
Code obfuscation can help but cannot prevent from stealing the information;
Local storage options such as nativescript-couchbase or nativescript-secure-storage -if my understanding is correct- depends on feeding the information manually after installing the app. But the information needs to be available inside the app at the time of shipping.
OAuth is not an option as it requires the user to login in order to receive the tokens. JWT is neither an option, as the APIs are protected just using basic authentication.
I am using nativescript/angular2 but i would appreciate any generic simple yet effective ideas..
I think you are looking for obfuscation here, securing the information within your source code. By default {N} has uglify plugin configured within webpack, it gives the basic obfuscation.
There is Jscrambler support which is paid.
Also, speaking of Sqlite, there is commercial version of the plugin that supports encryptions but I haven't tried it personally. You may feed your data into it and pack your db at build time then install the db on first launch.

Should I explicitly not use a standard URL with MSAL authentication?

All of the MSAL documentation wants me to use a prefix such as msalGUID:/// when authenticating back to the local device.
Then there is the oddball url urn:ietf:wg:oauth:2.0:oob that appears by default in the MSAL portal.
Since every URL I list there is essentially a backdoor into my application, I want to understand the security benefit of each option.
Why should I use the documented msalGUID:// scheme?
Should I not use an iOS Universal Link / fully qualified URL?
What is the benefit of the urn:ietf:wg:oauth:2.0:oob, and https://login.live.com/oauth20_desktop.srf?
What should I be aware of w.r.t. interactions with Microsoft Authenticator, which likely depends on this?
Background
There's a few attack vectors & usability cases that come into play when considering the redirect URI your app will use.
First, is your app going to be signing in users from an authorization agent that is not sandboxed to your app. If you're using MSAL, then the answer is almost always yes (unless you have explicitly opted to use in-app WebViews).
Cases to consider
If so, then you have two cases to consider: accidental collisions of redirect URIs (usability issue) and malicious apps intentionally trying to intercept a user being redirected back to your app (security issue).
Case 1: Naive apps
To address the former, MSAL has chosen msal<ClientID>://auth as it's unique to each app registration. There's a high amount on randomness in this format (that is lost with urn:ietf:wg:oauth:2.0:oob) which prevents the scenario in which multiple apps on the device are listening on the same URI and "accidentally" get the response. For a user, this is extremely frustrating and would impact their experience with their app. To summarize the best practice to address this, use a highly random URI that avoids accidental collision with other apps.
Case 2: Malicious apps
To address the latter, MSAL implements the Proof Key for Code Exchange (PKCE) protocol to eliminate this attack vector. To expand on the scenario, it's similar to the above scenario, except for the app has captured the response intentionally and intends to exchange the authorization code on your behalf. With PKCE, only the app that initiated the request can exchange the auth code.
Summarizing answers
To quickly answer your bullets,
Covered above.
If you're familiar with universal links and how to setup the necessary steps, this may be a good option for verifying that your app registration is only used by you.
These are intended for apps using in-app WebViews where there's stronger security guarantees related to the fact it's not leaving the app.
MSAL does not currently integrate into the Authenticator to complete auth requests. When it does, apps will likely be required to complete an enhanced registration related to redirect URIs similar to ADAL's requirements.

How to secure REST API for SPA and Mobile App using Cordova

I've done a lot of research on "best practices" surrounding this and have read blog post after blog post, SO question after SO question, and OWASP article after OWASP article. I've arrived at a few clear answers but some unknowns.
First, the "Do's":
Use JWT for authorizing users on my REST API [1] [2]
Store the JWT in a HTTPOnly/Secure cookie and build in CSRF protection. Do NOT store in HTML5 local storage [3] [4] [5] (Actually, this point is debatable, is it easier to protect against XSS or CSRF? [6])
Verify the signing method of the JWT [7]
Now I started with the assumption that having a SPA (built with Angular) and using HTML5 sessionStorage would be secure enough for short-lived tokens, but there is a point to be made that XSS attacks can happen from a "bad actor" originating in the one of many libraries loaded in from a CDN.
For my specific use case, I do not plan on having long-lived tokens - expiration after 10 minutes of non-use but I'm still figuring out if I want to track expiration by session or use refresh tokens - StormPath recommends the former (no longer stateless?) but I believe big players using JWTs use refresh tokens (Google uses them but states you need to store them in secure, long-term storage which means HTML5 localStorage is again, out of the question).
I would like to make it so my users don't have to log back in if they refresh the page (hence the need to store the token on the client side). I would also like to use my SPA as a "mobile app" with the help of Cordova. The obvious pitfall here is that if I use cookies, there is no baked-in cookie support/storage with Cordova and I'm urged to switch to HTML5 local storage instead. Since on mobile I don't really need to worry about refreshing pages, I can just let my token live in memory and expire with the strategy I settle on.
If I take this approach, cookie-based JWT on Desktop, "Bearer" headers on mobile, I now need an authentication end-point that will give tokens two different ways, and when I authorize on the REST API side, I need to support both cookie-based JWTs (with CSRF) and header based JWT verification. This complication has me worried as I don't know if I can accurately foresee security implications here.
To summarize the barrage of thoughts above:
Create an authentication handler that would hand out tokens via HttpOnly/Secure cookies to desktop, and by payload for mobile.
On my REST API, support both methods of verification - header based and cookie-based - including CSRF protection for the cookie-based approach.
Is there any reason why I wouldn't want to take this approach? I assume if I take XSS on my SPA as a serious risk, then I need a classic login-page for authentication to set the proper cookies because if I do authentication via the SPA, then any XSS attack could potentially intercept that as well (both on mobile and Desktop)! However, on mobile, I'd need to inject the JWT into SPA, maybe through some custom DOM element (meta tag?), but at that point I can just let the SPA perform the login and not consider XSS a threat on mobile devices. Cordova packages all assets into the install package so that's somewhat better but then why not take the same approach on the Desktop version?
My application takes very little user input, it is primarily a dashboard/reporting tool. There will be a "message center" but it's content should always be user-created (by only that user) and sanitized. In my use-case then, would it be ok to deviate from "best practices" and rely on localStorage not counting XSS as a serious risk for my SPA? This would simplify this entire thing (use HTML5 sessionStorage as originally planned) and reduce complexity, which would reduce attack surface for potential security blunders. I just want to make sure I understand the risks before moving forward.
Is there no secure way to make this secure other than by building a native app for mobile and not using Cordova to convert my SPA to a mobile app? I'd hate for this to be the case, but it might very well be.
I'd appreciate all thoughts on the matter!
When thinking of designing javascript based cross-platform applications to run a mobile device, many of the caveats with designing regular web browser based applications do not necessarily apply.
As far as security is concerned, whether you decide to use JWT or simple OAuth tokens, ensure that all your communications are via https.
Please use localStorage as much as you want.
If you consider the anatomy of a http request, all it really is sending some text based message divided into multiple sections to a server. The header of the request is no more secure than any other part of it including the cookies. So the points of interest from a security perspective are generation/validation/invalidation of the token, storage of the token on the device and the transport mechanism of the requests.
Generation/Validation/Invalidation: Generate the tokens on your server. Use some technology/strategy to ensure that there is no possibility for collisions or bleeding. Also, ensure that your strategy will allow you invalidate a token on the server which then subsequently denies access to data requested from the server on further usage of the token. It is then up to you in your app to handle the users UI journey when the server denies access to resources.
How you store the token on the device is constrained to what the device OS make makes available to you. Regarding whether using a native app is better than cross-platform, I think creating a native-cordova plugin to store your token using any specific native strategy if one is unsatisfied with the "out of the box" ones (such as local storage) is possible, although in my experience this is usually overkill. Happy to be corrected on this one if anyone has a different experience.
Please use HTTPS ALWAYS without exception for ALL Webservice end point communications. Is HTTPS foolproof, NO, but you wouldn't build a house without a front door simply because dedicated burglars could learn to pick locks. This secures the transport mechanism considerably.
Usually, this is all native apps have to work with too anyway.

Which is the better way to store my logincredentials(remember me option) and maintain session throughout the application in angular js

Iam developing angular js web application .I want to store the login credentials when the user checks on remember me option.can any one please suggest me which is the better way to store the details of user (local storage or cookies or etc).And I want to maintain the session throughout the application ..please give your suggestions.
Thanks in advance
There are already plenty of solutions for that kind of stuff. As this is a serious security issue, I would recommend to use one of those instead of "reinventing the wheel".
Whether the system is using cookies or localstorage doesn't really matter at the end of the day. It is however a bad idea in general to store the actual credentials. Instead, use a token-based system that will do a server-client handshake on request.
Personally, I am working with Firebase and Express at the moment.
Firebase
Firebase is "backend as a service". They offer a free plan for production usage, have a look at it. If you like it, things are pretty easy here. You pay money and get a full-featured REST-like "backend" with built-in user management (See Firebase doc's for SimpleLogin). All you have to do is calling service methods.
Express
This is the DIY way. If you want to have full-control and a free way of doing things, this is the way to go. I am no Express master, so you better have a look at some Tutorials (http://expressjs-book.com/forums/topic/express-js-sessions-a-detailed-tutorial/)
If you don't like neither Firebase nor Express, have a look at other Backend-as-a-service offers. You could even use PHP. I would assume that one could say that this is the oldschool way of implementing user sessions :)

Angularjs and php as backend

I've created a angularjs app which uses php for handling the database queries and enforcing an authentication schema.
When the user logs in into the app, he does so in php and php fetches the user data into a session. Then angularjs issues a http post request to a php page to read the fetched data.
After that, whenever a user asks for data, angular issues a post to a php page.
I'm considering using a framework for doing the authentication and the database queries in a better way. My security knowledge is primitive and I fear that I have mistakes in my code.
After doing a research I found laravel which seems straightforward and easy.
Now my questions are:
Can a php framework such as laravel do these things for me?
Is there something else I could use to have people authenticate and making sure that they are doing the CRUD operations they are authorized to do?
What are the keywords I'm searching about, is it routing, is it php restful? I'm asking in order to do further research on the matter.
Is there any other way in which a SPA could work with CRUD operations and Authenticating in a "safe" manner using php?
I know that the above questions are not programming questions per se, but I don't know where to ask (because I feel I cannot communicate what I want to learn about/ *that's why the keywords question above).
Thank you
There's basically two kinds of relevant "routing" both based on URLs, either client side or server side. AngularJS has the $routeProvider which you can configure so when the location changes (handled by $location) the client side template and controller being used also change. On the server side you may have redirects or "routes" that map a URL to a particular PHP file (or Java method) where at the destination it parses the incoming URL to get extra information/parameters.
I know nothing about laravel, but googling laravel and authentication came back with this which looks promising:
http://bundles.laravel.com/category/authentication
I also know things like Zend framework provide many similar options for plugging in some authentication code.
Ultimately if you're writing the CRUD operations something in your code is going to have to do deal with the role based execution of code or access to data.
RESTful is it's own thing. At a very basic level a RESTful interface uses HTTP "verbs/vocuabulary" like PUT, POST, DELETE, GET (part of the request headers which is just data that comes before any body data in the request) are given special meaning like update an entry etc. It's mostly orthogonal to the issue of authentication though if you do true REST I'm not sure if using the SESSION for maintaining authentication would be allowed since it's not completely stateless in that case (anyhow just an academic argument). Point being you can use the other ideas of REST or use some implementation that is "RESTful" and it can be written in any language or you can choose not to do this, either way you still have the issue of controlling resources (functions/methods/data) that you want to control and this issue is not the same as choosing RESTful or not RESTful (if you wanted to keep true to REST for reasons of scalability across a cluster of servers etc. you could follow guidance here How do I authenticate user in REST web service?). Also to note here the $resource in AngularJS provides an abstraction above $http specifically for handling restful services.
IMHO you should be searching for two things
1 php security/authentication
2 php hacking/hacks/vulnerabilities
You can simply write your own authentication mechanism using a session to keep track of the signed in user. http://php.net/manual/en/features.sessions.php There is no difference in a SPA vs a traditional web app as far as the server is concerned, these are simply differences in the client side code.
Any security you intend on putting in place is really only as good as your understanding of that security. I wouldn't trust someone else's plugin from the internet to handle authentication for me unless time was an extremely critical factor and security not so much. One thing that you hadn't mentioned but I think is worth looking into and necessary for any of this to really be secure is SSL. If you don't have your data encrypted there is always a possibility of a man in the middle attack (someone getting the plaintext username and password as their submitted to the database) or session hijacking (someone getting the sessionid of an active session then using that to act as the original user). Basically I would suggest you keep doing research regarding best practices and personally look over any code you plan to use to be sure you understand how it's working and what kind of security it provides you with.
I also wanted to mention, though it's a bit off topic languages wise, that Java Spring has some really nice stuff for dealing with authentication and handling access to services and data. If security is a major concern I would probably strongly consider running a Java server (not to say Java has never had it's issues or that it's automatically more secure but there's a lot of production code that has withstood the test of time). There's the free Tomcat J2EE Server or IBM WebSphere if you need to massively distribute an application. If interested search for Java, Spring, Hibernate (ORM), MyBatis, Data Access Objects. Those are all the parts (some optional) I can think of you would need to put together a service layer in Java. Good intro in the video on the left of this page:
http://static.springsource.org/spring-security/site/index.html
Also SSL isn't a silver bullet, but every layer of security helps.
Kevin Mitnick said in one of his books that lots of places have "hard-shell candy security" (paraphrasing) where breaking the outer layer means you get to all the mushy goodness inside. Any direct answer I would bank will result in this type of security.
Depending on the scope of the project it might be necessary to have security professionals do penetration testing on the system to determine if there are vulnerabilities so they can be plugged.

Resources