Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Rest Framework JWT Authentication Test

I'm setting up DRF to work with JWT Token Authentication. I seem to be at a point that DRF-JWT says that it's working correctly, but I can't get a login test to successfully run.

I've gone through the installation steps in the django-rest-framework-jwt docs and I am able to successfully run the curl $ curl -X POST -d "username=admin&password=abc123" http://localhost:8000/api-token-auth/ and get back a token.

I am expecting my test to pass me back a token as well, but apparently I don't have it set up right.

# tests.py
class LoginTests(APITestCase):
    def setUp(self):
        self.user = NormalUserFactory.create()
        self.jwt_url = reverse('jwt_login')

    def test_token_get_not_allowed(self):
        # do not allow GET requests to the login page
        response = self.client.get(self.jwt_url)
        self.assertEqual(response.data.get('detail'), 'Method "GET" not allowed.')

    def test_token_login_fail_incorrect_credentials(self):
        # pass in incorrect credentials
        data = {
            'username': self.user.username,
            'password': 'inCorrect01'
        }
        response = self.client.post(self.jwt_url, data)
        self.assertEqual(response.data.get('non_field_errors'), 
            ['Unable to login with provided credentials.'])

    def test_token_login_success(self):
        data = {
            'username': self.user.username,
            'password': 'normalpassword',
        }
        response = self.client.post(self.jwt_url, data)
        print(response.data.get("token"))
        self.assertNotEqual(response.data.get("token"), None)

The first two unittests run successfully, but the third will not return the token, but instead returns {'non_field_error':'Unable to login with provided credentials.'}, what I'm expecting when the credentials are incorrect.

To create the User instance (and other model instances) I am using factory_boy. This same method to create instances works in other apps within this project, as well as other projects, and I have verified the user does exist in the test database.

# factories.py
class UserFactory(DjangoModelFactory):
    class Meta:
        model = User

    native_language = 'es'


class NormalUserFactory(UserFactory):
    username = 'normaluser'
    password = 'normalpassword'
    email = '[email protected]'
    first_name = 'John'
    last_name = 'Doe'

here are my relevant settings as well:

# settings.py
REST_FRAMEWORK = {
    'API_ROOT': '/v1/',
    'TEST_REQUEST_DEFAULT_FORMAT': 'json',
    # Use Django's standard `django.contrib.auth` permissions,
    # or allow read-only access for unauthenticated users.
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.AllowAny',
    ],
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.BasicAuthentication',
        'rest_framework.authentication.SessionAuthentication',
        'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
    ),
}

JWT_AUTH = {
    'JWT_EXPIRATION_DELTA': datetime.timedelta(days=14)
}
like image 616
awwester Avatar asked Mar 27 '15 21:03

awwester


1 Answers

Try the following code:

tests.py

class LoginTests(APITestCase):
    def setUp(self):
        self.user = NormalUserFactory.create()
        self.jwt_url = reverse('jwt_login')    
    def test_post_form_failing_jwt_auth(self):
            """
            Ensure POSTing form over JWT auth without correct credentials fails
            """
            data = {
                'username': self.user.username,
                'password': 'inCorrect01'
            }
            response = self.client.post(self.jwt_url, data)
            self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
like image 123
Seenu S Avatar answered Oct 04 '22 06:10

Seenu S