DEV Community

Cover image for Authentication in Tests with DRF
Mangabo Kolawole
Mangabo Kolawole Subscriber

Posted on

Authentication in Tests with DRF

Writing tests with Django and Django REST is made easier with the tools and classes provided.
And if you are writing tests to test the endpoints of your API, using the APIClient class from Django REST is a simple way to write the tests and make requests.

And if you are looking to test a protected resource, you can directly use the .login(**kwargs) method.

client = APIClient()
client.login(username='john', password='12345')
Enter fullscreen mode Exit fullscreen mode

And if you want to bypass the authentication process without having to provide a username or password, you can use the .force_authenticate(user=None)

user = User.objects.first()
client = APIClient()
client.force_authenticate(user=user)
Enter fullscreen mode Exit fullscreen mode

Article posted using bloggu.io. Try it for free.

Top comments (3)

Collapse
 
sm0ke profile image
Sm0ke

We have a DRF expert here ..

Collapse
 
koladev profile image
Mangabo Kolawole

😎😎😎

Collapse
 
harihararamsriram profile image
Harihararam Sriram

Thanks for this small and concise article! I have a question, let's say I have created an API using DRF with authentication that only allows authenticated users to access the data offered by the API endpoints. To achieve this I use permission classes and when we access those end points from the browser we will be able to login via the DRF's GUI and on successful authentication we can access the data.
How will I authenticate my frontend (like React) to fetch the same data? I have used Postman in which you can authenticate by sending a CSRF token along with the credentials, to the endpoint and it works. CSRF Token is necessary along with the login credentials for successful login.
In React single page applications the frontend is independent from the backend (here, DRF); how to make the CSRF token available to React or is there any way to make authentication possible in this scenario?
I would love to learn your perspective about this.