401 Not Authorized for 'mozilla_django_oidc.contrib.drf.OIDCAuthentication' authenticate()

The django logs that are comming up are:

DJANGO [2020-11-27 19:55:14.894] DEBUG [urllib3.connectionpool:452] http://keycloak:8080 "GET /auth/realms/Clarsynt/protocol/openid-connect/certs HTTP/1.1" 200 1466
DJANGO [2020-11-27 19:55:14.919] DEBUG [urllib3.connectionpool:227] Starting new HTTP connection (1): keycloak:8080
DJANGO [2020-11-27 19:55:14.926] DEBUG [urllib3.connectionpool:452] http://keycloak:8080 "GET /auth/realms/Clarsynt/protocol/openid-connect/userinfo HTTP/1.1" 401 73
*** requests.exceptions.HTTPError: 401 Client Error: Unauthorized for url: 
http://keycloak:8080/auth/realms/Clarsynt/protocol/openid-connect/userinfo

The keycloak logs:

20:01:02,746 WARN  [org.keycloak.events] (default task-2) type=USER_INFO_REQUEST_ERROR, realmId=Clarsynt, clientId=null, userId=null, ipAddress=172.20.0.7, error=invalid_token, auth_method=validate_access_token

I am using the settings as described in the mozilla_django_oidc package. I am trying to use Keycloak OAuth2 authentication for my django app. Keycloak and Django are running in separate containers. Can somebody please tell me why I am getting the 401 error?

this is the relevant portion of my docker-compose file:

  keycloak:
      image: jboss/keycloak
      environment:
        DB_VENDOR: POSTGRES
        DB_ADDR: db
        DB_DATABASE: postgres
        DB_USER: postgres
        DB_SCHEMA: public
        DB_PASSWORD: webapp-devel
        KEYCLOAK_USER: myuser
        KEYCLOAK_PASSWORD: *******
        KEYCLOAK_IMPORT: /tmp/realm-export.json
      ports:
        - 9990:8080
  webapp:
    command: ./manage.py runserver 0.0.0.0:8000
    depends_on:
      - db
    environment:
      PORT: "8000"
      DEBUG: "True"

Hi,

Did you already checked the client and secret on django?

20:01:02,746 WARN  [org.keycloak.events] (default task-2) type=USER_INFO_REQUEST_ERROR, realmId=Clarsynt, clientId=null, userId=null, ipAddress=172.20.0.7, error=invalid_token, auth_method=validate_access_token

clientId is null and user id also, and gives invalid token.

yes, I did. I think it is working this way because it is making a request to keycloak:8080, but the jwt has the url localhost:9990 which is the frontend url. This problem has still not been fixed

So, the keycloak open other ports, is not just 8080, maybe this is not the error.

Try to authenticate on postman with the same data, in 8080 port.

POST : http://keycloak:8080/auth/realms/master/protocol/openid-connect/token
grant_type > client_credentials
client_id >
client_secret >

try it :slight_smile: