对于未经身份验证的请求,Keycloak spring boot returns 403 而不是 401

Keyclock springboot returns 403 instead of 401 for unauthenticated requests

Keyclock return 403 而不是 401 启用策略执行器配置时未经身份验证的请求。删除策略执行器配置时 returns 401.

使用此配置得到 403 空响应。

keycloak:
  realm: ${KEYCLOAK_REALM}
  auth-server-url: ${KEYCLOAK_AUTH_SERVER_URL}
  ssl-required: external
  resource: ${KEYCLOAK_CLIENT_ID}
  credentials.secret: ${KEYCLOAK_CLIENT_SECRET}
  use-resource-role-mappings: true
  cors: true
  public-client: false
  bearer-only: true
  policy-enforcer-config:
    lazy-load-paths: true
    http-method-as-scope: true
    path-cache-config:
      max-entries: 1000
      lifespan: 1000
    paths:
      - name: Insecure Resource
        path: /
        enforcement-mode: DISABLED
      - name: Swagger UI
        path: /swagger-ui/*
        enforcement-mode: DISABLED
      - name: Swagger Resources
        path: /swagger-resources/*
        enforcement-mode: DISABLED
      - name: Swagger api Resources
        path: /api-docs
        enforcement-mode: DISABLED
  securityConstraints:
    - authRoles:
       - '*'
      securityCollections:
        - name: protected
          patterns:
            - '/v1/*'
            - '/intranet/*'

如果我像这样删除政策执行者

keycloak:
  realm: ${KEYCLOAK_REALM}
  auth-server-url: ${KEYCLOAK_AUTH_SERVER_URL}
  ssl-required: external
  resource: ${KEYCLOAK_CLIENT_ID}
  credentials.secret: ${KEYCLOAK_CLIENT_SECRET}
  use-resource-role-mappings: true
  cors: true
  public-client: false
  bearer-only: true
#  policy-enforcer-config:
#    lazy-load-paths: true
#    http-method-as-scope: true
#    path-cache-config:
#      max-entries: 1000
#      lifespan: 1000
#    paths:
#      - name: Insecure Resource
#        path: /
#        enforcement-mode: DISABLED
#      - name: Swagger UI
#        path: /swagger-ui/*
#        enforcement-mode: DISABLED
#      - name: Swagger Resources
#        path: /swagger-resources/*
#        enforcement-mode: DISABLED
#      - name: Swagger api Resources
#        path: /api-docs
#        enforcement-mode: DISABLED
  securityConstraints:
    - authRoles:
       - '*'
      securityCollections:
        - name: protected
          patterns:
            - '/v1/*'
            - '/intranet/*'

returns 401

{
    "timestamp": "2021-10-05T11:25:33.116+0000",
    "status": 401,
    "error": "Unauthorized",
    "message": "No message available",
    "path": "/v1/approve-documents"
}

所有请求都在执行策略,无论是否经过身份验证。如何 return 401 如果令牌无效或丢失。

完整代码https://github.com/prajintst/keyclock-permissions

根据 Keycloak 架构图,策略执行检查发生在 autherization/authentication 之前。因此,您无法使用策略执行来实现预期的输出。

我建议您使用策略 evaluator/provider 或使用基于角色的授权来实现此目的。

看到我的回答post:Spring Security Plugin Should Respond with 401 instead of 403

它帮助我正确设置状态代码