我设法找到了一个 Javascript 解决方案来实现我的第一个方法。不同之处在于,因为
- 我的应用程序永远不会投入生产
- 与我的 Facebook OAuth 实施保持一致,
我使用了隐式流而不是授权码流,尽管出于安全考虑它不是推荐的方式。但是,我认为您可以轻松地使用授权代码流程,检索授权代码并将其传递到您的后端以交换 id 令牌。 (据我所知,您不能使用 Javascript/XHR 请求进行此交换)
所以,流程是从我的 C# 脚本中,我从 .jslib 文件中调用 Javascript 函数。基本上,该函数检测 OAuth 窗口何时重定向回我的 redirect_uri,然后从重定向的 URI 中获取 access_token 参数,并调用 C# 脚本函数。从那里,你应该能够做任何你需要做的事情(改变场景,发送到你的后端,等等)。请注意,这里有一个 try/catch,因为如果您尝试从 Google 登录页面获取信息,将会出现错误。
文件如下:
mergeInto(LibraryManager.library, {
OpenOAuthInExternalTab: function (url, callback) {
var urlString = Pointer_stringify(url);
var callbackString = Pointer_stringify(callback);
var child = window.open(urlString, "_blank");
var interval = setInterval(function() {
try {
// When redirected back to redirect_uri
if (child.location.hostname === location.hostname) {
clearInterval(interval) // Stop Interval
// // Auth Code Flow -- Not used due to relative complexity
// const urlParams = new URLSearchParams(child.location.search);
// const authCode = urlParams.get('code');
// console.log("Auth Code: " + authCode.toString());
// console.log("Callback: " + callbackString);
// window.unityInstance.SendMessage('Auth', callbackString, authCode);
// Implicit Flow
var fragmentString = child.location.hash.substr(1);
var fragment = {};
var fragmentItemStrings = fragmentString.split('&');
for (var i in fragmentItemStrings) {
var fragmentItem = fragmentItemStrings[i].split('=');
if (fragmentItem.length !== 2) {
continue;
}
fragment[fragmentItem[0]] = fragmentItem[1];
}
var accessToken = fragment['access_token'] || '';
console.log("access_token: " + accessToken);
child.close();
// Invoke callback function
window.unityInstance.SendMessage('Auth', callbackString, accessToken);l
}
}
catch(e) {
// Child window in another domain
console.log("Still logging in ...");
}
}, 50);
}
});
然后,在我的 C# 脚本中,我使用以下代码调用此函数:
public class GoogleHelper : MonoBehaviour
{
[DllImport("__Internal")]
private static extern void OpenOAuthInExternalTab(string url, string callbackFunctionName);
// ...
public void Login(string callbackFunctionName) {
var redirectUri = "https://localhost";
var url = "https://accounts.google.com/o/oauth2/v2/auth"
+ $"?client_id={clientId}"
+ "&response_type=token"
+ "&scope=openid%20email%20profile"
+ $"&redirect_uri={redirectUri}";
OpenOAuthInExternalTab(url, callbackFunctionName);
}
// ...
}
当然,这是超级hacky,而且我对Javascript不是很熟悉,所以不太了解上面代码的含义,但它适用于我的用例。