简体   繁体   English

如何配置 Azure 应用服务(用于移动)和 B2C 身份验证以及访问 Azure SQL 数据库

[英]How to configure Azure App Service (for Mobile) and B2C Authentication and access Azure SQL Database

I have a xamarin.forms mobile App using Microsoft.WindowsAzure.MobileServices and Microsoft.Identity.Client.我有一个使用 Microsoft.WindowsAzure.MobileServices 和 Microsoft.Identity.Client 的 xamarin.forms 移动应用程序。 Using EasyAuth I successfully got the xamarin mobile app to post data to the AzureSQL tables linked via connection string in the App Service configuration section.使用 EasyAuth 我成功地让 xamarin 移动应用程序将数据发布到通过应用服务配置部分中的连接字符串链接的 AzureSQL 表。 I use the local and offline sync methods of MobileServiceClient.我使用 MobileServiceClient 的本地和离线同步方法。 I then attempted to change to B2C authentication.然后我尝试更改为 B2C 身份验证。 I setup a Tenant and under this tenant registered a new App as a native client called "MobileB2C".我设置了一个租户,并在这个租户下注册了一个新的应用程序作为一个名为“MobileB2C”的本地客户端。 Redirect URIs were added automatically.重定向 URI 是自动添加的。 I then created the signinsignup UserFlows.然后我创建了 signinsignup UserFlows。

Back to the Azure App Service (Mobile) under Authentication section I added a provider and selected the B2C App, MobileB2C.回到身份验证部分下的 Azure 应用服务(移动),我添加了一个提供者并选择了 B2C 应用程序 MobileB2C。 I did not populate the "allowed token audiences" field and Azure automatically created Client secret setting name "MICROSOFT_PROVIDER_AUTHENTICATION_SECRET" and the issuer URL.我没有填充“允许的令牌受众”字段,Azure 会自动创建客户端机密设置名称“MICROSOFT_PROVIDER_AUTHENTICATION_SECRET”和颁发者 URL。

So when I run the xamarin mobile app I can login via azure B2C and I can see that the authResult returns the users correct info along with UserIdentifier,aud, iss, sub, oid etc.因此,当我运行 xamarin 移动应用程序时,我可以通过 azure B2C 登录,并且可以看到authResult返回用户正确的信息以及 UserIdentifier、aud、iss、sub、oid 等。

Once authResult is returned the xamarin mobile then tries to use the sync methods of MobileServiceClient to save data to the AzureSQL table.一旦返回 authResult,xamarin mobile 就会尝试使用 MobileServiceClient 的同步方法将数据保存到 AzureSQL 表。 Its at this point that it fails.它在这一点上失败了。 When the line await mClient.SyncContext.PushAsync().ConfigureAwait(false);当线await mClient.SyncContext.PushAsync().ConfigureAwait(false); is hit an error occurs described as Microsoft.WindowsAzure.MobileServices.Sync.MobileServicePushStatus.CancelledByAuthentication .发生错误,描述为Microsoft.WindowsAzure.MobileServices.Sync.MobileServicePushStatus.CancelledByAuthentication I continued to try and confirgure the Azure back end differently and now I no linger get the CancelledByAuthentication error but instead get Microsoft.WindowsAzure.MobileServices.Sync.MobileServicePushStatus.CancelledByNetworkError .我继续尝试以不同的方式配置 Azure 后端,现在我不会再得到 CancelledByAuthentication 错误,而是得到Microsoft.WindowsAzure.MobileServices.Sync.MobileServicePushStatus.CancelledByNetworkError

The relevant xamarin mobile app code to implement the authentication and AzureSQL table update is as follows;实现身份验证和AzureSQL表更新的相关xamarin移动应用代码如下;

private B2CAuthenticationService()
    {

        // default redirectURI; each platform specific project will have to override it with its own
        var builder = PublicClientApplicationBuilder.Create(B2CConstants.ClientID)
            .WithB2CAuthority(B2CConstants.AuthoritySignInSignUp)
            .WithIosKeychainSecurityGroup(B2CConstants.IOSKeyChainGroup)
            .WithRedirectUri($"msal{B2CConstants.ClientID}://auth");

        // Android implementation is based on https://github.com/jamesmontemagno/CurrentActivityPlugin
        // iOS implementation would require to expose the current ViewControler - not currently implemented as it is not required
        // UWP does not require this
        var windowLocatorService = DependencyService.Get<IParentWindowLocatorService>();

        if (windowLocatorService != null)
        {
            builder = builder.WithParentActivityOrWindow(() => windowLocatorService?.GetCurrentParentWindow());
        }

        _pca = builder.Build();
    }

    public async Task<UserContext> SignInAsync()
    {
        UserContext newContext;
        try
        {
            // acquire token silent
            newContext = await AcquireTokenSilent();
        }
        catch (MsalUiRequiredException)
        {
            // acquire token interactive
            newContext = await SignInInteractively();
        }
        return newContext;
    }
    private async Task<UserContext> SignInInteractively()
    {
        AuthenticationResult authResult = await _pca.AcquireTokenInteractive(B2CConstants.Scopes)
            .ExecuteAsync();

        var newContext = UpdateUserInfo(authResult);
        UserSingleton.Instance.UserId = newContext.UserIdentifier;
        return newContext;
    }

THe xamarin mobile app adds a record to the local database and then RefreshItemsAsync begins the synchronisation to the AzureSQL. xamarin 移动应用向本地数据库添加一条记录,然后 RefreshItemsAsync 开始同步到 AzureSQL。

await azureService.AddUserSurveyAsync(newSurvey).ConfigureAwait(false);等待 azureService.AddUserSurveyAsync(newSurvey).ConfigureAwait(false); await azureService.RefreshItemsAsync(true).ConfigureAwait(false);等待 azureService.RefreshItemsAsync(true).ConfigureAwait(false);

It is at the PushAsync line below that the the code fails.代码失败是在 PushAsync 行下方。

    public async Task InitializeAsync()
        {
            using (await initializationLock.LockAsync())
            {
                if (!isInitialized)
                {
                    mClient = new MobileServiceClient(https://mobileservice.azurewebsites.net);

                    // Define the offline store.
                    mStore = new MobileServiceSQLiteStore("mobile3.db");
                    mStore.DefineTable<UserSurvey>();
                    await mClient.SyncContext.InitializeAsync(mStore, new MobileServiceSyncHandler()).ConfigureAwait(false);
                    UserSurveyTable = mClient.GetSyncTable<UserSurvey>();
                    isInitialized = true;
                }
            }
        }

    public async Task RefreshItemsAsync(bool syncItems)
    {
            if (syncItems)
            {
                await SynchronizeAsync().ConfigureAwait(false);
            }
    }

    public async Task SynchronizeAsync()
    {
        await InitializeAsync().ConfigureAwait(false);

        IReadOnlyCollection<MobileServiceTableOperationError> syncErrors = null;

        if (!CrossConnectivity.Current.IsConnected)
            return;

        try
        {
            await mClient.SyncContext.PushAsync().ConfigureAwait(false);
            await UserSurveyTable.PullAsync("usersurveys", UserSurveyTable.CreateQuery()).ConfigureAwait(false);
        }
        catch (MobileServicePushFailedException error)
        {
            if (error.PushResult != null)
            {
                foreach (var result in error.PushResult.Errors)
                {
                    await ResolveError(result);
                }
            }
        }
    }

What is wrong with the Azure back end configuration or perhaps I'm missing code as I can't understand how the xamarin mobile app can then attempt to communicate with the Azure Mobile App Service and AzureSQL as I don't send any token with those lines of code for PushAsync etc or perhaps this is abstracted away? Azure 后端配置有什么问题,或者我可能缺少代码,因为我无法理解 xamarin 移动应用程序如何然后尝试与 Azure 移动应用程序服务和 AzureSQL 通信,因为我不发送任何令牌PushAsync 等的代码行或者这可能是抽象的?

Here are images of the exceptions;以下是例外情况的图片;

enter image description here在此处输入图片说明

enter image description here在此处输入图片说明

As promised, here is the succinct version of AAD authentication.正如所承诺的,这里是 AAD 身份验证的简洁版本。 For your purposes, B2C authentication is the same as AAD authentication.出于您的目的,B2C 身份验证与 AAD 身份验证相同。

There are two application definitions at play here - one for the mobile application (which basically says "this person is authenticated"), and one for the service (which says "a token authenticated for this mobile application can access this service").这里有两个应用程序定义 - 一个用于移动应用程序(基本上表示“此人已通过身份验证”),另一个用于服务(表示“为此移动应用程序验证的令牌可以访问此服务”)。 So, you create an application ID for your mobile application, and an application ID for your service, and then you configure the service application ID to accept the mobile application.因此,您为移动应用程序创建应用程序 ID,为服务创建应用程序 ID,然后配置服务应用程序 ID 以接受移动应用程序。

The "WPF" tutorial for Azure Mobile Apps gives the general overview, although it's for WPF instead of Xamarin. Azure 移动应用程序的“WPF”教程提供了一般概述,尽管它适用于 WPF 而不是 Xamarin。 The pieces you need are all the same.你需要的碎片都是一样的。

The "WPF" tutorial here: https://docs.microsoft.com/en-us/azure/developer/mobile-apps/azure-mobile-apps/quickstarts/wpf/authentication这里的“WPF”教程: https : //docs.microsoft.com/en-us/azure/developer/mobile-apps/azure-mobile-apps/quickstarts/wpf/authentication

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用AAD B2C对WPF应用程序进行身份验证以访问Azure应用服务 - How to Authenticate WPF Application with AAD B2C to gain access to Azure App Service azure App Service Authentication 模块是否支持 azure aad b2c? - does the azure App Service Authentication module suport azure aad b2c? 如何配置运行**本地**的 Azure Function 以使用 Azure B2C 执行身份验证? - How can I configure an Azure Function running **locally** to use Azure B2C to perform the authentication? 如何通过 Azure AD B2C 使用身份验证功能在 Azure Web 应用程序上添加身份验证? - How to add authentication on Azure Web App using Authentication feature via Azure AD B2C? 如何将通过b2c身份验证获取的访问令牌从Angular / MVC应用程序传递到Azure API管理服务到Micro服务 - How to pass access token acquired by b2c authentication to Azure API Management Service from Angular/MVC application to Micro services Azure AD B2C - Angularjs 示例(Web 和移动)应用 - Azure AD B2C - Angularjs sample (Web and Mobile) app Azure B2C 移动应用程序与 web api 相结合 - Azure B2C mobile app in combination with a web api Active Directory B2C onBehalfOf到SQL Azure的身份验证 - Active Directory B2C onBehalfOf authentication to SQL Azure Dockerized Azure Function 应用程序的 AAD B2C 身份验证 - AAD B2C Authentication for Dockerized Azure Function App 如何为Azure AD B2C配置SSO? - How to configure SSO for Azure AD B2C?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM