User Principle in SignalR Hub

I am trying to use my own principle in my SignalR Hub OnConnected method. I tried the following:

  • Context.Request.GetHttpContext (). User
  • HttpContext.Current.User
  • Thread.CurrentPrincipal

but no luck ..

He continues to throw an error:

Unable to cast object of type 'System.Web.Security.RolePrincipal' to type 'MVCSample.Biz.Profile.MyCustomPrincipal'.

Is there access to custom principles in SignalR hubs?

Thank!

This is my hub code:

[Authorize]
public class MBHub : Hub
{
    private readonly ILifetimeScope _hubLifetimeScope;
    private readonly IUserService _userService;        

    public MBHub(ILifetimeScope lifetimeScope)
    {
        _hubLifetimeScope = lifetimeScope.BeginLifetimeScope("AutofacWebRequest");
        _userService = _hubLifetimeScope.Resolve<IUserService>();
    }

    public override Task OnConnected()
    {
        //var idn = (MVCSample.Biz.Profile.MyCustomIdentity)Thread.CurrentPrincipal; <--- THIS DID NOT WORK

        //var idn = (MVCSample.Biz.Profile.MyCustomIdentity)HttpContext.Current.User; <--- THIS DID NOT WORK

        System.Web.HttpContextBase httpContext = Context.Request.GetHttpContext();

        var idn = (MVCSample.Biz.Profile.MyCustomIdentity)httpContext.User.Identity; // <--- THIS IS MY FINAL TRY, DID NOT WORK

        string userName = idn.Name;
        string city = idn.City;
        string connectionId = Context.ConnectionId;

        _userService.AddConnection(connectionId, userName, city, Context.Request.Headers["User-Agent"]);

        return base.OnConnected();
    }


    protected override void Dispose(bool disposing)
    {
        // Dipose the hub lifetime scope when the hub is disposed.
        if (disposing && _hubLifetimeScope != null)
            _hubLifetimeScope.Dispose();

        base.Dispose(disposing);
    }

}
+4
source share
1 answer

You must create your own Authorize attribute.

public class MyAuthorizeAttribute : AuthorizeAttribute
{
    public override bool AuthorizeHubConnection(HubDescriptor hubDescriptor, IRequest request)
    {
        //put our custom user-principal into a magic "server.User" Owin variable
        request.Environment["server.User"] = new MyCustomPrincipal(); //<!-THIS!

        return base.AuthorizeHubConnection(hubDescriptor, request);
    }
}

And then apply this attribute to your hub.

,

0

Source: https://habr.com/ru/post/1537432/


All Articles