Use AppServiceAuthentication with Signal

I am trying to create a notification mechanism in my backend application (azure mobile app). I managed to override the Authorize attribute to make the notification center available only to authorized users.

public class QueryStringBearerAuthorizeAttribute : Microsoft.AspNet.SignalR.AuthorizeAttribute
{
    public override bool AuthorizeHubConnection(HubDescriptor hubDescriptor, IRequest request)
    {

        try
        {
            var user = (request.Environment["server.User"] as ClaimsPrincipal).FindFirst(ClaimTypes.NameIdentifier).Value;
            if (user == null)
                return false;
            return true;

        }
        catch(Exception ex)
        {
            return false;
        }
    }

    public override bool AuthorizeHubMethodInvocation(IHubIncomingInvokerContext hubIncomingInvokerContext, bool appliesToMethod)
    {
        var connectionId = hubIncomingInvokerContext.Hub.Context.ConnectionId;
        // check the authenticated user principal from environment
        var environment = hubIncomingInvokerContext.Hub.Context.Request.Environment;
        var principal = environment["server.User"] as ClaimsPrincipal;
        if (principal != null && principal.Identity != null && principal.Identity.IsAuthenticated)
        {
            // create a new HubCallerContext instance with the principal generated from token
            // and replace the current context so that in hubs we can retrieve current user identity
            hubIncomingInvokerContext.Hub.Context = new HubCallerContext(new ServerRequest(environment), connectionId);
            return true;
        }
        else
        {
            return false;
        }
    }
}

In the startup.cs file:

 var authorizer = new Hubs.QueryStringBearerAuthorizeAttribute();

 var module = new AuthorizeModule(authorizer, authorizer);
 GlobalHost.HubPipeline.AddModule(module);
 app.MapSignalR();

In a console application (C #), I can connect to the notification hub by providing the X-ZUMO-AUTH header. However, it is not possible to set the title from the web application.

Is there a way to use a query string to check an authentication token instead of a header?

+4
source share
1 answer

To add an XHR header, you can use

var url = "www.example-mobile-azure-app.com";
var xhr = new XMLHttpRequest();
xhr.setRequestHeader('X-ZUMO-APPLICATION', 'Application-Key');
xhr.open('get', url, true);
xhr.responseType = 'json';
xhr.onload = function () {
    var status = xhr.status;
    if (status == 200) {
        // do what you need to do
    } else {
        // oh no an error occurred -.-
    }
};
xhr.send();
-1
source

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


All Articles