0

i am using django + angular 2

i am using rest_framework_jwt with a url like this

url(r'^api/api-token-auth/', obtain_jwt_token), 
url(r'^api/settings/?$', views.SettingsValues.as_view()),

My view is

class SettingsValues(generics.ListAPIView):
    serializer_class = SettingsSerializer
    permission_classes = (permissions.IsAuthenticatedOrReadOnly,)

    def get_queryset(self):
        queryset = Settings.objects.all()
        queryset = queryset.filter(user=self.request.user.id)
        print self.request.user
        return queryset

My service is:

  getSettings() : Promise <SettingsValues> {
      return this.http.get('/api/settings', { headers: this.headers })
      .toPromise()
      .then(response => response.json() as SettingsValues);

}

My login is working fine, but i cannot return the settings from django..

The print inside def get_queryset shows AnonymousUser.

Any idea what i am doing wrong ?

EDIT

  private headers = new Headers({
    'Content-Type': 'application/json',
    'Accept': 'application/json',
  });

1 Answers1

0

After obtaining the token from server, you have to save it and send in the header of subsequent api calls. Something like this:

getSettings() : Promise <SettingsValues> {
  this.headers.append('Authorization', 'JWT ' + token);
  return this.http.get('/api/settings', { headers: this.headers })
  .toPromise()
  .then(response => response.json() as SettingsValues);
}

In Angular 1.x.x, i can add this to cache Authorization Header for all subsequent api calls.

$http.defaults.headers.common.Authorization = 'JWT ' + token`;

In Angular 2, I am not sure how to cache it for all but take a look at this answer

Community
  • 1
  • 1
Nathan Do
  • 1,985
  • 19
  • 24
  • so simple ? damn it.. thank you very much! indeed i use let currentUser = JSON.parse(localStorage.getItem('currentUser')); and after this.headers.append('Authorization', 'JWT ' + currentUser.token); –  Feb 17 '17 at 17:20