如何让 JWT 在 Autorest 生成的 SDK 中工作? (ASP.NET 核心 2.0)

How do I get JWT working in Autorest generated SDK? (ASP.NET Core 2.0)

我希望能够使用用户名和密码登录到我的身份数据库并检索 JWT。然后我想使用 JWT 从我的 API.

安全地访问数据

我发现VS2017生成的SDK代码使用的是旧版autorest,所以改用Azure Autorest

api和SDK都是ASP.NETCore 2.0

生成我使用的SDK

AutoRest -mynamespace mytrack.Client -CodeGenerator CSharp -Modeler 
Swagger -Input swagger.json -PackageName mytrack.client -AddCredentials true

版本显示为

AutoRest code generation utility [version: 2.0.4262; node: v8.11.2]

我把测试写成

using System;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Newtonsoft.Json.Linq;
using swagger; // my name space from the autorest command, not to be confused with swagger itself.
using swagger.Models;

namespace CoreClientTest
{
    [TestClass]
    public class MyTests
    {
        [TestMethod]
        public void TestMethod1()
        {
            try
            {
                GetMyJob().Wait();
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
        }

        private static async Task GetMyJob()
        {
            var tokenRequest = new TokenRequest
            {
                Username = "myusername",
                Password = "mypassword"
            };

            var credentials = new TokenCredentials("bearer token");
            var uri = new Uri("https://localhost:44348", UriKind.Absolute);
            var tokenClient = new Track3API(uri, credentials);
            var tokenResponse = await tokenClient.ApiRequestTokenPostWithHttpMessagesAsync(tokenRequest);
            var tokenContent = await tokenResponse.Response.Content.ReadAsStringAsync();
            var tokenString = JObject.Parse(tokenContent).GetValue("token").ToString();
            var creds2 = new TokenCredentials(tokenString);
            var client2 = new Track3API(uri, creds2);
            var result = await client2.ApiJobsByIdGetWithHttpMessagesAsync(1);
            var response = result.Response;
            Console.WriteLine(response.ToString());
        }
    }
}

我可以看到结果是OK的,我可以看到里面的token。 我看不到 return 作业

api中的方法有

[Produces("application/json")]
[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
[Route("api/jobs")]
public class JobController : Controller
{


/// <summary>
/// Returns Job Header for Id
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
[HttpGet("{id}", Name = "Get")]
public IActionResult Get(int id)
{
    var header1 = new JobHeader
    {
        JobNumber = "1234",
        Id = id,
        CustomerPurchaseOrderNumber = "fred"
    };
    return Ok(header1);
}

}

您应该在 class 上应用 DataContract 属性,这样当 RestClient 使用服务引用时,它也会生成类型。

阅读here

您还应该在 属性 上附加 DatamMember 属性。见下面的例子

[DataContract]
class Person 
{
    [DataMember]
    public string Name {get; set; }

    [DataMember]
    public int Id {get; set; }

    public Person(string name, int id)
    {
        this.Name = name;
        this.Id = id;
    }
}

当 Rest Client 使用服务时,它会在客户端为那些带有 DataContract.

属性的 classes 生成 classes

终于可以用了。 我在 Andrei Dzimchuk's blog 找到了关于设置令牌

的提示
using System;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using swagger;
using swagger.Models;

namespace CoreClientTest
{
    [TestClass]
    public class MyTests
    {
        [TestMethod]
        public void TestMethod1()
        {
            try
            {
                 GetMyJob().Wait();
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
        }

        private static async Task<JobHeader> GetMyJob()
        {
            var tokenRequest = new TokenRequest
            {
                Username = "myusername",
                Password = "mypassword"
            };
            var credentials = new TokenCredentials("bearer token");
            var uri = new Uri("https://localhost:44348", UriKind.Absolute);
            var tokenClient = new Track3API(uri, credentials);
            var tokenResponse = await tokenClient.ApiRequestTokenPostWithHttpMessagesAsync(tokenRequest);
            var tokenContent = await tokenResponse.Response.Content.ReadAsStringAsync();
            var tokenString = JObject.Parse(tokenContent).GetValue("token").ToString();
            var creds2 = new TokenCredentials(tokenString);
            var client2 = new Track3API(uri, creds2);
            var result = await client2.ApiJobsByIdGetWithHttpMessagesAsync(1);
            string resultContent = await result.Response.Content.ReadAsStringAsync();
            var job = JsonConvert.DeserializeObject<JobHeader>(resultContent);
            Console.WriteLine(job.JobNumber);
            return job;

        }
    }
}