2017-01-13 1 views
-1

Je lis beaucoup d'articles (y compris SO) concernant ce sujet, mais ne trouve toujours pas la solution appropriée pour l'injection de dépendance avec Ninject dans AuthorizationFilterAttribute. Le code actuel fonctionne mais je suis sûr qu'il devrait y avoir une meilleure solution.DI dans custom AuthorizationFilterAttribute avec 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; 
      } 
     } 

Répondre