AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • 主页
  • 系统&网络
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • 主页
  • 系统&网络
    • 最新
    • 热门
    • 标签
  • Ubuntu
    • 最新
    • 热门
    • 标签
  • Unix
    • 最新
    • 标签
  • DBA
    • 最新
    • 标签
  • Computer
    • 最新
    • 标签
  • Coding
    • 最新
    • 标签
主页 / coding / 问题

问题[keycloak](coding)

Martin Hope
Ni2Be
Asked: 2025-03-08 02:07:37 +0800 CST

KeyCloak 26.1.3 权限选项卡不可见

  • 5

我正在尝试为 Teams Tab App 设置令牌交换,并想要设置 KeyCloak,以便我可以将 Entra 令牌兑换为 KeyCloak 令牌。

我启用了

  • KC_FEATURE=预览,令牌交换,管理细粒度身份验证

并且看起来它处于活动状态:

./opt/keycloak/bin/kc.sh show-config
:
kc.feature =  preview,token-exchange,admin-fine-grained-authz (ENV)
:

但是当我在管理控制台时,我仍然看不到“权限”选项卡: 在此处输入图片描述

我正在使用 quay.io/keycloak/keycloak:26.1.3

我错过了什么?

文件:
services:
  idp2-database:
    image: postgres:17.0
    volumes:
      - ./docker-volumes/userDatabase2:/var/lib/postgresql/data
    restart: always
    ports:
      - "45001:5432"
    environment:
      POSTGRES_DB: userDb
      POSTGRES_USER: keycloakUser
      POSTGRES_PASSWORD: keycloakUser
    container_name: idp2-database
    networks:
      - keycloak2-and-postgres-network
    healthcheck:
      test: ["CMD", "psql", "-U", "keycloakUser", "-d", "userDb", "-c", "SELECT 1"]
      interval: 10s
      timeout: 5s
      retries: 5

  idp2-keycloak:
    image: quay.io/keycloak/keycloak:26.1.3
    container_name: idp2-keycloak
    restart: always
    command: ["start", "--https-certificate-file=/opt/keycloak/certs/tls.crt", "--https-certificate-key-file=/opt/keycloak/certs/tls.key", "--spi-theme-static-max-age=-1", "--spi-theme-cache-themes=false", "--spi-theme-cache-templates=false"]
    environment:
      # features (token-exchange, admin-fine-grained-authz)
      - KC_FEATURE=preview,token-exchange,admin-fine-grained-authz

      # admin user
      - KEYCLOAK_ADMIN=admin
      - KEYCLOAK_ADMIN_PASSWORD=admin

      # database
      - KC_DB=postgres
      - KC_DB_URL=jdbc:postgresql://idp2-database:5432/userDb
      - KC_DB_USERNAME=keycloakUser
      - KC_DB_PASSWORD=keycloakUser

      # health
      - KC_HEALTH_ENABLED=true

      # logging
      - KEYCLOAK_LOGLEVEL=DEBUG

      # hosting
      - KC_HOSTNAME=localhost
      - KEYCLOAK_FRONTEND_URL=https://localhost:45000/auth
      - KC_HOSTNAME_STRICT=false
      - KC_HOSTNAME_STRICT_HTTPS=true
      - KC_HTTP_ENABLED=false
      - KC_HTTPS_PORT=8443
      # - KC_HTTP_MAX_HEADER_SIZE=32768 
      - QUARKUS_HTTP_HTTP2=false
      
    ports:
      - "45000:8443"
    volumes:
      - ./docker-volumes/keycloak2/standalone/data:/opt/keycloak/standalone/data
      - ./docker-volumes/keycloak2/certs:/opt/keycloak/certs
      - ../src/themes:/opt/keycloak/themes
      - ./docker-volumes/keycloak2/providers:/opt/keycloak/providers
      - ./docker-volumes/keycloak2/standalone/configuration:/opt/keycloak/standalone/configuration
    depends_on:
      idp2-database:
        condition: service_healthy
    networks:
      - keycloak2-and-postgres-network

networks:
  keycloak2-and-postgres-network:

证书片段:

openssl req -newkey rsa:2048 -nodes \
  -keyout ./docker-volumes/keycloak/certs/tls.key \
  -x509 -days 365 \
  -out ./docker-volumes/keycloak/certs/tls.crt \
  -subj "/CN=localhost" \
  -addext "subjectAltName=DNS:localhost,DNS:127.0.0.1"
keycloak
  • 1 个回答
  • 30 Views
Martin Hope
mohamed amine salah
Asked: 2024-11-19 01:06:11 +0800 CST

响应中的 id_token 缺少 nonce

  • 6

我使用 Keycloak 21 进行身份验证,但遇到了一个问题,即调用 /token 后返回的 id_token 中不包含 nonce 值。我在 /auth 请求中传递了 nonce,

keycloak
  • 1 个回答
  • 30 Views
Martin Hope
mascai
Asked: 2024-11-11 04:48:32 +0800 CST

keycloak 中的“无效令牌”

  • 6

我正在尝试在我的 FastAPI 应用程序中使用 keycloak 我的代码

from fastapi import Depends, HTTPException, status
from fastapi.security import OAuth2PasswordBearer
from jose import jwt, JWTError
from keycloak import KeycloakOpenID
import requests
import logging
import os

from .config import settings


# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

# Keycloak configuration
KEYCLOAK_SERVER_URL = settings.KEYCLOAK_SERVER_URL
KEYCLOAK_REALM = settings.KEYCLOAK_REALM
KEYCLOAK_CLIENT_ID = settings.KEYCLOAK_CLIENT_ID
KEYCLOAK_CLIENT_SECRET = settings.KEYCLOAK_CLIENT_SECRET
ALGORITHM = "RS256"
TOKEN_URL = f"{KEYCLOAK_SERVER_URL}/realms/fastapi-realm/protocol/openid-connect/token"


# Initialize KeycloakOpenID
keycloak_openid = KeycloakOpenID(
    server_url=f"{KEYCLOAK_SERVER_URL}",
    client_id=KEYCLOAK_CLIENT_ID,
    realm_name=KEYCLOAK_REALM,
    client_secret_key=KEYCLOAK_CLIENT_SECRET,
    verify=False
)
config_well_known = keycloak_openid.well_known()

oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")

def verify_token(token: str = Depends(oauth2_scheme)):
    try:
        decoded_token = keycloak_openid.decode_token(
            token,validate=True,
        )
        username = decoded_token['preferred_username']
        logger.info(f"Decoded token: {decoded_token}")
        # Verify the issuer claim
        issuer = decoded_token["iss"]

        expected_issuer = f"{KEYCLOAK_SERVER_URL}/realms/{KEYCLOAK_REALM}"
        I# Token example -- token: {'exp': 1731303036, 'iat': 1731267036, 'jti': 'f1b71d25-4de6-4c03-b5f5-d9726b39d51f', 'iss': 'https://feast-keycloak.pimc-st.innodev.local/realms/feast-realm', 'aud': 'account', 'sub': 'ac48f45e-f26b-4380-bde8-e752febb6d18', 'typ': 'Bearer', 'azp': 'feast-client-id', 'session_state': 'b36cd197-247d-447e-9f3d-6cf1fecae7d6', 'acr': '1', 'allowed-origins': ['https://feast-frontend.pimc-st.innodev.local', '/*', 'http://localhost:5173'], 'realm_access': {'roles': ['default-roles-feast-realm', 'offline_access', 'uma_authorization']}, 'resource_access': {'account': {'roles': ['manage-account', 'manage-account-links', 'view-profile']}}, 'scope': 'profile email', 'sid': 'b36cd197-247d-447e-9f3d-6cf1fecae7d6', 'email_verified': False, 'name': 'A B', 'preferred_username': 'my_username', 'given_name': 'A', 'family_name': 'B', 'email': '[email protected]'}
        logger.info(f"XXX_ issuer={issuer}")
        logger.info(f"XXX_ expected_issuer={expected_issuer}")
        if issuer != expected_issuer:
            raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid issuer")
        
        logger.info(f"username: {username}")
        return decoded_token
    except Exception as e:
        raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid token")

在我的 main.py 中我有以下代码

from fastapi import Depends, FastAPI, HTTPException, status, Security


from .keycloak import verify_token, oauth2_scheme, KEYCLOAK_CLIENT_ID, KEYCLOAK_CLIENT_SECRET, TOKEN_URL

app = FastAPI()

@app.post("/project", response_model=schemas.Project, tags=["project",])
def create_project(project: schemas.CreateProject, db: Session = Depends(get_db), payload: dict = Security(verify_token)):
    ...


@app.post("/login")
def get_token(body: schemas.Login):
    data = {
        "grant_type": "password", # TODO: clarify grant_type client_credentials (requires only client id and secret or password - requires password and login)
        "client_id": KEYCLOAK_CLIENT_ID,
        "client_secret": KEYCLOAK_CLIENT_SECRET,
        "password": body.password,
        "username": body.login
    }
    response = requests.post(TOKEN_URL, data=data,  verify=False)
    return JSONResponse(status_code=response.status_code, content=response.json())

我通过 /login 方法获取令牌然后我像这样应用令牌: 在此处输入图片描述

对于请求/project我有一个错误:

“无效令牌”

如何修复错误?

keycloak
  • 1 个回答
  • 41 Views
Martin Hope
mascai
Asked: 2024-10-24 19:03:56 +0800 CST

客户端凭据是 unsupported_grant_type

  • 6

我正在创建 FastApi + KeyCloak 应用程序。已创建领域、客户端和用户

客户端配置 在此处输入图片描述

我的用户配置 在此处输入图片描述

我可以借助此请求获取令牌

在此处输入图片描述

但是对于 grant_typeclient-credentials我有一个错误:

{
    "error": "unsupported_grant_type",
    "error_description": "Unsupported grant_type"
}

密码和客户端凭证有什么区别?如何支持客户端凭证?

keycloak
  • 1 个回答
  • 16 Views
Martin Hope
alexanoid
Asked: 2024-09-02 16:26:56 +0800 CST

使用 Keycloak 作为登录提供商的 StackOverflow 返回空的电子邮件地址

  • 3

在我的 Keycloak 设置中,StackOverflow 被配置为登录提供程序之一。最近,我注意到新用户无法通过 StackOverflow 在我的网站上注册,因为返回的电子邮件为空。这可能是什么原因?

keycloack.版本 18.0.2

2024-09-02 10:39:51,276 WARN  [org.keycloak.services] (executor-thread-11964) KC-SERVICES0020: Email is null. Reset flow and enforce showing reviewProfile page
2024-09-02 10:39:51,276 WARN  [org.keycloak.services] (executor-thread-11964) KC-SERVICES0013: Failed authentication: org.keycloak.authentication.AuthenticationFlowException
    at org.keycloak.authentication.AuthenticationProcessor.authenticateOnly(AuthenticationProcessor.java:1038)
    at org.keycloak.services.resources.LoginActionsService$1.authenticateOnly(LoginActionsService.java:808)
    at org.keycloak.authentication.AuthenticationProcessor.authenticate(AuthenticationProcessor.java:892)
    at org.keycloak.services.resources.LoginActionsService.processFlow(LoginActionsService.java:323)
    at org.keycloak.services.resources.LoginActionsService.brokerLoginFlow(LoginActionsService.java:838)
    at org.keycloak.services.resources.LoginActionsService.firstBrokerLoginGet(LoginActionsService.java:732)
    at jdk.internal.reflect.GeneratedMethodAccessor343.invoke(Unknown Source)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:568)
    at org.jboss.resteasy.core.MethodInjectorImpl.invoke(MethodInjectorImpl.java:170)
    at org.jboss.resteasy.core.MethodInjectorImpl.invoke(MethodInjectorImpl.java:130)
    at org.jboss.resteasy.core.ResourceMethodInvoker.internalInvokeOnTarget(ResourceMethodInvoker.java:660)
    at org.jboss.resteasy.core.ResourceMethodInvoker.invokeOnTargetAfterFilter(ResourceMethodInvoker.java:524)
    at org.jboss.resteasy.core.ResourceMethodInvoker.lambda$invokeOnTarget$2(ResourceMethodInvoker.java:474)
    at org.jboss.resteasy.core.interception.jaxrs.PreMatchContainerRequestContext.filter(PreMatchContainerRequestContext.java:364)
    at org.jboss.resteasy.core.ResourceMethodInvoker.invokeOnTarget(ResourceMethodInvoker.java:476)
    at org.jboss.resteasy.core.ResourceMethodInvoker.invoke(ResourceMethodInvoker.java:434)
    at org.jboss.resteasy.core.ResourceLocatorInvoker.invokeOnTargetObject(ResourceLocatorInvoker.java:192)
    at org.jboss.resteasy.core.ResourceLocatorInvoker.invoke(ResourceLocatorInvoker.java:141)
    at org.jboss.resteasy.core.ResourceLocatorInvoker.invoke(ResourceLocatorInvoker.java:32)
    at org.jboss.resteasy.core.SynchronousDispatcher.invoke(SynchronousDispatcher.java:492)
    at org.jboss.resteasy.core.SynchronousDispatcher.lambda$invoke$4(SynchronousDispatcher.java:261)
    at org.jboss.resteasy.core.SynchronousDispatcher.lambda$preprocess$0(SynchronousDispatcher.java:161)
    at org.jboss.resteasy.core.interception.jaxrs.PreMatchContainerRequestContext.filter(PreMatchContainerRequestContext.java:364)
    at org.jboss.resteasy.core.SynchronousDispatcher.preprocess(SynchronousDispatcher.java:164)
    at org.jboss.resteasy.core.SynchronousDispatcher.invoke(SynchronousDispatcher.java:247)
    at io.quarkus.resteasy.runtime.standalone.RequestDispatcher.service(RequestDispatcher.java:73)
    at io.quarkus.resteasy.runtime.standalone.VertxRequestHandler.dispatch(VertxRequestHandler.java:151)
    at io.quarkus.resteasy.runtime.standalone.VertxRequestHandler.handle(VertxRequestHandler.java:82)
    at io.quarkus.resteasy.runtime.standalone.VertxRequestHandler.handle(VertxRequestHandler.java:42)
    at io.vertx.ext.web.impl.RouteState.handleContext(RouteState.java:1212)
    at io.vertx.ext.web.impl.RoutingContextImplBase.iterateNext(RoutingContextImplBase.java:163)
    at io.vertx.ext.web.impl.RoutingContextImpl.next(RoutingContextImpl.java:141)
    at io.quarkus.vertx.http.runtime.StaticResourcesRecorder$2.handle(StaticResourcesRecorder.java:67)
    at io.quarkus.vertx.http.runtime.StaticResourcesRecorder$2.handle(StaticResourcesRecorder.java:55)
    at io.vertx.ext.web.impl.RouteState.handleContext(RouteState.java:1212)
    at io.vertx.ext.web.impl.RoutingContextImplBase.iterateNext(RoutingContextImplBase.java:163)
    at io.vertx.ext.web.impl.RoutingContextImpl.next(RoutingContextImpl.java:141)
    at io.quarkus.vertx.http.runtime.VertxHttpRecorder$5.handle(VertxHttpRecorder.java:380)
    at io.quarkus.vertx.http.runtime.VertxHttpRecorder$5.handle(VertxHttpRecorder.java:358)
    at io.vertx.ext.web.impl.RouteState.handleContext(RouteState.java:1212)
    at io.vertx.ext.web.impl.RoutingContextImplBase.iterateNext(RoutingContextImplBase.java:163)
    at io.vertx.ext.web.impl.RoutingContextImpl.next(RoutingContextImpl.java:141)
    at org.keycloak.quarkus.runtime.integration.web.QuarkusRequestFilter.lambda$createBlockingHandler$1(QuarkusRequestFilter.java:71)
    at io.vertx.core.impl.ContextImpl.lambda$null$0(ContextImpl.java:159)
    at io.vertx.core.impl.AbstractContext.dispatch(AbstractContext.java:100)
    at io.vertx.core.impl.ContextImpl.lambda$executeBlocking$1(ContextImpl.java:157)
    at io.quarkus.vertx.core.runtime.VertxCoreRecorder$13.runWith(VertxCoreRecorder.java:543)
    at org.jboss.threads.EnhancedQueueExecutor$Task.run(EnhancedQueueExecutor.java:2449)
    at org.jboss.threads.EnhancedQueueExecutor$ThreadBody.run(EnhancedQueueExecutor.java:1478)
    at org.jboss.threads.DelegatingRunnable.run(DelegatingRunnable.java:29)
    at org.jboss.threads.ThreadLocalResettingRunnable.run(ThreadLocalResettingRunnable.java:29)
    at io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30)
    at java.base/java.lang.Thread.run(Thread.java:833)

2024-09-02 10:39:51,277 WARN  [org.keycloak.events] (executor-thread-11964) type=IDENTITY_PROVIDER_FIRST_LOGIN_ERROR
keycloak
  • 1 个回答
  • 31 Views
Martin Hope
Vinod Louis
Asked: 2024-07-31 20:11:15 +0800 CST

Keycloak 令牌交换错误 - 客户端不在令牌受众范围内

  • 6

我正在处理 keycloak 的令牌交换请求,其中尝试在与客户端 1 进行身份验证时获取客户端 2 的访问令牌。

已在 keycloak 实例上启用 token_exchange 和 admin_fine_grained_authz。

遵循https://www.keycloak.org/docs/latest/securing_apps/index.html#_internal-token-to-internal-token-exchange中的文档

当我点击 API 进行代币交换时

curl --location 'http://<URL>/realms/Genting/protocol/openid-connect/token' \
--header 'Content-Type: application/x-www-form-urlencoded' \
--data-urlencode 'client_id=client2' \
--data-urlencode 'client_secret=<client2 secret>' \
--data-urlencode 'subject_token=<client1 token> \
--data-urlencode 'audience=client2' \
--data-urlencode 'grant_type=urn:ietf:params:oauth:grant-type:token-exchange' \
--data-urlencode 'requested_token_type=urn:ietf:params:oauth:token-type:access_token' 

作为回应,我得到了

{
    "error": "access_denied",
    "error_description": "Client is not within the token audience"
} 

我是否遗漏了一些设置以致无法正确接收令牌?

keycloak
  • 1 个回答
  • 18 Views
Martin Hope
Pawel Zieminski
Asked: 2024-03-15 04:43:19 +0800 CST

如何在keycloak中列出服务帐户用户

  • 6

有没有办法使用 Keycloak API (19.x) 列出服务帐户用户?

我可以使用 列出用户GET /admin/realms/{realm}/users,并且可以使用 GET 访问服务用户帐户用户/admin/realms/{realm}/users/{service-account-user-id},如果我有这样的 id,例如用户登录事件,但有没有办法列出这些?

我所需要的只是他们的 id 和用户名值。

/admin/realms/{realm}/users我查看了可用的 Keycloak REST API 文档,但在或下看不到它/admin/realms/{realm}/clients。当通过翻转客户端上启用的服务帐户来创建这些用户时,也没有相应的创建和更新事件。

keycloak
  • 2 个回答
  • 19 Views
Martin Hope
Альберт Александров
Asked: 2023-08-17 21:15:48 +0800 CST

在没有 admin-cli 的情况下通过 KeyCloak 中的 API 创建用户?

  • 7

想象一下创建了一个领域my-realm和客户端。my-client是否可以在没有 admin-cli 的情况下通过 API 创建用户(带有my-client客户端的秘密)?

keycloak
  • 1 个回答
  • 20 Views

Sidebar

Stats

  • 问题 205573
  • 回答 270741
  • 最佳答案 135370
  • 用户 68524
  • 热门
  • 回答
  • Marko Smith

    重新格式化数字,在固定位置插入分隔符

    • 6 个回答
  • Marko Smith

    为什么 C++20 概念会导致循环约束错误,而老式的 SFINAE 不会?

    • 2 个回答
  • Marko Smith

    VScode 自动卸载扩展的问题(Material 主题)

    • 2 个回答
  • Marko Smith

    Vue 3:创建时出错“预期标识符但发现‘导入’”[重复]

    • 1 个回答
  • Marko Smith

    具有指定基础类型但没有枚举器的“枚举类”的用途是什么?

    • 1 个回答
  • Marko Smith

    如何修复未手动导入的模块的 MODULE_NOT_FOUND 错误?

    • 6 个回答
  • Marko Smith

    `(表达式,左值) = 右值` 在 C 或 C++ 中是有效的赋值吗?为什么有些编译器会接受/拒绝它?

    • 3 个回答
  • Marko Smith

    在 C++ 中,一个不执行任何操作的空程序需要 204KB 的堆,但在 C 中则不需要

    • 1 个回答
  • Marko Smith

    PowerBI 目前与 BigQuery 不兼容:Simba 驱动程序与 Windows 更新有关

    • 2 个回答
  • Marko Smith

    AdMob:MobileAds.initialize() - 对于某些设备,“java.lang.Integer 无法转换为 java.lang.String”

    • 1 个回答
  • Martin Hope
    Fantastic Mr Fox msvc std::vector 实现中仅不接受可复制类型 2025-04-23 06:40:49 +0800 CST
  • Martin Hope
    Howard Hinnant 使用 chrono 查找下一个工作日 2025-04-21 08:30:25 +0800 CST
  • Martin Hope
    Fedor 构造函数的成员初始化程序可以包含另一个成员的初始化吗? 2025-04-15 01:01:44 +0800 CST
  • Martin Hope
    Petr Filipský 为什么 C++20 概念会导致循环约束错误,而老式的 SFINAE 不会? 2025-03-23 21:39:40 +0800 CST
  • Martin Hope
    Catskul C++20 是否进行了更改,允许从已知绑定数组“type(&)[N]”转换为未知绑定数组“type(&)[]”? 2025-03-04 06:57:53 +0800 CST
  • Martin Hope
    Stefan Pochmann 为什么 {2,3,10} 和 {x,3,10} (x=2) 的顺序不同? 2025-01-13 23:24:07 +0800 CST
  • Martin Hope
    Chad Feller 在 5.2 版中,bash 条件语句中的 [[ .. ]] 中的分号现在是可选的吗? 2024-10-21 05:50:33 +0800 CST
  • Martin Hope
    Wrench 为什么双破折号 (--) 会导致此 MariaDB 子句评估为 true? 2024-05-05 13:37:20 +0800 CST
  • Martin Hope
    Waket Zheng 为什么 `dict(id=1, **{'id': 2})` 有时会引发 `KeyError: 'id'` 而不是 TypeError? 2024-05-04 14:19:19 +0800 CST
  • Martin Hope
    user924 AdMob:MobileAds.initialize() - 对于某些设备,“java.lang.Integer 无法转换为 java.lang.String” 2024-03-20 03:12:31 +0800 CST

热门标签

python javascript c++ c# java typescript sql reactjs html

Explore

  • 主页
  • 问题
    • 最新
    • 热门
  • 标签
  • 帮助

Footer

AskOverflow.Dev

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve