Unable to make authentication of views with Simple JWT in Django REST framework working - Stack Overflow

admin2025-05-01  1

Thank you for looking at this question: I have already spent so many hours trying to authenticate DRF views using Simple JWT. Can anybody look at my code and tell me what is wrong?

Settings:

"REST_FRAMEWORK = {
(...)
'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework_simplejwt.authentication.JWTAuthentication',
],
'DEFAULT_PERMISSION_CLASSES': (
    'rest_framework.permissions.IsAuthenticated',
),


SIMPLE_JWT = {
'ACCESS_TOKEN_LIFETIME': timedelta(days=1),
'REFRESH_TOKEN_LIFETIME': timedelta(days=1),
'AUTH_HEADER_TYPES': ('JWT',)

}

urls:

 `path('listJob', views.JobListView.as_view(), name='listJob'),
(...)
 path('token/create/', TokenObtainPairView.as_view(), name='token_create'),
 path('token/refresh/', TokenRefreshView.as_view(), name='token_refresh'),
 path('token/verify/', TokenVerifyView.as_view(), name='token_verify'),

Views:

class JobListView(SingleTableMixin, FilterView, APIView ):
model = Job
table_class = JobTable
template_name = 'jobs/list_jobs.html'  
filterset_class = JobFilter
search_fields = ['title']  
ordering_fields = ['-evaluate_on', 'title']

I have used somebody else Ajax call to take care of the token process:

<script>
    $(document).ready(function () {


    $.ajax({
        url: 'http://127.0.0.1:9001/candidateevaluator/listJob/',
        headers: {
            'Authorization': `JWT ${window.localStorage.getItem('accessToken')}`
        },
        type: "GET",
        cache: false,
        tokenFlag: true,
        success: function (data) {
            alert('success = ' + data);
        },
        error: handleAjaxError
    }); // end ajax
});

function handleAjaxError(rs, e) {
    if (rs.status == 401) {
        if (this.tokenFlag) {
            this.tokenFlag = false;
            if (obtainAccessTokenWithRefreshToken()) {
                this.headers["Authorization"] = `JWT ${window.localStorage.getItem('accessToken')}`
                $.ajax(this);  // calling API endpoint again with new access token
            }
        }
    } else {
        alert("rs.responseText= " + rs.responseText);
    }
}

function obtainAccessTokenWithRefreshToken() {
    /*
        This method will create new access token by using refresh token.
        If refresh token is invalid it will redirect user to login page
    */
  
    let flag = true;
    let formData = new FormData();
    formData.append('refresh', window.localStorage.getItem('refreshToken'));
    $.ajax({
        url: 'token/refresh/',
        type: "POST",
        data: formData,
        async: false,
        cache: false,
        processData: false,
        contentType: false,
        success: function (data) {
            alert('success a new access token has been obtained = ' + data['access'])
            window.localStorage.setItem('accessToken', data['access']);
        },
        error: function (rs, e) {
            alert ('error in the obtaining a new access token')
            if (rs.status == 401) {
                flag = false;
                window.localStorage.removeItem('refreshToken');
                window.localStorage.removeItem('accessToken');
                window.location.href = "/login/";
            } else {
                alert('error = '+rs.responseText);
            }
        }
    }); // end ajax
    alert('returning the flag = ' + flag)
    return flag
}
  </script>

What I am getting is:

GET /candidateevaluator/listJob HTTP 401 Unauthorized Allow: GET, HEAD, OPTIONS Content-Type: application/json Vary: Accept WWW-Authenticate: JWT realm="api"

{ "detail": "Authentication credentials were not provided." }

  • I can access the pages correctly using the Mod Header choosing Authorization JWT + access token

  • the login page correctly adds the Access token to the window.localStorage

    $(document).ready(function() { $("#login-form").submit(function (event) {
    event.preventDefault(); let formData = new FormData(); formData.append('username', $('#id_username').val().trim()); formData.append('password', $('#id_password').val().trim()); $.ajax({ url: "token/create/", type: "POST", data: formData, cache: false, processData: false, contentType: false, success: function (data) { alert("success token stored in localStorage ") // store tokens in localStorage window.localStorage.setItem('refreshToken', data['refresh']); window.localStorage.setItem('accessToken', data['access']); alert("access token stored = " +window.localStorage.getItem('accessToken')); window.location.href = "listJob"; }, error: function (rs, e) { alert("success token NOT stored in localStorage ") console.error(rs.status); console.error(rs.responseText); } }); // end ajax }); });

Any help would be appreciated.

转载请注明原文地址:http://www.anycun.com/QandA/1746109951a91805.html