小编joz*_*olo的帖子

使用Web API对JWT令牌进行单元测试

我正在尝试使用Web API2,JWT,Microsoft.IdentityModel.JsonWebTokens 5.2.422和本文中概述的令牌验证逻辑:http : //www.decatechlabs.com/secure-webapi-using-jwt

当我重复本文中的步骤(包括通过Restlet测试API)时,一切都对我的项目非常有用。但是,我正在尝试对该项目使用测试驱动开发(TDD),并且理想情况下,我想测试所有工作在我的测试中是否有效,包括令牌验证处理程序。如果我在单元测试中直接调用我的控制器,就可以对其进行测试,但这可以绕过实际的令牌验证处理程序。因此,我尝试使用自托管HTTP正确行使完整的API,包括所有令牌验证处理程序逻辑。这是我获得令牌的完整单元测试,然后将令牌传递给需要授权的第二种方法:

[TestMethod]

public void GetAuthorizedStatus_SelfHostedHTTP()
{
    HttpServer server = TestAPIHelper.GenerateTestServer();

    using (HttpMessageInvoker client = new HttpMessageInvoker(server))
    {
        string token = string.Empty;

        using (HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, loginURL))
        {
            var stringContent = new StringContent(JsonConvert.SerializeObject(TestAPIHelper.loginObject), Encoding.UTF8, "application/json");
            request.Content = stringContent;

            using (HttpResponseMessage response = client.SendAsync(request, System.Threading.CancellationToken.None).Result)
            {
                Assert.AreEqual(HttpStatusCode.OK, response.StatusCode, "Error getting token from login portion");

                token = response.Content.ReadAsAsync<string>().Result;
                Assert.IsTrue(token.Length > 50);
            }
        }

        using (HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, authorizedStatusURL))
        {
            request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", …
Run Code Online (Sandbox Code Playgroud)

c# tdd unit-testing jwt asp.net-web-api2

5
推荐指数
1
解决办法
1463
查看次数

标签 统计

asp.net-web-api2 ×1

c# ×1

jwt ×1

tdd ×1

unit-testing ×1