0

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.

1
  • You need to enable CORS on your webserver because making a ajax call from javascript you should have CORS enabled on the server Commented Oct 11, 2017 at 14:44

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

0

Add a proxy.config.json file to your app root folder.

proxy.config.json

{

   "/backend-api-domain-name/*": {

      "target": "http:localhost:[port_number]",

      "changeOrigin": true

   }

}

when you start your ionic application, you need to specify the proxy file ng serve --proxy-config proxy.config.json

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.