SignalR Autofac Inject Authorize Attribute

2019-07-16 00:01发布

I'm trying to figure out a way to inject dependencies into my AuthorizeAttribute in SignalR similar to the way it is done in WebAPI.

In Web API I know I can call builder.RegisterWebApiFilterProvider(config); but I can't quite seem to find an equivalent for SignalR. The closest thing I can find that looks like it might do the trick is the PropertiesAutowired() method.

I have tried builder.RegisterType<MyAuthorizationAttribute>.PropertiesAutowired(); where my attribute looks like

public class MyAuthorizationAttribute : AuthorizeAttribute
{
    public IRepository Repository { get; set; }

    public override bool AuthorizeHubConnection(HubDescriptor hubDescriptor, 
        IRequest request)
    {
        Repository.QueryStoredProcedure("Test");
        ...
    }

    protected override bool UserAuthorized(IPrincipal user)
    {
        ...
    }
}

But the instance of Repository is null every time.

1条回答
放我归山
2楼-- · 2019-07-16 00:58

According to http://eworldproblems.mbaynton.com/2012/12/signalr-hub-authorization/

Register your MyAuthorizationAttribute in Autofac:

builder.RegisterType<MyAuthorizationAttribute>().PropertiesAutowired();

then before app.MapSignalR():

 var myModule = container.Resolve<MyAuthorizationAttribute >(); 
 GlobalHost.HubPipeline.AddModule(new AuthorizeModule(myModule, myModule));

With this piece of code, you can set global authorize modules for hub connections and for method invocation.

Optionally, this module may be instantiated with IAuthorizeHubConnection and IAuthorizeHubMethodInvocation authorizers that will be applied globally to all hubs and hub methods.

Read more here https://msdn.microsoft.com/en-us/library/microsoft.aspnet.signalr.hubs.authorizemodule(v=vs.118).aspx

查看更多
登录 后发表回答