SignalR Autofac Inject Authorize Attribute

一曲冷凌霜 提交于 2019-12-24 00:27:51

问题


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:


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



来源:https://stackoverflow.com/questions/34190207/signalr-autofac-inject-authorize-attribute

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!