c# - AuthorizeAttribute 和 POST 异步
问题描述
我继承了一个.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 令牌,因此我编写了一个 .NET Core 项目,该项目在成功验证后生成并返回 JWT 令牌。我使用 Postman 测试了这件作品以 POST 到控制器并且它可以工作。
现在,在我当前的代码中,我想在 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";
}
}
但我无法让它工作,response.Status 正在返回“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()
从那里取出并重复使用它。
推荐阅读
- python - OpenCV 像素块检测(检测白色像素块)
- php - 如何在wordpress插件的自定义元框中保存多个复选框值?
- laravel - Creating zip of multiple files and download in laravel
- shell - to append the file using vi/vim using shell script
- c++ - Collect template parameters at compile time
- c# - Return
string for json - docker - 具有 DHCP 分配地址的 Docker 容器
- python - 如何构建包含集合项的表单
- mysql - MySQL 与 Docker/Kubernetes
- javascript - 如何检测我的页面是否已加载到 div 中?