Camilo Terevinto
Camilo Terevinto

Reputation: 32068

Authenticate SignalR from MVC Controller

I am learning ASP.NET Identity and SignalR among other stuff. I was able to create my own authentication system using a custom implementation of Identity. I am now trying to authenticate the user to SignalR before calling the overridden OnConnected.
After the user gets authenticated using the Cookie Authentication, the [System.Web.Mvc.Authorize] attribute passes succesfully, while the [Microsoft.AspNet.SignalR] attribute tells me that the user has not authenticated yet.

//This is my Authorize method:
[HttpGet]
public ActionResult Authorize()
{
    AuthenticationManager.SignIn(new ClaimsIdentity(new ClaimsPrincipal(User).Claims.ToArray(), "Bearer"));
    return new EmptyResult();
}

//This is my CookieAuthenticationOptions
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
    AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
    LoginPath = new PathString("/Account/Login"),
    Provider = new CookieAuthenticationProvider()
});

//On the Hub
public override Task OnConnected()
{
    string userName = Context.User.Identity.Name; //User is null?
}

What I am missing here? I have googled for some time and I'm not able to find anything, not even an idea on how to authenticate to SignalR.

Upvotes: 1

Views: 577

Answers (1)

Sirwan Afifi
Sirwan Afifi

Reputation: 10824

Most probably you're mapping SignalR before the authentication, You must map SignalR after authentication:

public void Configuration(IAppBuilder app)
{

        app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
            LoginPath = new PathString("/Home/Index")
        });

        //...

        app.MapSignalR();    
}

Upvotes: 3

Related Questions