DI in custom AuthorizationFilterAttribute with Ninject

449 views Asked by At

I read a lot of articles (including SO) regarding this subject, but still cannot find proper solution for dependency injection with Ninject in AuthorizationFilterAttribute. Current code is working but I'm pretty sure there should be much better solution.

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

There are 1 answers

0
Altair On BEST ANSWER

You want something like:

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

in NinjectWebCommon.RegisterServices(IKernel).

There's some good documentation for filters at https://github.com/ninject/Ninject.Web.WebApi/wiki/Dependency-injection-for-filters.