mozilla / mozilla-django-oidc

A django OpenID Connect library
https://mozilla-django-oidc.readthedocs.io
Mozilla Public License 2.0
450 stars 168 forks source link

Documentation: How to get tokens to SPA? #341

Open TJHeeringa opened 4 years ago

TJHeeringa commented 4 years ago

I have a React single page application( SPA) on the same server that I have a Django Rest Framework RESTfull API. I want to implement OIDC for my setup. I can login directly on DRF just fine. I run into problems for my frontend in React. I logged in on my API using OIDC. Now I do a query like fetch('/server/api/get/stuff', {credentials: 'same-origin'}) to see how I need to query the API from the frontend, but I get a 401 Access Denied. How do I sent a request from the SPA to the django API using mozilla-django-oidc on the same domain?

I can give relevant settings (not sure which those are atm), if that helps.

akatsoulas commented 4 years ago

@johngian can you maybe take a look at this?

dannon commented 3 years ago

Is there a good example for how to do this yet? I have a Vue SPA client with a DRF backend (separate projects entirely, the static SPA won't be served by the django server) and I'm having a bit of trouble figuring out the right handshake.

TJHeeringa commented 3 years ago

I have the same case just with React as SPA. Both my SPA and DRF backend share the same domain (drf is on subdomain api.). My OIDC IdP supports the option to pass a redirect_url throught the oidc flow. In my frontend when logging in I make a fetch call to the DRF backend with mozilla-django-oidc. After the backend handles the oidc flow, I use the redirect_url to redirect back to the frontend. Every subsequent fetch call I authenticate with {credentials: 'same-origin'}. So far this seems to work (I did not notice any errors regarding this during development nor did I receive messages about errors from the users).

If you get errors because one is on the subdomain of the other like I have, they you might need to change some CORS settings using django-cors-headers. I don't recall whether I had errors which I needed to fix with CORS settings. If you place the DRF backend at /api this likely is not required.

Maybe a similar construction is suitable for you too.

paulsmirnov commented 3 years ago

+1, the same setup works for me also