0

I have an Angular application making a CORS consuming of a rest api (Django Rest Framework). Now I want to GET all the user from http://127.0.0.1/api/users. I have already enabled my backend to allow cors request and I can get the data without problems if the django view is not been set any permission restrict (permission_classes = ()). But I will fail if there is permission restrict IsAdminUser. I can the user view with permission successfully in the browser if login in as admin. My question is how to let angular use csrftoken to consume the rest api with permission.

The UserList view:

# List all the users or create a new user
class UserList(generics.ListAPIView):
    queryset = User.objects.all()
    serializer_class = UserSerializer
    permission_classes = (IsAdminUser,)

The code in angular:

$httpProvider.defaults.xsrfCookieName = 'csrftoken';
$httpProvider.defaults.xsrfHeaderName = 'X-CSRFToken';
$httpProvider.defaults.withCredentils = true;

and:

.run(function run($http, $cookies){
    // For CSRF token compatibility with Django
    $http.defaults.headers.post['X-CSRFToken'] = $cookies.csrftoken;
}

The error:

Failed to load resource: the server responded with a status of 403 (Forbidden)
Scofield77
  • 917
  • 10
  • 16

1 Answers1

0

It depends on DRF authentication method. For example if you are using TokenAuthentication - you need to set token as default header:

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

Where token - user-specific token received from server.

zymud
  • 2,221
  • 16
  • 24
  • It doesn't work. I found there is a csrftoken in request header if I access the backend rest api directly from web browser. How coud I let my gulp served front-end Angular can use that token? About [angular-gulp-generator](https://www.google.co.in/url?sa=t&rct=j&q=&esrc=s&source=web&cd=1&ved=0CB0QFjAA&url=https%3A%2F%2Fgithub.com%2FSwiip%2Fgenerator-gulp-angular&ei=E9JlVd7UAtLmoATssYNY&usg=AFQjCNE0dt6R935EfRHM6QYGif948Jn4kg&sig2=Odqf7K-VaiX15R1nLk_4pg&bvm=bv.93990622,d.cGU) – Scofield77 May 27 '15 at 14:18
  • I found a similar [question](http://stackoverflow.com/questions/18156452/django-csrf-token-angularjs) But I still get the 403. – Scofield77 May 27 '15 at 15:25
  • 1. What type of request do you execute (GET or POST)? csrf is not related to GET request and cannot produce 403 exception. 2. What type of Authentication you are using on backend? – zymud May 29 '15 at 07:25
  • 1. GET. Why GET request cannot product 403 exception. I think it's a csrftoken issure. Because if i remove the permission limit from the django backend, I will get the right result. I can get the `csrftoken` using $cookies.csrftoken. But I don't know how to put it into the right position in the request header. 2. Using the default Django authentication like [this](https://docs.djangoproject.com/en/1.8/topics/auth/) – Scofield77 May 29 '15 at 12:06