【问题标题】:Implement Custom Authentication In Windows Azure Mobile Services在 Windows Azure 移动服务中实现自定义身份验证
【发布时间】:2014-10-10 10:17:35
【问题描述】:

Windows Azure 移动服务目前没有用于自定义身份验证和查看功能请求的选项

http://feedback.azure.com/forums/216254-mobile-services/suggestions/3313778-custom-user-auth

它不会很快到来。

使用 .NET 后端和 .NET 应用程序,您如何实现自定义身份验证,这样您就不必使用 Facebook、Google 或它们当前的任何其他提供商?

有很多部分完成的教程介绍了如何使用 JS 后端以及 iOS 和 Android 完成此操作,但是 .NET 示例在哪里?

【问题讨论】:

  • 当然,在我发布了这个问题和答案之后,我发现了这篇文章:azure.microsoft.com/en-us/documentation/articles/… 躲起来。与我的方法非常相似,但执行得更好。但是,我仍然会留在这里,因为我相信它提供了更简单的解释和更多关于如何使其工作的信息。微软的文章遗漏了几个关键点,让人感到困惑。
  • 你能告诉我你在哪里找到了关于 jsbackend 和 iOS 自定义身份验证的那些部分完成的教程吗?我找不到!!

标签: azure-mobile-services


【解决方案1】:

在下面列出的文章的一些帮助下,一些智能感知和一些试验和错误,我终于完成了解决方案。

WAMS 的工作原理

首先,我想以一种非常简单的形式来描述什么是 WAMS,因为这部分让我困惑了一段时间,直到它最终点击。 WAMS 只是为快速部署而打包的一组预先存在的技术。对于这种情况,您需要了解的是:

正如您所见,WAMS 实际上只是一个 WebAPI 和其他东西的容器,我不会在这里详细介绍。在 Azure 中创建新的移动服务时,您可以下载包含 WebAPI 的项目。他们使用的示例是 TodoItem,因此您将通过项目看到此场景的代码。

下面是你下载这个例子的地方(我只是在做一个 Windows Phone 8 应用程序)

我可以继续深入,但本教程将帮助您入门:

http://azure.microsoft.com/en-us/documentation/articles/mobile-services-dotnet-backend-windows-store-dotnet-get-started/

设置 WAMS 项目

您将需要 MasterKey 和 ApplicationKey。您可以从 Azure 门户获取它们,单击您的移动服务应用程序并按底部的管理密钥

您刚刚下载的项目,在 Controllers 文件夹中,我刚刚创建了一个名为 AccountController.cs 的新控制器,并在其中放入了

    public HttpResponseMessage GetLogin(String username, String password)
    {
        String masterKey = "[enter your master key here]";
        bool isValidated = true;

        if (isValidated)
            return new HttpResponseMessage() { StatusCode = HttpStatusCode.OK, Content = new StringContent("{ 'UserId' : 'F907F58C-09FE-4F25-A26B-3248CD30F835', 'token' : '" + GetSecurityToken(new TimeSpan(1,0, 0), String.Empty, "F907F58C-09FE-4F25-A26B-3248CD30F835", masterKey)  + "' }") };
        else
            return Request.CreateErrorResponse(HttpStatusCode.Unauthorized, "Username and password are incorrect");

    }

    private static string GetSecurityToken(TimeSpan periodBeforeExpires, string aud, string userId, string masterKey)
    {
        var now = DateTime.UtcNow;
        var utc0 = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
        var payload = new
        {
            exp = (int)now.Add(periodBeforeExpires).Subtract(utc0).TotalSeconds,
            iss = "urn:microsoft:windows-azure:zumo",
            ver = 2,
            aud = "urn:microsoft:windows-azure:zumo",
            uid = userId
        };

        var keyBytes = Encoding.UTF8.GetBytes(masterKey + "JWTSig");
        var segments = new List<string>();

        //kid changed to a string
        var header = new { alg = "HS256", typ = "JWT", kid = "0" };
        byte[] headerBytes = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(header, Formatting.None));
        byte[] payloadBytes = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(payload, Formatting.None));
        segments.Add(Base64UrlEncode(headerBytes));
        segments.Add(Base64UrlEncode(payloadBytes));
        var stringToSign = string.Join(".", segments.ToArray());
        var bytesToSign = Encoding.UTF8.GetBytes(stringToSign);
        SHA256Managed hash = new SHA256Managed();
        byte[] signingBytes = hash.ComputeHash(keyBytes);
        var sha = new HMACSHA256(signingBytes);
        byte[] signature = sha.ComputeHash(bytesToSign);
        segments.Add(Base64UrlEncode(signature));
        return string.Join(".", segments.ToArray());
    }

    // from JWT spec
    private static string Base64UrlEncode(byte[] input)
    {
        var output = Convert.ToBase64String(input);
        output = output.Split('=')[0]; // Remove any trailing '='s
        output = output.Replace('+', '-'); // 62nd char of encoding
        output = output.Replace('/', '_'); // 63rd char of encoding
        return output;
    }

您可以将 GetLogin 中的内容替换为您自己的验证码。验证后,它将返回所需的安全令牌 (JWT)。

如果您在本地主机上进行测试,请记住进入您的 web.config 文件并填写以下键

<add key="MS_MasterKey" value="Overridden by portal settings" />
<add key="MS_ApplicationKey" value="Overridden by portal settings" />

您需要在此处输入您的主密钥和应用程序密钥。当您上传它们时它们将被覆盖,但如果您在本地运行所有内容,则需要输入它们。

在 TodoItemController 的顶部添加 AuthorizeLevel 属性,如下所示

[AuthorizeLevel(AuthorizationLevel.User)]
public class TodoItemController : TableController<TodoItem>

您需要修改 TodoItemController 中的大部分函数,​​但这里是 Get All 函数的示例。

    public IQueryable<TodoItem> GetAllTodoItems()
    {
        var currentUser = User as ServiceUser;

        Guid id = new Guid(currentUser.Id);

        return Query().Where(todo => todo.UserId == id);
    }

顺便说一句,我使用 UserId 作为 Guid(唯一标识符),您需要将其添加到 todo 模型定义中。您可以将 UserId 设置为您想要的任何类型,例如Int32

Windows Phone/应用商店应用

请注意,这只是一个示例,您应该在主应用程序运行后清理代码。

在您的客户端应用上

安装 NuGet 包:Windows Azure 移动服务

进入 App.xaml.cs 并将其添加到顶部

    public static MobileServiceClient MobileService = new MobileServiceClient(
          "http://localhost:50527/",
          "[enter application key here]"
    );

在我创建的 MainPage.xaml.cs 中

public class Token
{
    public Guid UserId { get; set; }
    public String token { get; set; }
}

在主类中添加一个Authenticate函数

    private bool Authenticate(String username, String password)
    {
        HttpClient client = new HttpClient();
        // Enter your own localhost settings here
        client.BaseAddress = new Uri("http://localhost:50527/");

        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

        HttpResponseMessage response = client.GetAsync(String.Format("api/Account/Login?username={0}&password={1}", username, password)).Result;

        if (response.StatusCode == System.Net.HttpStatusCode.OK)
        {
            var token = Newtonsoft.Json.JsonConvert.DeserializeObject<Token>(response.Content.ReadAsStringAsync().Result);

            App.MobileService.CurrentUser = new MobileServiceUser(token.UserId.ToString());
            App.MobileService.CurrentUser.MobileServiceAuthenticationToken = token.token;

            return true;
        }
        else
        {
            //Something has gone wrong, handle it here
            return false;
        }           

    }

然后在 Main_Loaded 函数中

    private void MainPage_Loaded(object sender, RoutedEventArgs e)
    {
        Authenticate("test", "test");

        RefreshTodoItems();
    }

如果你在WebAPI中有断点,你会看到它进来,获取token,然后回到ToDoItemController,currentUser会被UserId和token填充。

您需要创建自己的登录页面,因为使用此方法您不能将自动创建的页面与其他身份提供者一起使用。不过我更喜欢创建自己的登录屏幕。

任何其他问题在 cmets 中告诉我,如果可以,我会提供帮助。

安全说明

记得使用 SSL。

参考文献

[]http://www.thejoyofcode.com/Exploring_custom_identity_in_Mobile_Services_Day_12_.aspx

[]http://www.contentmaster.com/azure/creating-a-jwt-token-to-access-windows-azure-mobile-services/

[]http://chrisrisner.com/Custom-Authentication-with-Azure-Mobile-Services-and-LensRocket

【讨论】:

【解决方案2】:

这正是你的做法。这个人需要 10 颗星和 5 箱啤酒!

有一件事,我使用移动服务 LoginResult 进行登录,例如: var token = Newtonsoft.Json.JsonConvert.DeserializeObject(response.Content.ReadAsStringAsync().Result);

希望现在就将它引入 Android!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-03-12
    • 2015-10-01
    • 2015-10-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多