I set up a little django app with mozilla-django-oidc. As OIDC server I use keycloak. All works fine and I can login with a keycloak user.
Now, my next step is to add an api to my model. I use django-restframework to do that. I have implemented a small test to create and read objects. Tests are running fine.
My next step is to add permissions to API. I use permission_classes = (permissions.IsAuthenticated) to do that. As expected tests are failing.
But how can I add the login/ get a token to access the API?
I'm looking for something like that
user = User.objects.create_user(example_username)
token = user.auth(credentials)
response = self.client.get(reverse(foo:bar),
HTTP_AUTHORIZATION=Bearer {token}
)
Thanks in advance
There is a
contrib/drf.pyfile inside of this library. But it was not done for this usage as the main target, and very few controls are mode on the access token received.You can check some of the issues on that:
When using DRF you are not in the classical
confidentialfull mode of OIDC, your are in thebearer-onlymode of Keycloak. Because for a REST API there is no login screen, no login process, no redirection to the SSO server. If the token is invalid you need to send an invalid HTTP code, not a redirect-to-soo-login.Usually the login comes from somewhere else (a confidential application, or a public front-only js app) and the access token is used against the DRF API.
A good practice is to use a different client_id for this DRF API side of your application.
Now, for your tests, you will need to obtain a token, to use it against the API, one way to do it is to use a 'service account' in keycloak, then use this service account with client_id/client_secret against Keycloak (use a POST on
/realms/<real name>/protocol/openid-connect/tokenwithgrant_type=client_credentialsand the client id and secret as credentials) and you will receive a valid access token (without a refresh token which is not required for service accounts). depending on your Keycloak version they may be differences in the way to generate this service account, but you should easily find docs on the right way to do it. once the received access token is outdated just redo the login query against keycloak to get a new one (no refresh token things to bother about).