-1
이 주제와 관련하여 많은 기사 (SO 포함)를 읽었지만 AuthorizationFilterAttribute의 Ninject와의 종속성 삽입에 대한 적절한 해결책을 찾을 수 없습니다. 현재 코드가 작동하지만 훨씬 더 좋은 해결책이 있어야한다고 확신합니다. NinjectWebCommon.RegisterServices에서Ninject 사용자 정의 AuthorizationFilterAttribute의 DI
Ninject.Web.WebApi.FilterBindingSyntax.BindingRootExtensions
.BindHttpFilter<SomeAuthorisationFilter>(kernel,
Http.Filters.FilterScope.Global)
(IKernel) :
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;
}
}