使用Ninject自定义AuthorizationFilterAttribute中的DI

时间:2017-01-13 07:56:25

标签: c# dependency-injection ninject iauthorizationfilter

我阅读了很多关于这个主题的文章(包括SO),但仍未找到适当的解决方案,用于在AuthorizationFilterAttribute中使用Ninject进行依赖注入。目前的代码正在运行,但我非常确定应该有更好的解决方案。

public override void OnAuthorization(HttpActionContext actionContext)
   {
      var ts = GlobalConfiguration.Configuration.DependencyResolver.GetService(typeof(TokenService));
        try
            {
                var token = GetHeader(actionContext.Request);
                if (token == null)
                {
                    actionContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized)
                    {
                        Content = new StringContent("Token not found")
                    };
                    return;
                }
                else
                {
                    var tks = ts as TokenService;
                    var tkn = Task.Run(() => tks.FindToken(token)).Result;
                    if (tkn.ValidTill > DateTime.Now)
                    {
                        var us = GlobalConfiguration.Configuration.DependencyResolver.GetService(typeof(UserService));
                        var uss = us as UserService;
                        var user = Task.Run(() => uss.FindByTokenValue(token)).Result;
                        if (user != null)
                        {
                            if (!_roles.Contains(user.RoleName))
                            {
                                actionContext.Response = new HttpResponseMessage(HttpStatusCode.Forbidden)
                                {
                                    Content = new StringContent("You role permission is not enough")
                                };
                                return;
                            }
                            var identity = new Identity { Name = user.Login, IsAuthenticated = true };
                            var principal = new GenericPrincipal(identity, new[] { user.RoleName });
                            actionContext.RequestContext.Principal = principal;
                            Thread.CurrentPrincipal = principal;
                            base.OnAuthorization(actionContext);
                            _roles = null;
                        }
                        else
                        {
                            actionContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized)
                            {
                                Content = new StringContent("User not found")
                            };
                            return;
                        }
                    }
                    else
                    {
                        actionContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized)
                        {
                            Content = new StringContent($"Token valid till {tkn.ValidTill}")
                        };
                        return;
                    }
                }
            }
            catch (Exception ex)
            {
                actionContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized)
                {
                    Content = new StringContent($"Authorization error: {ex.Message}")
                };
                return;
            }
        }

1 个答案:

答案 0 :(得分:2)

你想要这样的东西:

Ninject.Web.WebApi.FilterBindingSyntax.BindingRootExtensions
       .BindHttpFilter<SomeAuthorisationFilter>(kernel,
           Http.Filters.FilterScope.Global)

在NinjectWebCommon.RegisterServices(IKernel)中。

https://github.com/ninject/Ninject.Web.WebApi/wiki/Dependency-injection-for-filters的过滤器有一些很好的文档。