AuthorizeAttribute和POST异步

时间:2018-12-20 22:37:22

标签: 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令牌,所以我去写了一个.NET Core项目,该项目在成功通过身份验证后生成并返回JWT令牌。我使用Postman将其发布到控制器进行了测试,并且可以正常工作。

现在,在我当前的代码中,我想在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的限制,我无法执行此操作。我在这里能做什么,有没有办法从这里继续调用异步调用,还是我必须将逻辑移到其他地方?

1 个答案:

答案 0 :(得分:3)

如果您使用正确的重载,那不是问题:

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()并重新使用。