【问题标题】:Azure Mobile App OAuth with API Controller带有 API 控制器的 Azure 移动应用 OAuth
【发布时间】:2016-08-23 15:04:35
【问题描述】:

通过 Xamarin 表单使用上述服务,我已在服务器级别启用 OAuth(Microsoft 和 Google)身份验证。

来自 Swagger 的调用工作正常。但是我收到 401 错误 通过应用程序访问它。这既不适用于 TableController 也不适用于 APIController。我没有使用 EasyTables。以下是我的代码。

public async Task<bool> AuthenticateAsync()
{
    bool success = false;
    try
    {
        if (user == null)
        {
            user = await ItemManager.DefaultManager.CurrentClient.LoginAsync(this, MobileServiceAuthenticationProvider.MicrosoftAccount);

            Constants.MobileToken = user.MobileServiceAuthenticationToken;
        }
        success = true;
    }
    catch (Exception ex)
    {
        CreateAndShowDialog(ex.Message, "Authentication failed");
    }
    return success;
}

public async Task<ObservableCollection<Item>> GetItemsAsync(bool syncItems = false)
    {
        try
        {
            IEnumerable<Item> items = await itemTable
                .ToEnumerableAsync();

            return new ObservableCollection<Item>(items);
        }
        catch (MobileServiceInvalidOperationException msioe)
        {
            Debug.WriteLine(@"Invalid sync operation: {0}", msioe.Message);
        }
        catch (Exception e)
        {
            Debug.WriteLine(@"Sync error: {0}", e.Message);
        }
        return null;
    }

我尝试使用 rest 服务客户端,但不确定如何通过身份验证标头。正如我所看到的 Swagger,它实际上是通过 cookie AppServiceAuthSession 发送的。应该如何通过 Xamarin Forms 完成?

    public ItemManager(IRestService service)
    {
        restService = service;
    }

    public Task<List<Item>> GetTasksAsync()
    {
        return restService.RefreshDataAsync();
    }

我读到我们必须作为“X-ZUMO-AUTH”提供的令牌不是提供商发回给我们的访问令牌;它是移动服务后端发回的令牌。我们假设如何检索这个令牌?而且我没有看到 Swagger 发送 X-Zumo-Auth 标头。

以下是我的 Rest Service 初始化:

    public RestService()
    {


        client = new HttpClient(new LoggingHandler(true));
        client.MaxResponseContentBufferSize = 256000;
        client.DefaultRequestHeaders.Add("x-access_type", "offline");
        client.DefaultRequestHeaders.Add("x-zumo-auth", Constants.MobileToken);
        client.DefaultRequestHeaders.Add("ZUMO-API-VERSION", "2.0.0");
    }

 public async Task<List<Item>> RefreshDataAsync()
    {
        Items = new List<Item>();
        var uri = new Uri(string.Format(Constants.RestUrl, string.Empty));
        try
        {
            var response = await client.GetAsync(uri);
            if (response.IsSuccessStatusCode)
            {
                var content = await response.Content.ReadAsStringAsync();
                Items = JsonConvert.DeserializeObject<List<Item>>(content);
            }
        }
        catch (Exception ex)
        {
            Debug.WriteLine(@"              ERROR {0}", ex.Message);
        }

        return Items;
    }

编辑

启用服务器日志记录后 - Azure 服务实际上抛出 404 错误。只有当我在服务器上启用自定义授权时才会发生这种情况。

调试代码后,我注意到 Mobile App 与 Swagger 处理的身份验证之间存在以下差异: 移动应用将 Authentication Type 设置为 Federation,但 Swagger 将其正确设置为 microsoftaccount

这也使得 ID 不同:

我不能在这里正确传递令牌。

【问题讨论】:

标签: azure authentication oauth xamarin.forms azure-mobile-services


【解决方案1】:

所以到目前为止我发现我需要将标头 X-ZUMO-AUTH 与当前用户令牌一起传递以使其工作。

并在 API 代码中处理此标头以检索用户详细信息

         //Try to retrieve from header if available
        actionContext.Request.Headers.TryGetValues("x-zumo-auth", out auth_token);

        if (auth_token !=null)
        {
            try
            {
                string urlPath = string.Concat(new Uri(actionContext.Request.RequestUri, actionContext.Request.GetRequestContext().VirtualPathRoot).AbsoluteUri, ".auth/me");
                var result = Get<List<AzureUserDetail>>(HttpWebRequest.Create(urlPath), auth_token.FirstOrDefault(), null)?.FirstOrDefault();
                userID = result.User_Claims.FirstOrDefault(c => c.Type == ClaimTypes.NameIdentifier).Val;
            }
            catch
            {
                actionContext.Response = new HttpResponseMessage(System.Net.HttpStatusCode.NotAcceptable);
            }
        }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-11-05
    • 2017-08-14
    • 1970-01-01
    • 2015-02-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多