.NET MAUI集成Sign in with Apple遇无效重定向URL错误
.NET MAUI集成Apple登录报错:invalid_request invalid web redirect url
我正在开发一个.NET MAUI应用,在集成Sign in with Apple功能时,点击登录按钮会弹出错误提示:invalid_request invalid web redirect url。
已尝试的解决方案
- 尝试过苹果开发者论坛相关方案,但没有效果
- 查阅了Sign in with Apple环境配置的官方文档
- 参考过Clerk、Auth0的Apple登录教程,以及YouTube上的相关视频教程
代码片段
登录请求初始化
// 初始化Apple登录请求 WebAuthenticatorResult result = null; if (scheme.Equals(Constants.apple, StringComparison.Ordinal) && DeviceInfo.Platform == DevicePlatform.iOS && DeviceInfo.Version.Major >= 13) { // 确保已在 entitlements 和配置文件中启用Apple登录 var options = new AppleSignInAuthenticator.Options { IncludeEmailScope = true, IncludeFullNameScope = true, }; result = await AppleSignInAuthenticator.AuthenticateAsync(options); } else { var authUrl = new Uri(Constants.authenticationUrl + scheme); var callbackUrl = new Uri(Constants.callbackUrl); result = await WebAuthenticator.AuthenticateAsync(authUrl, callbackUrl); } AuthToken = string.Empty; // 从回调URL中获取姓名和邮箱 //if (result.Properties.TryGetValue("name", out var name) && !string.IsNullOrEmpty(name)) // AuthToken += $"Name: {name}{Environment.NewLine}"; //if (result.Properties.TryGetValue("email", out var email) && !string.IsNullOrEmpty(email)) // AuthToken += $"Email: {email}{Environment.NewLine}"; AuthToken += result?.AccessToken ?? result?.IdToken; AuthCredential credential = null;
登录结果处理(后端接口)
// WebAuthenticator端点 - 用于社交登录(如Google、Facebook、Apple等) const string callbackScheme = "socialloginauthenticator"; [HttpGet("{scheme}")] public async Task Get([FromRoute] string scheme) { var auth = await Request.HttpContext.AuthenticateAsync(scheme); if (!auth.Succeeded || auth?.Principal == null || !auth.Principal.Identities.Any(id => id.IsAuthenticated) || string.IsNullOrEmpty(auth.Properties.GetTokenValue("access_token"))) { // 未认证,发起挑战 await Request.HttpContext.ChallengeAsync(scheme); } else { var claims = auth.Principal.Identities.FirstOrDefault()?.Claims; var email = string.Empty; email = claims?.FirstOrDefault(c => c.Type == System.Security.Claims.ClaimTypes.Email)?.Value; // 整理要返回给回调的参数 var qs = new Dictionary<string, string> { { "access_token", auth.Properties.GetTokenValue("access_token") }, { "refresh_token", auth.Properties.GetTokenValue("refresh_token") ?? string.Empty }, { "expires_in", (auth.Properties.ExpiresUtc?.ToUnixTimeSeconds() ?? -1).ToString() }, { "email", email } }; // 构建结果URL var url = callbackScheme + "://#" + string.Join( "&", qs.Where(kvp => !string.IsNullOrEmpty(kvp.Value) && kvp.Value != "-1") .Select(kvp => $"{WebUtility.UrlEncode(kvp.Key)}={WebUtility.UrlEncode(kvp.Value)}")); // 重定向到最终URL Request.HttpContext.Response.Redirect(url); } }
内容的提问来源于stack exchange,提问作者Ahmad Pasha
相关产品推荐
相关产品推荐

