title: In FastAPI Getting 'Not authenticated' Error after authenticate
body: <h1>File dir</h1>
  <blockquote>
  <p>fastapi_jwt</p>
  <blockquote>
  <p>.env
  main.py
  app</p>
  <blockquote>
  <p>api.py
  model.py
  auth</p>
  <blockquote>
  <p>auth_bearer.py
  auth_handler.py</p>
  </blockquote>
  </blockquote>
  </blockquote>
  </blockquote>
  <hr />
  <h3>fastapi_jwt/.env</h3>
  <pre><code>secret=please_please_update_me_please
  algorithm=HS256
  </code></pre>
  <hr />
  <h3>fastapi_jwt/main.py</h3>
  <pre><code>import uvicorn
  
  if __name__ == &quot;__main__&quot;:
      uvicorn.run(&quot;app.api:app&quot;, host=&quot;127.0.0.1&quot;, port=8000, reload=True)
  </code></pre>
  <hr />
  <h3>fastapi_jwt/app/api.py</h3>
  <pre><code>from fastapi import FastAPI, Body, Depends
  from starlette.responses import HTMLResponse
  
  from app.model import PostSchema, UserSchema, UserLoginSchema
  from app.auth.auth_bearer import JWTBearer
  from app.auth.auth_handler import signJWT
  
  app = FastAPI()
  
  @app.get(&quot;/&quot;, tags=[&quot;root&quot;])
  async def read_root():
      return {&quot;message&quot;: &quot;Welcome to your blog!.&quot;}
  
  from app.model import PostSchema
  
  posts = [
      {
          &quot;id&quot;: 1,
          &quot;title&quot;: &quot;Pancake&quot;,
          &quot;content&quot;: &quot;Lorem Ipsum ...&quot;
      }
  ]
  
  users = []
  
  @app.get(&quot;/posts&quot;, tags=[&quot;posts&quot;])
  async def get_posts() -&gt; dict:
      return { &quot;data&quot;: posts }
  
  
  @app.get(&quot;/posts/{id}&quot;, tags=[&quot;posts&quot;])
  async def get_single_post(id: int) -&gt; dict:
      if id &gt; len(posts):
          return {
              &quot;error&quot;: &quot;No such post with the supplied ID.&quot;
          }
  
      for post in posts:
          if post[&quot;id&quot;] == id:
              return {
                  &quot;data&quot;: post
              }
  @app.get(&quot;/post&quot;, dependencies=[Depends(JWTBearer())], tags=[&quot;posts&quot;])
  @app.post(&quot;/post&quot;, dependencies=[Depends(JWTBearer())], tags=[&quot;posts&quot;])
  async def add_post(post: PostSchema) -&gt; dict:
      post.id = len(posts) + 1
      posts.append(post.dict())
      return {&quot;result&quot;:&quot;Post added successfully&quot;}
  
  @app.post(&quot;/user/signup&quot;, tags=[&quot;user&quot;])
  async def create_user(user: UserSchema = Body(...)):
      users.append(user) # replace with db call, making sure to hash the password first
      return signJWT(user.email)
  
  def check_user(data: UserLoginSchema):
      for user in users:
          if user.email == data.email and user.password == data.password:
              return True
      return False
  
  @app.post(&quot;/user/login&quot;, tags=[&quot;user&quot;])
  async def user_login(user: UserLoginSchema = Body(...)):
      if check_user(user):
          return signJWT(user.email)
      return {
          &quot;error&quot;: &quot;Wrong login details!&quot;
      }
  </code></pre>
  <hr />
  <h3>fastapi_jwt/app/model.py</h3>
  <pre><code>from pydantic import BaseModel, Field, EmailStr
      
      
      class PostSchema(BaseModel):
          id: int = Field(default=None)
          title: str = Field(...)
          content: str = Field(...)
      
          class Config:
              schema_extra = {
                  &quot;example&quot;: {
                      &quot;title&quot;: &quot;Securing FastAPI applications with JWT.&quot;,
                      &quot;content&quot;: &quot;In this tutorial, you'll learn how to secure your application by enabling authentication using JWT. We'll be using PyJWT to sign, encode and decode JWT tokens....&quot;
                  }
              }    
      class UserSchema(BaseModel):
          fullname: str = Field(...)
          email: EmailStr = Field(...)
          password: str = Field(...)
      
          class Config:
              schema_extra = {
                  &quot;example&quot;: {
                      &quot;fullname&quot;: &quot;Abdulazeez Abdulazeez Adeshina&quot;,
                      &quot;email&quot;: &quot;abdulazeez@x.com&quot;,
                      &quot;password&quot;: &quot;weakpassword&quot;
                  }
              }
      
      class UserLoginSchema(BaseModel):
          email: EmailStr = Field(...)
          password: str = Field(...)
      
          class Config:
              schema_extra = {
                  &quot;example&quot;: {
                      &quot;email&quot;: &quot;abdulazeez@x.com&quot;,
                      &quot;password&quot;: &quot;weakpassword&quot;
                  }
              }
  </code></pre>
  <hr />
  <h3>fastapi_jwt/app/auth/auth_bearer.py</h3>
  <pre><code>from fastapi import Request, HTTPException
  from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
  
  from .auth_handler import decodeJWT
  
  
  class JWTBearer(HTTPBearer):
      def __init__(self, auto_error: bool = True):
          super(JWTBearer, self).__init__(auto_error=auto_error)
  
      async def __call__(self, request: Request):
          credentials: HTTPAuthorizationCredentials = await super(JWTBearer, self).__call__(request)
          if credentials:
              if not credentials.scheme == &quot;Bearer&quot;:
                  raise HTTPException(status_code=403, detail=&quot;Invalid authentication scheme.&quot;)
              if not self.verify_jwt(credentials.credentials):
                  raise HTTPException(status_code=403, detail=&quot;Invalid token or expired token.&quot;)
              return credentials.credentials
          else:
              raise HTTPException(status_code=403, detail=&quot;Invalid authorization code.&quot;)
  
      def verify_jwt(self, jwtoken: str) -&gt; bool:
          isTokenValid: bool = False
  
          try:
              payload = decodeJWT(jwtoken)
          except:
              payload = None
          if payload:
              isTokenValid = True
          return isTokenValid
  </code></pre>
  <hr />
  <h3>fastapi_jwt/app/auth/auth_handler.py</h3>
  <pre><code>import time
  from typing import Dict
  
  import jwt
  from decouple import config
  
  
  JWT_SECRET = config(&quot;secret&quot;)
  JWT_ALGORITHM = config(&quot;algorithm&quot;)
  
  
  def token_response(token: str):
      return {
          &quot;access_token&quot;: token
      }
  
  def signJWT(user_id: str) -&gt; Dict[str, str]:
      payload = {
          &quot;user_id&quot;: user_id,
          &quot;expires&quot;: time.time() + 600
      }
      token = jwt.encode(payload, JWT_SECRET, algorithm=JWT_ALGORITHM)
  
      return token_response(token)
  
  def decodeJWT(token: str) -&gt; dict:
      try:
          decoded_token = jwt.decode(token, JWT_SECRET, algorithms=[JWT_ALGORITHM])
          return decoded_token if decoded_token[&quot;expires&quot;] &gt;= time.time() else None
      except:
          return {}
  </code></pre>
  <p>I run 'main.py', the url
  &quot; <a href="http://127.0.0.1:8000/post" rel="nofollow noreferrer">http://127.0.0.1:8000/post</a> &quot; shows the output &quot;{&quot;detail&quot;:&quot;Not authenticated&quot;}&quot;.
  So go to the url &quot; <a href="http://127.0.0.1:8000/docs" rel="nofollow noreferrer">http://127.0.0.1:8000/docs</a> &quot; for FastAPI -Swagger UI interface like
  <a href="https://i.stack.imgur.com/WMqs6.png" rel="nofollow noreferrer">this</a>.
  Then I signup and login to get the jwt token and use that token to <a href="https://i.stack.imgur.com/qo21M.png" rel="nofollow noreferrer">authenticate</a>, then go to url
  &quot; /post &quot; in FastAPI -Swagger UI and execute to get the output <a href="https://i.stack.imgur.com/7ftJU.png" rel="nofollow noreferrer">{&quot;result&quot;: &quot;Post added successfully&quot;}</a>.
  But in &quot; <a href="http://127.0.0.1:8000/post" rel="nofollow noreferrer">http://127.0.0.1:8000/post</a> &quot; got an error and show the same ouput &quot;{&quot;detail&quot;:&quot;Not authenticated&quot;}&quot;</p>