Search code examples
asp.net-mvcsignalrauthorize

AllowAnonymous attribute in SignalR


[Authorize] // Derived from Microsoft.AspNet.SignalR.Authorize
public class ChatHub : Hub
{
    [System.Web.Mvc.AllowAnonymous] // [AllowAnonymous] doesn't be supported here
    public async Task GetEmails()
    {
        using (var db = new MyDbContext())
        {
            var users = await db.Users.ToListAsync();
            var emails = new List<string>();
            users.ForEach(x => emails.Add(x.Email));
            Clients.All.getEmails(JsonConvert.SerializeObject(emails));
        }
    }
}

My problem: I'd set breakpoint to GetEmails method but it's never hit to. Then, I signed in and tried again, it's working.

That means: [System.Web.Mvc.AllowAnonymous] doen't work within [Microsoft.AspNet.SignalR.Authorize].

So, my question is: Why doesn't namespace Microsoft.AspNet.SignalR support [AllowAnonymous] attribute? And do I need to declare AllowAnonymous attribute for that?


Solution

  • I've solved the problem: Using [System.Web.Mvc.Authorize] instead of [Authorize]. Like this:

    [System.Web.Mvc.Authorize] 
    public class ChatHub : Hub
    {
        [System.Web.Mvc.AllowAnonymous] 
        public async Task GetEmails()
        {
            // ...
        }
    }
    

    I don't understand why but it should work perfectly :)