Flutter应用集成Keycloak时出现认证错误,请求协助解决
Flutter + Keycloak 认证问题解决方案
核心问题分析
- 自定义Scheme格式的
redirect_uri被Keycloak判定无效,无法启动认证流程 - 使用http/https格式的
redirect_uri时,认证完成后WebView无法关闭并返回App
问题1:自定义Scheme redirect_uri 无效的解决步骤
1.1 Keycloak客户端配置调整
- 在Keycloak客户端的Valid Redirect URIs中,添加自定义Scheme的完整路径并带上通配符:
cu.havanaclub.fe_dashboard_mobile://auth/*(通配符允许该Scheme下的所有路径匹配) - 将客户端的Access Type设置为
public(移动端App属于公共客户端,不需要client_secret,Keycloak会拒绝带client_secret的公共客户端请求) - 在Web Origins中添加
cu.havanaclub.fe_dashboard_mobile://auth,测试环境可临时填*,生产环境建议精确配置
1.2 Flutter端配置调整
- 移除代码中的
clientSecret参数,公共客户端无需该字段 - 确保自定义Scheme已在Android和iOS工程中配置:
- Android:在
AndroidManifest.xml的主Activity标签内添加intent-filter:<intent-filter> <action android:name="android.intent.action.VIEW" /> <category android:name="android.intent.category.DEFAULT" /> <category android:name="android.intent.category.BROWSABLE" /> <data android:scheme="cu.havanaclub.fe_dashboard_mobile" android:host="auth" /> </intent-filter> - iOS:在
Info.plist中添加URL Scheme配置:<key>CFBundleURLTypes</key> <array> <dict> <key>CFBundleURLSchemes</key> <array> <string>cu.havanaclub.fe_dashboard_mobile</string> </array> <key>CFBundleURLName</key> <string>auth</string> </dict> </array>
- Android:在
问题2:http/https redirect_uri 无法返回App的解决步骤
如果必须使用http/https格式的redirect_uri,需配置系统级跳转关联:
- iOS配置通用链接,Android配置App Links,让系统识别该URL归属你的App
- 在Keycloak的Valid Redirect URIs和Web Origins中添加该http/https地址
- 确保
app_auth库能正确处理该URL的跳转回调
修正后的Flutter登录代码示例
Future<bool> login() async { _assertInitialization(); try { tokenResponse = await _appAuth.authorizeAndExchangeCode( AuthorizationTokenRequest( "fe-dashboard-mobile", // client id "cu.havanaclub.fe_dashboard_mobile://auth", // redirect uri discoveryUrl: "http://10.10.13.77:24001/realms/prod-env/.well-known/openid-configuration", issuer: _keycloakConfig.issuer, scopes: ['openid', 'profile'], promptValues: ['login'], allowInsecureConnections: true, // 移除clientSecret,公共客户端无需此参数 ), ); if (tokenResponse.isValid) { if (tokenResponse.refreshToken != null) { await _secureStorage.write( key: _refreshTokenKey, value: tokenResponse.refreshToken, ); } } else { developer.log('Invalid token response.', name: 'keycloak_wrapper'); } _streamController.add(tokenResponse.isValid); return tokenResponse.isValid; } catch (e, s) { print('$e'); print('$s'); onError('Failed to login.', e, s); return false; } }
额外检查点
- 确认Keycloak 23.0.4客户端的Implicit Flow Enabled无需开启,
authorizeAndExchangeCode使用的是Authorization Code Flow - 确保设备与Keycloak服务器在同一网络,避免网络连通性问题
- 检查
app_auth库版本,建议使用最新稳定版,避免版本兼容问题
内容的提问来源于stack exchange,提问作者Gabriel Alberto Pérez Guerra
相关产品推荐
相关产品推荐

