27
81 Comments

Ask IH: How do you do authentication?

Could you show me how you currently do authentication? What tools and software did you choose? Any parts you love and hate.

posted to Icon for group Developers
Developers
on January 27, 2020
  1. 9

    I generally roll my own:

    • On successful signup or login, create a new JWT token that includes the user ID. Tokens expire within 1-24 hours depending on security tightness. Optionally include a refresh token that is longer lived.
    • JWT token is (edit: thanks @DanHulton) automatically managed via HttpOnly cookies on web.
    • On mobile, the flow is slightly different:
      • Token is stored in secure app storage.
      • Attach the token to the Authorization header on subsequent requests.
    • If token is expired, use refresh token to get a new access token.
    • If this also fails and 401 is returned, log user out and required new login.
      • On web this means making a call to the backend which will remove the cookie.
      • On mobile this is as simple as deleting the token from secure storage.

    I prefer this approach to session based storage but that is also a valid option.

    If you want an off the shelf solution, Auth0 is a pretty good option though it can get expensive.

    1. 2

      I had cause to look into this pretty extensively recently, and the one thing I'd recommend is not storing that JWT in localstorage. Any javascript on the page can then access that token, and if you get XSS'd, they can then send those JWTs off to an attacker site for later misuse.

      Store them in secure, http-only cookies instead. You'll need to lightly modify your infrastructure (for instance, you can't just delete the JWT from the client, you'll need to hit a server endpoint and have the server clear the cookie), but it's worth it for the additional layer of security.

      1. 2

        I would say localStorage is just fine. If you get XSS attacked, it's already basically game over. The attacker can use your site to do what they want (even if you are using HttpOnly cookies). And as @parhelion pointed out, cookies have their own attack surfaces.

        I would recommend spending more time protecting against XSS attacks.

        1. 3

          I'd still prefer avoiding localStorage. Yes if someone XSS'es you, you have a breach situation, but if you practice defence in depth, you can mitigate the reach of said breach. Limiting your JWT accessibility is a good preemptive step to take, because then those tokens can't continue to be used after you close the XSS exploit. It's obviously not the only step you want to take, but the more layers of security you can reasonably add, the better.

          1. 1

            True. Although, that can be mitigated in other ways such as a blacklist for JWTs.

            My point wasn't so much that localStorage is better but more that each method has tradeoffs so use whichever is easier. Within reasonable security of course.

            1. 3

              JWT blacklisting can be used to mitigate that issue. However, by implementing that, you are bypassing the one major benefit of using JWTs - super fast session verification (it becomes almost equivalent to opaque tokens).

              That being said, I strictly prefer cookies over localstorage because:

              Even if you have JWT blacklisting, in order to blacklist it, you first need to detect that it has been stolen or that it is being maliciously used via an XSS attack, both of which can be quite difficult to detect accurately. So we want to minimise chances of these attacks. Now, both cookies and localstorage enable XSS attacks, however localsatorage also enables JWT theft, which cookies don't.

              In terms of CSRF attacks, localstorage doesn't allow for that, but it's incredibly straightforward to implement anti-csrf tokens within the JWT. So we can simply ignore this attack.

              Therefore, cookies are better.

              Source of my thoughts:

              1. 1

                @hello_world I see you were working on a session management solution for Node.js. How is that coming? I would love to try it out if it is ready!

              2. 1

                I wouldn't say that super fast session verification is a big benefit of JWTs. I'm still looking up the user in the database for role and other information that I wouldn't store in JWTs.

                You would have to detect that an XSS attack in order to stop it as well. So cookies have that same problem. Just different ways of mitigating.

                I'm not super familiar with how to remediate CSRF attacks but I wouldn't say you can just ignore it. You still have to make sure you cover it.

                Again, if an XSS attack is happening, it's game over. The attacker can do whatever they want with your API until you detect it. Once you detect it, you mitigate it via whatever method you need to. There is no useful difference between localStorage or cookies. Just different ways of stopping the issue.

                In any case, keeping XSS from happening is the most effective mitigation of either issue. Therefore, spend time keeping that from happening as a primary priority.

                Those are some great sources. They think through a lot of situations. But my opinion remains that keeping XSS from happening is the best defense regardless.

                I'm definitely not saying that I'm smarter than the people at OWASP (I'm most definitely not). I would link to the source of my thoughts as well but it was a podcast and I can't find the episode...

                1. 2

                  Hi @nprail,
                  Thanks for your reply! You can try out SuperTokens for node today! We currently support many popular databases and websites (with support for sessions on mobile apps coming soon). Go to https://supertokens.io to try it out.

                  Regarding my comment of ignoring CSRF, I did not mean to say that one should ignore this attack, but instead, it's very simple to solve, and hence one can treat it as a completely solved issue (i.e. we can ignore this attack for argument's sake). I do agree that this must be dealt with.

                  I also agree that if a site is vulnerable to XSS, it is "game over", and I also think that technically it's impossible to solve for this attack (since someone can be manipulated into copy/pasting js into the browser console). With that in mind, it's a fact that using httpOnly cookies reduces any damage from XSS, as compared to using localstorage. Hence, I strongly feel that cookies are the best way to go.

      2. 1

        This is a good point! Though even HttpOnly cookies are susceptible to CSRF attack surface. Mitigating that requires another small bit of infrastructure but also very doable.

    2. 1

      Auth0 is a pretty good option though it can get expensive.

      I was just looking at the pricing. Did you have a budget in mind you wanted to spend on auth? What budget should I consider spending on auth?

      1. 1

        It really depends on your operating budget.

        For example, if your product is an enterprise SaaS that isn't expected to have a ton of overall users, Auth0 is a great option because you can probably cap out at $100 / month (roughly 5000 unique users).

        Alternatively, if your product is a consumer app that will have hundreds of thousands of users, Auth0 will be prohibitively expensive.

  2. 7

    firebase auth. free & easy.

    1. 2

      Thanks. A lot of people are recommending firebase. Do I have to commit to the entire firebase ecosystem to use it? And how long does it take to easily implement?

      1. 1

        You can use it alone. It doesn't tied to any firebase services. 1-2 days I guess.

    2. 1

      do you integrate firebase directly from the frontend? if so, my understanding was that firebase was blocked in china so that could be a problem..

      1. 1

        Yes. Directly from the frontend. I'm using React. Not sure about it being blocked in China.

        1. 1

          do you use any react framework to communicate with firebase?
          do you use react hooks of some sort?

          1. 1

            https://www.robinwieruch.de/complete-firebase-authentication-react-tutorial/

            This one using class. You can convert them to React hooks easily if you are familiar with hooks. But it doesn't really matter.

        2. 1

          All google services are blocked.

  3. 5

    Hey Gat, we at SuperTokens are working on a product for session management right now! In solutions like firebase, auth0, and all such services, one drawback is the lifetime of the refresh token. All these services grants refresh tokens which are long-lasting. And you use the same refresh token to generate new access tokens. Going through ITEF RFC 6749 [https://tools.ietf.org/html/rfc6749] and ITEF RFC 6819 [https://tools.ietf.org/html/rfc6819], you’ll understand why refresh token should be used only once and why rotation of refresh token is required. The quote from this documentation is:

    “The authorization server could employ refresh token rotation in which a new refresh token is issued with every access token refresh response. The previous refresh token is invalidated but retained by the authorization server. If a refresh token is compromised and subsequently used by both the attacker and the legitimate client, one of them will present an invalidated refresh token, which will inform the authorization server of the breach.”

    Well, it’s tricky as well as complex to have a correct working solution where we can assure that refresh tokens are used at most once and are rotated correctly. The scenario where refresh token might get lost during the transit is not easy to handle either. We at SuperTokens have found a perfect solution that doesn't only do the rotate the refresh token on each use but also helps to identify the token theft scenario, i.e. if someone has stolen your refresh token. Well, of course, the solution also takes care of preventing various session related attacks such as XSS, CSRF. If you want to read more about this solution, you can head over to https://supertokens.io.

    Also, I would suggest against using AWS Cognito, especially user pools. You can check this link to know why:
    https://github.com/aws-amplify/amplify-js/issues/3495

  4. 4

    I usually roll out my own auth, if you're using Node.js, you can do it in a couple hours using Passport.js.

  5. 4

    I currently use both a homemade solution and AWS Cognito User Pools https://docs.aws.amazon.com/cognito/latest/developerguide/getting-started-with-cognito-user-pools.html.
    (If you are not familiar with Cognito, be aware that user pools are different from identity pools as the latter is linked to IAM users you might have in your AWS account)

    The big pro of Cognito is Price, fully-featured and free up to 50k users.
    I use it for its OAuth implementation, SAML integration and social logins, you can also have multiple pools for internal and external users.
    It has several cons though, integration not as smooth as Auth0, some stupid limitations on token duration and their hosted UI is not super customizable. Also, migrations from previous systems are a pain.

    Auth0 and Okta look more polished but as the number or even the type of users go up, the price becomes quite steep.

    1. 2

      I used to be on Cognito with Amplify but switched to Firebase. Cognito and Amplify both have major issues that don't get fixed. I wouldn't recommend anyone to start using it really. I initially used it before it was way cheaper than Auth0, but now I discovered Firebase (with FirebaseUI) there is no reason to stick with Cognito.

      Auth0 is very cool but expensive.
      Firebase is simple and totally free.

      1. 1

        I hear you, we've been fighting with some of the issues. I will definitely give firebase a chance on the next project, Google Cloud feels definitely more dev friendly than AWS.
        Just to be clear mine wasn't an endorsement just a report of my experience :)

        1. 1

          Well Google Cloud isn't great either tbh. Firebase is really nice but it's just a layer ontop of Google Cloud really. But Google Cloud itself can also be quite a beast to work with.

          I wanted to host some static files on a GCP storage with CDN but I ended up using S3 with Cloudflare instead. Simple things like setting headers on GCP storage is really annoying/near impossible.

          So I just use GCP or AWS, whichever part I need. I'd love to use an all in one cloud, but a good one doesn't exist. Don't even get me started on Azure :P

          1. 1

            Multi-account setup is much better on GCP and I much prefer IAM on GCP.
            The console UI is at least usable on GCP.
            Documentation on GCP is also much better and all the Machine Learning stuff is way ahead. Yes AWS has a massive offering and they don't drop products like Google.

            For my next project, I'll start exclusively with GCP and see if it delivers.

      2. 1

        Firebase is simple and totally free.

        Thanks for sharing Firebase. I will check it out. How did you find out about it?

        1. 2

          I used AWS Amplify before but it has critical bugs that aren't getting fixed so I started looking for an alternative. The 3 big players here are AWS, Firebase and Auth0.

          1. 1

            Did you consider or find any smaller players?

            So far Firebase looks both the simplest with fair pricing, but how much time should I expect to spend on implementing auth with it? Is there anything I can just drop in in 5 minutes and be done? Sort of like a PayPal button but for auth?

            1. 1

              Yes, Firebase UI does that. Or Auth0.
              That's also what AWS Amplify is aimed to do, but I can't recommend it.

              Thing is with authentication, I don't want to use a smaller player. I want a big player so I can be sure that my most important data is safe.
              I did come across a few smaller players but they were already out of business... That didn't help me confidence either :/

              1. 1

                Good point. Trust is key. How did you even find those smaller players? I can't find anything other than those big 3 you mentioned from various google searches (caveat: I also couldn't find Firebase initially though.)

    2. 1

      The big pro of Cognito is Price, fully-featured and free up to 50k users.

      Was price important to your project(s) for auth? Did you have a budget you were willing to spend to solve auth?

      1. 2

        Yes, for our use case Auth0 would have cost us a lot.

        1. 1

          Can you tell me more about your use case? 7,000 users for free sounds pretty good.

          (Auth0's pricing page is confusing though. 7k users on free plan, but otherwise $23/month for 1,000 users - which does sound very expensive)

          1. 2

            We have a mix of internal and external users, it would have cost us around 500 per month.

  6. 3

    I feel like I've seen 1 or 2 here on indie hackers. Only one that comes to mind is Kno by @richardesigns.

    https://www.indiehackers.com/product/kno

  7. 3

    I actually created a list of all the auth as a service platforms out there if interested. There's not actually that many! The best I could find / have heard of is Auth0, AWS Cognito, Firebase etc...

    https://github.com/karltaylor/awesome-auth-as-a-service

    1. 1

      Great to have a list. Thanks! What did you end up choosing?

      1. 1

        I've used Firebase Auth and also rolled my own using JWT, they all have their pro's / con's I think. E.g I have to roll my own forget password / confirm email integration with SendGrid with the JWT route, firebase auth does it all for you.

        1. 1

          Do the emails coming from Firebase have your domain or do they look like Firebase?

          1. 1

            You can set the email domain to be your custom domain, instead of [email protected] but I believe the email templates cannot be changed and are created by Firebase, but you can change the way they are implemented with custom email action handlers

            https://firebase.google.com/docs/auth/custom-email-handler

  8. 2

    Ruby's devise gem is quite robust in authentication

    1. 1

      What is robust about it? Have you tried it compared to any other service based solutions like Firebase?

  9. 2

    Something new that might be cool to look at is @dvassallo and https://userbase.com/

    1. 1

      Userbase looks closer to what I'm looking for. Have you used it?

      1. 1

        Userbase founder here. Let me know if I can help.

        1. 1

          This might come off snarky but it's not intended to. Userbase looks like Firebase - even the name is similar. What's the big deal of using Userbase rather than Firebase?

          1. 3

            All user data is end-to-end encrypted.

            Significantly simpler SDK.

            100% open source, MIT license.

            1. 1

              Love that it is open sourced.

              For the end to end encryption, is the onus on the user to save that backup key locally somehow? Any concern with less savvy technical users losing account access because of this?

  10. 2

    I decided to only create social logins for digester.app. I did that by using plugins in both the frontend and backend to handle the oauth exchange. All I need from the authenticate provider (eg. facebook) is the e-mail address and once I have that, I create a good old session on the backend.

    Some thoughts:

    • Sessions (I use redis) are easy to expire, which is a pain with JWT
    • Didn't want to use Firebase because it doesn't seem to be available in China and I'm terrified to depend on Google for such a critical piece
    • Auth0 looked very nice, but the pricing is not something I can afford
    • Manually implementing username/password login on my site comes with a lot of complexity I don't want to deal with right now: (a) prevent users from creating spam accounts, (b) require the users to verify their e-mail address, (c) other things I can't think of right now ;-)
    1. 1

      Did you use a framework to support the social login or just use the social company's login button code directly?

      1. 1

        I'm using vuejs and one of its authentication frameworks. I didn't use any of the facebook/... SDKs though.

  11. 1

    We built did.app to make it easier for services to offer passwordless authentication.

    Our solution is a combination of device crypto and email based account recovery.
    The crypto gives us one click sign in from trusted devices. We think it is the future with efforts like WebAuthN, It is hard to get right hence the value in a service.

    It's what we use. Our login is handled by our own service. We are currently in beta but there is a test site at https://example.did.app

  12. 1

    Just a plug for Laravel and its built-in authentication system. Just run:

    php artisan make:auth

    and you are good to go.

  13. 1

    Started with Auth0, continued with IdentityServer, which is a .NET Core OAuth server.

    The bad thing about maintaining your own OAuth server is understanding the lingo, which is definitely daunting when you first deal with it. The good thing however is that I have absolute freedom in designing the sign-on experience, and it's friggin' easy to integrate it with whatever client I'm building (which is also the case with Auth0 anyway).

  14. 1

    Firebase Auth is easy to quickly get set up and running with if you use firebaseui-web: https://github.com/firebase/firebaseui-web

    You're able to integrate with a bunch of third party OAuth providers, as well as email or phone number authentication. You don't have to worry about setting up the UI or even the forgot password flow, since Firebase will also handle email sending for you.

    Firebase can also send email verifications for you, but that requires a small bit of effort to set up (basically just calling the firebase send email verification function when a new user signs up).

  15. 1

    A general rule of thumb is "don't roll your own security".

    Figure out what your requirements are. Do you need social logins (i.e. via Google, Facebook, Twitter, etc)? Do you need Single Sign On from enterprise customers? If so you'll need SAML support.

    Then compare what you need vs. what different providers offer. Look at the ones mentioned here: Firebase, AWS Cognito, Okta, Auth0, or even run your own server with something like KeyCloak.

  16. 1

    Typically speaking, for a new project, I'll roll my own: store credentials securely hashed (Argon2 or PBKDF2) with an absolute minimum of PII stored in the system. On login, serve JWT as a secure, HTTP-only cookie. All APIs are secured and abstracted so that I can add other auth mechanisms later (OAuth, social, etc.).

  17. 1

    I tested many solutions, but for me the only thing I will ever use is auth0. Easy extendable and a good community. You should defiantly check it out! The free plan is also a bonus for MVPs!

  18. 1

    I'm mostly a FE developer so I wanted to avoid dealing with user management as much as possible and therefore I choose to use Auth0. It was a bad experience:

    • Signup is a pain.
    • Authorization is slow.
    • Documentation and setup not easy at all (nodejs / react).

    I'll be switching to probably firebase soon.

    1. 1

      Thanks. Good to know. There docs did seem unnecessarily confusing. They have good SEO though. They came up in many of my searches.

      Aside: Have you seen the mention of userbase.com above? I'm also looking into Firebase like you, but I'm now also interested in hearing more about Userbase.com.

      1. 1

        @gatleon thanks looks interesting! Doesn't seem like it handles social signup/login though

  19. 1

    If you’d rather not run a backend, we just launched Userbase to make it as easy as possible to add auth and persistence to a static site. https://www.producthunt.com/posts/userbase

  20. 1

    All handled by Firebase

  21. 1

    I'm working on a product for user management right now!
    My hypothesis that user management code is boilerplate across nearly all SaaS/productized services, and while user management is important, it isn't something worth rolling your own auth, allocation, payment, and support services for. |
    I'd love to talk more about what I'm building, and I'd love some feedback from all the IndieHackers. Feel free to shoot me an email, it's listed in my profile.

    1. 2

      Tell me more about that

      1. 2

        The general premise is that every SaaS product needs user management, payment management, resource allocation, and support tools. However, most companies tend to implement their own solution to this problem without thinking much about it.

        The core feature set of what I'm working on includes

        • user signup and login
        • session management
        • resource allocation (i.e. API request based pricing)
        • payments and recurring billing

        The end goals- First, reduce development time and have an easy to use API and libraries to provide the ability to check authentication, authorization, and resource usage with a single method call. Second, reduce support time by offering integrations with popular back office tools like Jira, Clubhouse, etc.

        1. 1

          Sounds great. In another thread, I just learned about userbase.com. How is it different than that?

          1. 1

            The primary difference is providing a comprehensive admin dashboard to manage and interface with the users.
            My product also handles the allocation of resource, user and group management, and the SaaS-centric features you'd find with the majority of services

  22. 1

    All my experiments are nodejs projects, and the "passport" library is pure gold for authentication.

    1. 1

      Just checked it out. The strategies look great.

      Can I use passport.js without a database?

      1. 1

        Not really. There are some you could use without a DB, but they would all be a sort of "shared login" type scheme. For example a HTTP basic with a predefined user/pass, or a Bearer token strategy with a fixed bearer token. But in general in order to look up a user and enforce a password, you will need some form of database.

  23. 1

    Firebase with FirebaseUI, really the best option out there.

    1. 2

      Can you tell me more about that? Why?

      1. 1

        Great documentation and an integrated login UI for web or apps. Doesn't take long at all to setup email/google/facebook login and everything just works.
        And it's free, no user limit.

        You don't need to use anything else from Firebase either.

        1. 1

          You don't need to use anything else from Firebase either

          Oh, that is great.

          What kind of framework did you implement it with - React, SPA, something else?

          1. 1

            Depends on the project. Usually Vue but sometimes just plain HTML if it's a simple project where SEO is important. Either way, Firebase is real easy.

            1. 1

              Nice. Good to hear it is easy even with a plain HTML page. What's 'easy' in this respect - a couple hours of your time, a couple days? I guess I'm wondering what I should expect to commit to using it.

              1. 1

                I've done it before so maybe a few hours but the first time it took a day or 2. That's everything including fine tuning and social logins.

  24. 1

    This comment was deleted 4 years ago.

  25. 1

    This comment was deleted 4 years ago.

Trending on Indie Hackers
I spent $0 on marketing and got 1,200 website visitors - Here's my exact playbook User Avatar 41 comments Why Early-Stage Founders Should Consider Skipping Prior Art Searches for Their Patent Applications User Avatar 22 comments I built eSIMKitStore — helping travelers stay online with instant QR-based eSIMs 🌍 User Avatar 20 comments Codenhack Beta — Full Access + Referral User Avatar 20 comments Veo 3.1 vs Sora 2: AI Video Generation in 2025 🎬🤖 User Avatar 18 comments Day 6 - Slow days as a solo founder User Avatar 13 comments