3

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

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

api 和 SDK 都是 ASP.NET Core 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());
        }
    }
}

我可以看到结果正常,我可以看到其中的令牌。我看不到返回工作

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);
}

}

4

2 回答 2

1

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

在这里阅读。

您还应该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

于 2018-05-19T06:30:30.420 回答
0

最后它正在工作。我在Andrei Dzimchuk 的博客上找到了关于设置令牌的提示

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;

        }
    }
}
于 2018-05-29T08:46:58.410 回答