Xamarin Forms中如何基于Google移动端令牌获取Azure Mobile Apps可用令牌?
解决Azure Mobile Apps Google登录的跨客户端令牌问题
你遇到的问题确实是因为Xamarin.Auth获取的access token绑定的是移动应用客户端ID,而Azure Mobile Apps的Google认证是基于Web应用类型的客户端ID配置的,两者权限范围不兼容。按照Google的跨客户端认证流程,我们可以通过令牌交换来获取适用于Azure的Web端令牌,具体步骤如下:
1. 先完成Google Cloud Console的配置
首先确保你的Google Cloud项目里同时存在两类客户端ID,并且完成授权关联:
- 确认已创建移动应用客户端ID(Android/iOS,也就是你用来通过Xamarin.Auth获取token的那个)
- 创建一个Web应用类型的客户端ID(专门给Azure Mobile Apps使用)
- 进入Web应用客户端ID的详情页,在已授权的客户端ID列表里,添加你的移动应用客户端ID并保存配置。这一步是核心,用来允许移动端的token交换为Web端的token。
2. 交换移动端Token为Web端Token
拿到Xamarin.Auth返回的移动端access token后,调用Google的令牌交换端点https://oauth2.googleapis.com/token,发送POST请求获取针对Web客户端的新token。
代码示例(C#)
using System.Net.Http; using System.Collections.Generic; using Newtonsoft.Json; public async Task<string> ExchangeGoogleToken(string mobileAccessToken, string webClientId) { var client = new HttpClient(); var formData = new Dictionary<string, string> { {"grant_type", "urn:ietf:params:oauth:grant-type:token-exchange"}, {"subject_token", mobileAccessToken}, {"subject_token_type", "urn:ietf:params:oauth:token-type:access_token"}, {"audience", webClientId}, {"requested_token_type", "urn:ietf:params:oauth:token-type:access_token"} }; var response = await client.PostAsync("https://oauth2.googleapis.com/token", new FormUrlEncodedContent(formData)); response.EnsureSuccessStatusCode(); var responseContent = await response.Content.ReadAsStringAsync(); var tokenData = JsonConvert.DeserializeObject<dynamic>(responseContent); // 返回适配Azure的Web端access token return tokenData.access_token; }
3. 使用新Token调用Azure Mobile Apps登录
拿到交换后的Web端access token后,再调用LoginAsync方法即可:
var webAccessToken = await ExchangeGoogleToken(yourMobileAccessToken, "你的Web应用客户端ID"); await App.MobileService.LoginAsync(MobileServiceAuthenticationProvider.Google, new Newtonsoft.Json.Linq.JObject { ["access_token"] = webAccessToken });
额外注意事项
- 如果交换时遇到权限报错,检查Google Cloud项目是否开启了Identity Toolkit API
- 确保Web客户端ID和你在Azure Mobile Apps门户配置的Google认证客户端ID完全一致
- 移动端的access token必须是未过期、权限范围包含基础用户信息的有效令牌
内容的提问来源于stack exchange,提问作者Elielson Anjos
相关产品推荐
相关产品推荐

