我继承了一个.NET 4.6框架中的WEB API项目。它通过使用 System.Web.Http.AuthorizeAttribute 实现自定义身份验证,例如:
public class AuthorizeAttribute : System.Web.Http.AuthorizeAttribute
{
public override void OnAuthorization(HttpActionContext actionContext)
{
//Call authentication logic against DB.
}
}
我自己想改进它以使用新的 JWT token ,因此我编写了一个 .NET Core 项目,该项目在成功身份验证后生成并返回 JWT token 。我使用 Postman 测试了这篇文章以 POST 到 Controller ,它可以工作。
现在,在我当前的代码中,我想在 OnAuthorization() 内调用 WEB-API 调用,如下所示:
public class AuthorizeAttribute : System.Web.Http.AuthorizeAttribute
{
public override void OnAuthorization(HttpActionContext actionContext)
{
var auth = actionContext.Request.Headers.Authorization;
string[] userInfo = Encoding.Default.GetString(Convert.FromBase64String(auth.Parameter)).Split(':');
Profile user = new Profile();
user.UserName = userInfo[0];
user.Password = userInfo[1];
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://localhost:31786");
var response = client.PostAsJsonAsync("api/token/request", user);
//I hope to get the JWT Token back here or by this time the server should return it or set it in a cookie.
return "OK";
}
}
但我无法让它工作,响应。状态正在返回“WaitingForActivation”。
我知道为什么会收到此消息,因为我应该更改此调用以进行等待并将函数的签名更新为 Task。
await client.PostAsJsonAsync("api/token", content);
但是,由于 System.Web.Http.AuthorizeAttribute
的限制,我无法执行此操作。我在这里可以做什么,有没有办法仍然从这里调用异步调用,或者我是否必须将逻辑移到其他地方?
最佳答案
如果您使用正确的重载,这不是问题:
public override async Task OnAuthorizationAsync(HttpActionContext actionContext, CancellationToken token)
{
var auth = actionContext.Request.Headers.Authorization;
string[] userInfo = Encoding.Default.GetString(Convert.FromBase64String(auth.Parameter)).Split(':');
Profile user = new Profile();
user.UserName = userInfo[0];
user.Password = userInfo[1];
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://localhost:31786");
var response = await client.PostAsJsonAsync("api/token/request", user);
//I hope to get the JWT Token back here or by this time the server should return it or set it in a cookie.
return "OK";
}
顺便说一句,您应该从那里取出 new HttpClient()
并重新使用它。
关于c# - AuthorizeAttribute 和 POST 异步,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53876999/