keycloak spring boot always receives Anonymous Authentication token

Viewed 856

Im using keycloak spring boot adapter version 10.0.2 and I am trying to get the username using the authentication token, for that I created a web filter and trying to get the Principal but although the user is authenticated I only get Anonymous user like this:

org.springframework.security.authentication.AnonymousAuthenticationToken@81a4f960: 
Principal: anonymousUser; 
Credentials: [PROTECTED]; Authenticated: true; 
Details: org.springframework.security.web.authentication.WebAuthenticationDetails@0: 
RemoteIpAddress: 10.128.15.244; 
SessionId: 6F41901438BFC9AD6FEEB34A3A6926EB; 
Granted 
Authorities: ROLE_ANONYMOUS

I have the following application.yaml

cheques.paging.size: 10
spring.jpa.hibernate.ddl-auto: none
spring.jpa.hibernate.use-new-id-generator-mappings: FALSE
spring.datasource.url: "jdbc:oracle:thin:@${db_host}:${db_port}/${db_instance}"
spring.datasource.username: "${db_user}"
spring.datasource.password: "${db_password}"
spring.datasource.driver.class: "${db_driver}"
spring.jpa.properties.hibernate.dialect: "org.hibernate.dialect.Oracle10gDialect"
spring.jpa.hibernate.naming.physical-strategy: "org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl"
management.health.ldap.enabled: false
management.endpoints.enabled-by-default: false
management.endpoint.health.enabled: true

keycloak:
  realm: mrdc
  auth-server-url: ${keycloak_url}
  ssl-required: external
  principal-attribute: preferred_username
  disableTrustManager: true
  allow-any-hostname: true
  resource: mrdc-client
  cors: true
  credentials:
    secret: secret
  securityConstraints:
    - securityCollections:
        - name: default
          patterns:
            - /*
      authRoles:
        - user
  policy-enforcer-config:
    lazy-load-paths: false
    enforcement-mode: ENFORCING
    paths:
      - name: actuator
        path: /actuator/*
        enforcement-mode: DISABLED
        methods:
          - method: GET

I really want to know what I've done wrong,I mean I have used keycloak before and used a similar web filter and always got the username like this:

public class CustomerFilter extends GenericFilterBean {
    private static final Logger LOGGER = LoggerFactory.getLogger(CustomerFilter.class);

    @Override
    public void doFilter(ServletRequest servletRequest,
                         ServletResponse servletResponse,
                         FilterChain filterChain) throws IOException, ServletException {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        Principal userPrincipal = httpServletRequest.getUserPrincipal();
        if (userPrincipal != null) {
            userPrincipal.getName();
            LOGGER.info("username: " + userPrincipal);
        }
        filterChain.doFilter(servletRequest, servletResponse);
    }
}

and here is my keycloak realm.json file in case that helps:

{
  "realm": "mrdc",
  "displayName": "PS-mRDC",
  "enabled": true,
  "requiredCredentials": [
    "password"
  ],
  "users": [
    {
      "username": "service-account-mrdc",
      "enabled": true,
      "serviceAccountClientId": "mrdc-client",
      "clientRoles": {
        "mrdc-client": [
          "uma_protection"
        ]
      }
    },
    {
      "username": "mrdc.user",
      "enabled": true,
      "credentials": [
        {
          "type": "password",
          "value": "mrdc"
        }
      ],
      "realmRoles": [],
      "groups": [
        "user-group"
      ]
    },
    {
      "username": "admin.user",
      "enabled": true,
      "credentials": [
        {
          "type": "password",
          "value": "admin"
        }
      ],
      "realmRoles": [],
      "groups": [
        "user-group",
        "admin-group"
      ]
    }
  ],
  "roles": {
    "realm": [
      {
        "name": "user"
      }
    ]
  },
  "groups": [
    {
      "name": "user-group",
      "path": "user-group",
      "attributes": {},
      "realmRoles": [
        "user"
      ],
      "clientRoles": {
        "account": [
          "view-profile",
          "manage-account"
        ]
      },
      "subGroups": []
    },
    {
      "name": "admin-group",
      "path": "admin-group",
      "attributes": {},
      "realmRoles": [
        "user"
      ],
      "clientRoles": {
        "account": [
          "view-profile",
          "manage-account"
        ],
        "realm-management": [
          "view-users",
          "view-realm",
          "view-clients",
          "manage-users"
        ]
      },
      "subGroups": []
    }
  ],
  "scopeMappings": [
    {
      "client": "mrdc-client",
      "roles": [
        "user"
      ]
    },
    {
      "clientScope": "offline_access",
      "roles": [
        "offline_access"
      ]
    }
  ],
  "clients": [
    {
      "clientId": "mrdc-client",
      "rootUrl": "",
      "baseUrl": "",
      "enabled": true,
      "redirectUris": [
        "https://*"
      ],
      "secret": "secret",
      "fullScopeAllowed": false,
      "directAccessGrantsEnabled": true,
      "authorizationServicesEnabled": true,
      "authorizationSettings": {
        "allowRemoteResourceManagement": false,
        "policyEnforcementMode": "ENFORCING",
        "resources": [
          {
            "name": "Default Resource",
            "uri": "/*"
          }
        ],
        "policies": [
          {
            "name": "Default Policy",
            "description": "A policy that grants access only for users within this realm",
            "type": "js",
            "logic": "POSITIVE",
            "decisionStrategy": "AFFIRMATIVE",
            "config": {
              "code": "// by default, grants any permission associated with this policy\n$evaluation.grant();\n"
            }
          },
          {
            "name": "Only User Role Policy",
            "type": "role",
            "logic": "POSITIVE",
            "decisionStrategy": "UNANIMOUS",
            "config": {
              "roles": "[{\"id\":\"user\",\"required\":false}]"
            }
          },
          {
            "name": "User Permission",
            "type": "resource",
            "logic": "POSITIVE",
            "decisionStrategy": "UNANIMOUS",
            "config": {
              "resources": "[\"Default Resource\"]",
              "applyPolicies": "[\"Only User Role Policy\"]"
            }
          }
        ],
        "scopes": [
          "view"
        ]
      }
    }
  ]
}
0 Answers
Related