Delphi FMX Android应用如何捕获Google OAuth2认证服务器响应
解决Delphi FMX Android Google OAuth2认证响应捕获问题
一、修正Android Manifest的Intent-Filter配置
确保Intent-Filter能精准匹配OAuth2重定向URI,替换示例中的com.yourcompany.yourapp为你的反向DNS标识:
<intent-filter> <action android:name="android.intent.action.VIEW" /> <category android:name="android.intent.category.DEFAULT" /> <category android:name="android.intent.category.BROWSABLE" /> <!-- 匹配重定向URI:com.yourcompany.yourapp/oauth2redirect --> <data android:scheme="com.yourcompany.yourapp" android:path="/oauth2redirect" /> </intent-filter>
关键注意点:
android:scheme必须和Google控制台配置的重定向URI的scheme部分完全一致- 不要添加
android:host字段,因为你的重定向URI无host部分 - 必须包含
BROWSABLE类别,否则浏览器无法唤起你的应用
二、调整Intent响应处理逻辑
不要仅判断Intent的Action,Google OAuth2重定向返回的Intent Action固定为android.intent.action.VIEW,核心是检查Intent的Data是否匹配重定向路径。修改Delphi代码如下:
1. 处理启动时的Intent
procedure TMainForm.FormCreate(Sender: TObject); var Intent: JIntent; Uri: JUri; begin Intent := SharedActivity.getIntent; if Assigned(Intent) and not Intent.getData.isNull then begin Uri := Intent.getData; // 校验URI是否匹配预设的重定向路径 if Uri.getScheme.equals(StringToJString('com.yourcompany.yourapp')) and Uri.getPath.equals(StringToJString('/oauth2redirect')) then begin // 提取授权码并处理后续流程 var AuthCode := JStringToString(Uri.getQueryParameter(StringToJString('code'))); ProcessOAuth2Response(AuthCode); end; end; end;
2. 处理应用后台时的Intent
重写Activity的onNewIntent方法,确保应用在后台也能接收重定向Intent:
type TMainForm = class(TForm) // 你的组件声明 protected procedure onNewIntent(Intent: JIntent); override; end; procedure TMainForm.onNewIntent(Intent: JIntent); var Uri: JUri; begin inherited; if Assigned(Intent) and not Intent.getData.isNull then begin Uri := Intent.getData; if Uri.getScheme.equals(StringToJString('com.yourcompany.yourapp')) and Uri.getPath.equals(StringToJString('/oauth2redirect')) then begin var AuthCode := JStringToString(Uri.getQueryParameter(StringToJString('code'))); ProcessOAuth2Response(AuthCode); end; end; end;
三、验证Google控制台配置一致性
- 进入Google Cloud Console的OAuth2凭证页面
- 确认Android凭证的授权重定向URI为
com.yourcompany.yourapp/oauth2redirect,与Manifest配置完全一致 - 检查签名证书的SHA-1指纹是否正确,指纹不匹配会直接导致重定向失败
四、正确调用OAuth2授权页面
使用系统浏览器打开授权URL(避免用WebView,符合Google OAuth2安全规范):
procedure TMainForm.btnAuthClick(Sender: TObject); var AuthUrl: string; JAuthUrl: JString; Intent: JIntent; begin // 替换为你的客户端ID、权限范围等参数 AuthUrl := 'https://accounts.google.com/o/oauth2/v2/auth?' + 'client_id=YOUR_CLIENT_ID.apps.googleusercontent.com&' + 'redirect_uri=com.yourcompany.yourapp/oauth2redirect&' + 'response_type=code&' + 'scope=email profile'; JAuthUrl := StringToJString(AuthUrl); Intent := TJIntent.JavaClass.init(TJIntent.JavaClass.ACTION_VIEW, TJUri.JavaClass.parse(JAuthUrl)); SharedActivity.startActivity(Intent); end;
内容的提问来源于stack exchange,提问作者David U
相关产品推荐
相关产品推荐

