Community Posts
September 18, 2024

Make Your FastAPI App Secure with Userfront

This post was originally published on hashnode.dev.

Python devs this is for you! In this article, I’ll show you how to simplify authentication in your fast API app using a neat little tool called Userfront. It helps you set up things like sign-ups, logins, and password resets without having to build everything yourself.

Let's get started and set up your app with some solid user security! 🔐

What You'll Need

Before we jump in, let's make sure you have everything you need. Open up your command prompt or terminal and type in:

pip install fastapi uvicorn PyJWT

This will install FastAPI for your backend, uvicorn to run your app, and PyJWT to help with those secure tokens Userfront uses.

Step 1: Set Up a Basic FastAPI App

First things first, let's create a simple FastAPI app. If you haven't made one before, here's a quick way to do it:

from fastapi import FastAPI

app = FastAPI()

@app.get("/")
async def read_root():
    return {"message": "Welcome to the FastAPI app"}

To get this running, type this in your terminal:

uvicorn main:app --reload

Now, if you go to http://127.0.0.1:8000/ in your web browser, you should see a message saying "Welcome to the FastAPI app."

Step 2: Add User Login Checks

When someone signs up or logs in using Userfront, they get a special token (called a JWT) that proves who they are. We're going to use these tokens to make sure only the right people can access certain parts of your app.

Setting Up Token Checks

We need to make sure these tokens are real. Here's how we can do that in FastAPI:

from fastapi import Depends, HTTPException
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
from jose import JWTError, jwt

app = FastAPI()

# You'll get this key from your Userfront account page
USERFRONT_PUBLIC_KEY = "your-userfront-public-key"

security = HTTPBearer()

def check_token(credentials: HTTPAuthorizationCredentials = Depends(security)):
    token = credentials.credentials
    try:
        # We check if the token is real using your Userfront public key
        decoded_token = jwt.decode(token, USERFRONT_PUBLIC_KEY, algorithms=["HS256"])
        return decoded_token  # If it's real, we send back the token info
    except JWTError:
        raise HTTPException(status_code=401, detail="Sorry, that's not a valid login token")

This code looks at the token and makes sure it's real. If it's not, it tells the user they're not allowed in.

Protecting Your App's Pages

Now, let's use this to keep certain pages safe:

@app.get("/dashboard")
async def dashboard(user: dict = Depends(check_token)):
    return {"message": "Welcome to your dashboard!", "user": user}

With this setup, when someone tries to visit the dashboard page, they'll need to have a valid login token. If their token checks out, they'll see their personal dashboard.

Step 3: Adding Userfront to Your Website

Userfront gives you ready-made forms for signing up, logging in, and resetting passwords. You can easily add these to your website if you're using something like React or Vue.js.

Here's a quick example of how you'd add a sign-up form in React:

import { SignupForm } from "@userfront/react";

export default function SignupPage() {
  return <SignupForm />;
}

Once people sign up, Userfront takes care of creating and storing their login tokens. All you need to do is check those tokens on your FastAPI backend, which we set up earlier.

Step 4: Extra Security

Want to make sure only certain users can do specific things in your app? Userfront makes it easy to set up user roles. You can use these roles to control who gets to access different parts of your FastAPI app.

For example, if you want to make a page that only admins can see:

def check_token(credentials: HTTPAuthorizationCredentials = Depends(security)):
    token = credentials.credentials
    try:
        decoded_token = jwt.decode(token, USERFRONT_PUBLIC_KEY, algorithms=["HS256"])
        roles = decoded_token.get("authorization", {}).get("roles", [])
        if "admin" not in roles:
            raise HTTPException(status_code=403, detail="Sorry, you don't have permission to see this")
        return decoded_token
    except JWTError:
        raise HTTPException(status_code=401, detail="Sorry, that's not a valid login token")

With this setup, only users who have been marked as admins will be able to access the page.

Wrapping Up

And there you have it! You've now added secure user accounts to your FastAPI app using Userfront. With just a bit of code, you can handle sign-ups, logins, and even control who gets to see what in your app.

Userfront does a lot of the hard work for you, so you can focus on making your app awesome. 🚀

Feel free to explore more of what Userfront can do, like helping users reset passwords, setting up different user roles, or even adding extra security with two-factor authentication.

Good luck with your app! If you have any questions, don't hesitate to ask. Happy coding! 👨‍💻👩‍💻

Related

UserFront - The King of Authentication

Managing user authentication and access control has long been a complex and time-consuming challenge for developers. Often consuming a disproportionate amount of development resources.According to a 2023 survey by SlashData, developers spend an average of 25% of their time on security-related tasks, with authentication and access control being major components of this effort.
November 13, 2024
By 
Scofield Idehen
Community Posts

Elevate Your Next.js Security: Middleware Authorization with Userfront

In this guide, I will show you how to secure your Next.js application with Userfront by implementing middleware-level authorization and leaving component authorization practices.
October 11, 2024
By 
Syed Muhammad Yaseen
Community Posts

Make Your FastAPI App Secure with Userfront

This post was originally published on hashnode.dev.Python devs this is for you! In this article, I’ll show you how to simplify authentication in your fast API app using a neat little tool called Userfront. It helps you set up things like sign-ups, logins, and password resets without having to build everything yourself.
September 18, 2024
By 
Omu Inetimi
Community Posts