How can I authenticate a user who belongs to another database through my other microservice in django rest framework?

Viewed 55

I'm new to django and I am required to create two microservices with separate databases;

One to hold user information and the other to hold todo/tasks information. So far, I have created two separate projects with two separate databases,

  1. To authenticate the user using simplejwt authentication. (todo_auth project with todo_auth database)
  2. To show the todo/task information specific to that user. (todo project with todo database)

I need the todo project to verify the token by routing it back to the todo_auth project, and then I need the todo_auth project to send a response to the todo project. (By specifying the port)

How can I achieve this? Many thanks.

PS: I'm running the two django projects on the same server with different port numbers.

1 Answers

Simple JWT provides a verify route that you can pass a token to which will validate it was singed by the server and it is not expired.

From the documentation:

You can also include a route for Simple JWT’s TokenVerifyView if you wish to allow API users to verify HMAC-signed tokens without having access to your signing key:

from rest_framework_simplejwt.views import TokenVerifyView

urlpatterns = [
   ...
   path('api/token/verify/', TokenVerifyView.as_view(), name='token_verify'),
   ...
]

If you want to do some other logic you should just write a normal view, use the JWT auth provided, and have the other one forward the token in the request

# todo-project
class ToDoView(APIView):
   def get(self, request):
       auth = request.headers["authorization"]
       response = requests.get(
           "http://todo-auth.sevice.com/api/do-thing/", 
           headers={
               "Authorization": auth
           }
       )
       if response.status_code = 200: 
           do_something(response.json())

# todo-auth-service 
class DoThing(APIView):
    authentication_classes = [JWTAuthentication]
    def get(self, request):
        ...
Related