You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET 7 MAUI中Xamarin.Auth的替代方案:纯客户端Apple/Google登录

.NET 7 MAUI 纯客户端实现Apple/Google登录的Xamarin.Auth替代方案

Apple Sign-In 实现

MAUI中可通过原生API或WebAuthenticator实现纯客户端Apple登录,无需依赖后端服务。原生API方案更贴合系统原生体验,推荐优先使用:

原生API实现(对应原Xamarin.Auth代码逻辑)

private async Task OnAppleSignInButtonClicked()
{
    try
    {
        // 创建Apple登录请求
        var appleIdProvider = new ASAuthorizationAppleIdProvider();
        var request = appleIdProvider.CreateRequest();
        request.RequestedScopes = new[] { ASAuthorizationScope.Email, ASAuthorizationScope.FullName };

        // 发起授权流程
        var rootController = UIApplication.SharedApplication.KeyWindow.RootViewController;
        var authController = new ASAuthorizationController(new[] { request });
        authController.Delegate = new AppleAuthDelegate(OnAppleSignInCompleted);
        authController.PresentationContextProvider = new AppleAuthPresentationProvider(rootController);
        authController.PerformRequests();
    }
    catch (Exception ex)
    {
        // 处理异常逻辑
    }
}

// 登录结果回调
private void OnAppleSignInCompleted(ASAuthorizationAppleIdCredential credential)
{
    if (credential != null)
    {
        // 获取用户核心信息
        var userId = credential.User;
        var email = credential.Email;
        var fullName = $"{credential.FullName?.GivenName} {credential.FullName?.FamilyName}";
        
        // 执行登录成功后的业务逻辑
    }
    else
    {
        // 处理登录失败场景
    }
}

// iOS平台特定委托类(需放在iOS项目中)
public class AppleAuthDelegate : ASAuthorizationControllerDelegate
{
    private readonly Action<ASAuthorizationAppleIdCredential> _onCompleted;

    public AppleAuthDelegate(Action<ASAuthorizationAppleIdCredential> onCompleted)
    {
        _onCompleted = onCompleted;
    }

    public override void DidCompleteAuthorization(ASAuthorizationController controller, ASAuthorization authorization)
    {
        if (authorization.Credential is ASAuthorizationAppleIdCredential appleCredential)
        {
            _onCompleted?.Invoke(appleCredential);
        }
    }

    public override void DidFailAuthorization(ASAuthorizationController controller, NSError error)
    {
        _onCompleted?.Invoke(null);
    }
}

public class AppleAuthPresentationProvider : NSObject, IASAuthorizationControllerPresentationContextProviding
{
    private readonly UIViewController _viewController;

    public AppleAuthPresentationProvider(UIViewController viewController)
    {
        _viewController = viewController;
    }

    public UIWindow GetPresentationAnchor(ASAuthorizationController controller)
    {
        return _viewController.View.Window;
    }
}

跨平台WebAuthenticator实现

若需统一跨平台代码,可使用WebAuthenticator,需在Apple开发者后台配置applinks:你的BundleID作为跳转链接:

private async Task OnAppleSignInButtonClicked()
{
    var authResult = await WebAuthenticator.AuthenticateAsync(
        new Uri($"https://appleid.apple.com/auth/authorize?client_id=你的BundleID&response_type=code id_token&response_mode=form_post&scope=name email"),
        new Uri("applinks:你的BundleID"));

    if (!string.IsNullOrEmpty(authResult.IdToken))
    {
        // 解析IdToken获取用户信息,执行登录成功逻辑
    }
}

Google Sign-In 实现

替代Xamarin.Auth的纯客户端方案有两种选择,均无需后端支持:

方案1:使用Google.Apis.Auth.Maui(原生UI体验)

  1. 安装NuGet包:Google.Apis.Auth.Maui
  2. 代码示例:
private async Task OnGoogleSignInButtonClicked()
{
    try
    {
        var googleAuth = new GoogleAuthClient(
            clientId: "你的Google客户端ID",
            scopes: new[] { "email", "profile" });

        var authResult = await googleAuth.SignInAsync();
        if (authResult != null && authResult.IsAuthenticated)
        {
            // 获取用户详细信息
            var userInfo = await googleAuth.GetUserInfoAsync();
            var userId = userInfo.Id;
            var email = userInfo.Email;
            var name = userInfo.Name;
            
            // 执行登录成功后的业务逻辑
        }
        else
        {
            // 处理登录失败场景
        }
    }
    catch (Exception ex)
    {
        // 处理异常逻辑
    }
}

方案2:使用WebAuthenticator(纯跨平台代码)

需在Google Cloud控制台配置Redirect URI为com.googleusercontent.apps.你的客户端ID:/oauth2redirect:

private async Task OnGoogleSignInButtonClicked()
{
    var authResult = await WebAuthenticator.AuthenticateAsync(
        new Uri($"https://accounts.google.com/o/oauth2/v2/auth?client_id=你的Google客户端ID&scope=email profile&response_type=code&redirect_uri=com.googleusercontent.apps.你的客户端ID:/oauth2redirect"),
        new Uri("com.googleusercontent.apps.你的客户端ID:/oauth2redirect"));

    if (!string.IsNullOrEmpty(authResult.AccessToken))
    {
        // 获取用户信息
        var httpClient = new HttpClient();
        var userInfoResponse = await httpClient.GetStringAsync($"https://www.googleapis.com/oauth2/v2/userinfo?access_token={authResult.AccessToken}");
        var userInfo = Newtonsoft.Json.JsonConvert.DeserializeObject<GoogleUserInfo>(userInfoResponse);
        
        // 执行登录成功后的业务逻辑
    }
}

// 复用原有的GoogleUserInfo类
public class GoogleUserInfo
{
    public string Id { get; set; }
    public string Email { get; set; }
    public string Name { get; set; }
}

关键配置注意事项

  • Apple端:在Apple Developer后台启用「Sign In with Apple」,配置Bundle ID及对应的applinks关联域。
  • Google端:在Google Cloud控制台创建OAuth 2.0客户端ID(选择iOS/Android平台),配置对应的Redirect URI。

内容的提问来源于stack exchange,提问作者Brett Whittaker

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 17:07:01