首页 > 解决方案 > 无法使用 openid_client 通过带有 keycloak 的 pkce Flutter 应用程序进行身份验证

问题描述

我有以下 KeyCloak 客户端配置,以使用 pkce 身份验证流程:

Realm: REALM

Client ID:              pkce-client
Client Protocol:        openid-connect
Access Type:            public
Standard Flow Enabled:  ON
Valid Redirect URIs:    http://localhost:4200/ 

Advanced Settings:
Proof Key for Code Exchange Code Challenge Method: S256

我尝试像这样通过 openid_client https://pub.dev/packages/openid_client在带有 iOS 模拟器的颤振应用程序中进行身份验证

  authenticate() async {

    var uri = Uri.parse('http://$localhost:8180/auth/realms/REALM');
    var clientId = 'pkce-client';
    var scopes = List<String>.of(['profile', 'openid']);
    var port = 4200;
    var redirectUri = Uri.parse(http://localhost:4200/);

    var issuer = await Issuer.discover(uri);
    var client = new Client(issuer, clientId);

    urlLauncher(String url) async {
      if (await canLaunch(url)) {
        await launch(url, forceWebView: true);
      } else {
        throw 'Could not launch $url';
      }
    }

    var authenticator = new Authenticator(
        client,
        scopes: scopes,
        port: port,
        urlLancher: urlLauncher,
        redirectUri: redirectUri,
    );

    var auth = await authenticator.authorize();
    var token= await auth.getTokenResponse();
    return token;
  }

但它只给了我这个网络视图: 在此处输入图像描述

KeyCloak 运行的终端给了我以下几行:

INFO  [org.keycloak.protocol.oidc.endpoints.AuthorizationEndpointChecker] (default task-34) PKCE enforced Client without code challenge method.
WARN  [org.keycloak.events] (default task-34) type=LOGIN_ERROR, realmId=REALM, clientId=pkce-client, userId=null, ipAddress=127.0.0.1, error=invalid_request, response_type=code, redirect_uri=http://localhost:4200/, response_mode=query 

使用 Postman 时,它起作用了,它为我提供了登录页面: 在此处输入图像描述

但是我那里有额外的参数,我不知道在Authenticator(..)使用openid_client时在哪里添加它们,状态是自动添加的。

state: <state>
code_challenge: <code-challenge>
code_challenge_method: S256 

我是否需要在 openid_client 方法的某处添加这些 code_challenge 参数?

还是在使用应用程序时需要更改重定向 URL?我尝试使用此处建议的 package_name(https://githubmemory.com/repo/appsup-dart/openid_client/issues/32),但它也不起作用。

标签: flutterkeycloakopenid-connectpkce

解决方案


查看源代码

      : flow = redirectUri == null
            ? Flow.authorizationCodeWithPKCE(client)
            : Flow.authorizationCode(client)

您已指定redirectUri,因此authorizationCode使用了 flow 。但是在这种情况下你想要authorizationCodeWithPKCE流动。因此,只需确保redirectUri为 null 并且将使用正确的 PKCE 流(带有正确的 url 参数,例如 code_challenge)。


推荐阅读