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