pcibraro / hawknet

Hawk protocol implementation for .NET
MIT License
114 stars 35 forks source link

AllowAnonymous doesn't work #5

Closed CheloXL closed 11 years ago

CheloXL commented 11 years ago

Hi, I just downloaded and tested the project, since I need something similar, and I found that the AllowAnonymous attribute it is not working at all.

In your test that seems to work because you are already using and authorized client. If you modify your test code (lines 64 to 69 in Example.cs) to the following, you will see the issue:

var client2 = new HttpClient();
var request2 = new HttpRequestMessage(HttpMethod.Get, "http://localhost:8091/Api/HelloWorldAnonymous");
request2.Headers.Host = "localhost";

var response2 = client2.SendAsync(request2).Result;
var message2 = response2.Content.ReadAsStringAsync().Result;
Console.WriteLine("Response {0} - Http Status Code {1}", message2, response2.StatusCode);
pcibraro commented 11 years ago

Yes, that's true. However, I am not sure there is possible to put a quick fix for that. If the client does not send an authorization header, the Hawk filter must return a challenge. The check about AllowAnonymous is performed later in the pipeline. The message handler does not even have access to the api method via reflection to get those attributes. What you can do is to configure the HawkMessagehandler for certain routes as I did here in this post,

http://weblogs.asp.net/cibrax/archive/2013/02/25/message-handlers-per-route-in-asp-net-web-api.aspx

I will remove that example with AllowAnonymous as it is broken as you said.

Thanks Pablo.

CheloXL commented 11 years ago

Well, actually, after I posted the above I started to dig a bit more and found a way to solve (at least on my project, but it should work on this too). Basically, what I'm doing is the following:

1) In the SendAsync method, I first check if I have an Authorization header and if Scheme matches my scheme. If so, goto 2 else goto 3 :) 2) Get a principal based on the request headers (here it is up to the implementation) 3) return a base.SendAsync, but use a continuation (ContinueWith) and check if the result.StatusCode of the continuation is Unauthorized and if the Authorization is null or the Scheme is null or empty. In that case, send the challenge.

So later, the Authorize attribute on the action will check for an authorized principal and if it is not, it will return an Unauthorized response that will be catch'ed by the continuation.

I already have that implemented and it seems to be working fine.

pcibraro commented 11 years ago

I found a way to fix this issue. The challenge is only returned when the upper layer returns Unauthorized. It's in the latest version. Thanks