Facebook Auth with AngularJS and Django REST Framework

前端 未结 3 753
别那么骄傲
别那么骄傲 2021-01-30 07:25

I am developing a SPA application with AngularJS which uses Django backend for the server. The way that I communicate with the server from the SPA is with django-rest-framework.

3条回答
  •  孤街浪徒
    2021-01-30 07:59

    Add the following line to your ObtainAuthToken class

    authentication_classes = ()
    

    and your error {"detail": "Invalid token"} will go away.

    Here's why...

    Your request contains the following header

    Authorization: Token yourAccessToken
    

    yet you have defined rest_framework.authentication.TokenAuthentication in DEFAULT_AUTHENTICATION_CLASSES.

    Based on this Django thinks you want to perform token authentication as you have passed a Token in. It fails because this is an access token for facebook and doesn't exist in your django *_token database, hence the invalid token error. In your case all you need to do is tell Django not to use TokenAuthentication for this view.

    FYI

    Keep in mind you may encounter further errors as your code execution was halted before the post method of ObtainAuthToken executed. Personally when trying to step through your code I got the error

    'DjangoStrategy' object has no attribute 'backend'
    

    on

    backend = request.strategy.backend
    

    and resolved it by changing to

    uri = ''
    strategy = load_strategy(request)
    backend = load_backend(strategy, backend, uri)
    

    Additionally you should update your you register_by_access_token function as it doesn't line up with the working code from the blog you referenced. The blog author posted his latest code here. Your version doesn't pull the token out of the auth header which is required if you want to use it to auth with a third party like facebook.

提交回复
热议问题