我希望能够使用用户名和密码登录到我的身份数据库并检索 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);
}
}