Search code examples
javascriptpythonangularionic-framework

How to do HTTP Basic Auth using angular


I'm building ionic app with django rest framework backend, And I can't do simple http basic auth.

backend view:

class GetActive(APIView):
    permission_classes = (permissions.IsAuthenticated,)

    def get(self, request):
        settings = Setting.objects.filter(active=True)
        for setting in reversed(settings):
            headers = {'Access-Control-Allow-Origin': '*'}
            return Response({
                'youtube_link': setting.youtube_link,
                'text': setting.text}, headers=headers)
        return HttpResponse('not found')

frontend api.ts:

@Injectable()
export class ApiProvider {
  url;

  constructor(public http: Http) {
    this.url = 'http://127.0.0.1:8000/get_active/';
  }

  getSettings() {
    var auth = window.btoa("foo:bar"),
        headers = {"Authorization": "Basic " + auth};
    return this.http.get(this.url, {headers: headers}).map(res => res.json());
  }
}

I'm getting this error:

403 forbidden No 'Access-Control-Allow-Origin' header is present on the requested resource.

However, if I remove IsAuthenticated permisson on backend and remove headers from frontend request then it's working.

To be confident that it is indeed working when IsAuthenticated is on, I make this python script:

import requests
from requests.auth import HTTPBasicAuth

theurl = 'http://localhost:8000/get_active'
username = 'foo'
password = 'bar'

r = requests.get(theurl, auth=HTTPBasicAuth(username, password))
print (r.text)

And it is working fine, so I just need js analog.


Solution

  • Add CORS to the server. pip install django-cors-headers and add header maybe this help