JWT Authentication – FastAPI Beyond CRUD (Part 10)
In this article, we will explore how to protect endpoints with JSON Web Token (JWT) authentication in FastAPI.
What is JWT Authentication?
JWT authentication is a method of securing APIs by using JSON Web Tokens. JWTs are compact, URL-safe tokens that encode a JSON payload and are digitally signed. They can be used to authenticate and authorize users accessing APIs.
Implementing JWT Authentication in FastAPI
First, we need to install the necessary dependencies for FastAPI to support JWT authentication:
$ pip install fastapi[all] python-jose
Next, we need to generate a secret key that will be used to sign and verify JWT tokens:
$ openssl rand -hex 32
We can then create a utility function to generate JWT tokens:
def create_access_token(data: dict, secret_key: str, algorithm: str = "HS256") -> str:
encoded_jwt = jwt.encode(data, secret_key, algorithm=algorithm)
return encoded_jwt
Finally, we can protect our endpoints by requiring a valid JWT token in the HTTP Bearer Authorization header:
from fastapi import Depends, HTTPException, status
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
security = HTTPBearer()
@app.get("/protected")
def protected_route(credentials: HTTPAuthorizationCredentials = Depends(security)):
token = credentials.credentials
try:
payload = jwt.decode(token, SECRET_KEY, algorithms=["HS256"])
except jwt.JWTError:
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid token")
Conclusion
JWT authentication is a powerful way to secure APIs and protect endpoints in FastAPI. By using JWT tokens, we can authenticate and authorize users accessing our APIs in a secure and efficient manner.
Hi everyone, Kindly help me leave a like on this video. It help this video go to many people. Thanks in advance. See you in the next one.
Why is there no token expiration date check?
No arguments were passed to the self.token_valid method. This `if self.token_valid:` check always returns True
Very good tutorial for us beginners. Thank you very much Ssali. I am getting this error [ File "D:PythonREST_APIsrcauthdependencies.py", line 65, in _call_
if token_data['refresh']:
~~~~~~~~~~^^^^^^^^^^^
TypeError: string indices must be integers, not 'str' ] from the following code:
if token_data['refresh']:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Please provide an access token"
)
can you tell me about your vs code theme name?? its very beautiful
😃