c# - AuthorizeAttribute 和 POST 异步

标签 c# .net asp.net-web-api

我继承了一个.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/

相关文章:

c# - 如何在 ASP.net Web API 中使用详细参数隐藏/显示结果 JSON

visual-studio-2013 - 没有服务引用的项目。错误 : Type 'Newtonsoft.Json.Linq.JToken' is a recursive collection data contract which is not supported.

c# - 快速查询 Active Directory

c# - 是什么导致在BackgroundAudioPlayer.get_Position()出现System.Runtime.InteropServices.COMException?

c# - 关于ASP.Net Postback的一些问题

c# - 使用托管代码包装器从 64 位托管代码调用 32 位非托管代码的最佳方式

c# - 如何远程调试数据库的 ASP.NET MVC bug?

c# - 在 Ubuntu 中读取 pfx 证书以创建 X509

c# - 创建一个没有无限实例化的实例

java - 对象的原始成员是在堆上还是在栈上?