keycloak spring boot始终接收匿名身份验证令牌

问题描述

我正在使用keycloak spring boot adapter版本10.0.2,并且我尝试使用身份验证令牌获取用户名,为此,我创建了一个Web过滤器并尝试获取Principal,但是尽管该用户已通过身份验证,但我仅获得了匿名用户像这样:

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

我有以下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

我真的很想知道自己做错了什么,我的意思是我以前使用过keycloak并使用过类似的Web过滤器,并且总是得到这样的用户名:

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);
    }
}

这是我的keycloak realm.json文件,以防万一:

{
  "realm": "mrdc","displayName": "PS-mRDC","enabled": true,"requiredCredentials": [
    "password"
  ],"users": [
    {
      "username": "service-account-mrdc","serviceAccountClientId": "mrdc-client","clientRoles": {
        "mrdc-client": [
          "uma_protection"
        ]
      }
    },{
      "username": "mrdc.user","credentials": [
        {
          "type": "password","value": "mrdc"
        }
      ],"realmRoles": [],"groups": [
        "user-group"
      ]
    },{
      "username": "admin.user","value": "admin"
        }
      ],"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","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": "","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","decisionStrategy": "UNANIMOUS","config": {
              "roles": "[{\"id\":\"user\",\"required\":false}]"
            }
          },{
            "name": "User Permission","type": "resource","config": {
              "resources": "[\"Default Resource\"]","applyPolicies": "[\"Only User Role Policy\"]"
            }
          }
        ],"scopes": [
          "view"
        ]
      }
    }
  ]
}

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...