首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >是否可以在CustomAttribute中重新绑定IPrincipal?

是否可以在CustomAttribute中重新绑定IPrincipal?
EN

Stack Overflow用户
提问于 2021-02-19 08:43:36
回答 1查看 26关注 0票数 0

背景

我们有一个Web API2项目,我们正在把它变成我们的“公共api”。对于对我们的api的请求,我们使用一个自定义属性(ApiKeyAuthorize)根据API键查找用户,然后使用他们的信息创建一个ClaimsPrincipal。

此外,依赖链中的一些类在其构造函数中有一个IPrincipal,这要求我们在NinjectWebCommon.cs中绑定到IPrincipal。我们将其绑定到HttpContext.Current.User。

问题

问题是,一旦Ninject完成了绑定,我就无法重新绑定IPrincipal。在我的属性逻辑被触发之后,HttpContext.Current.User是正确的ClaimsPrincipal,但是注入的IPrincipal没有改变。我试着给kernal.Rebind打电话,但没起作用。有没有一种方法可以不用用Lazy<T>重写所有现有类,也不用用Thread.CurrentUser替换所有IPrincipal,就可以重新绑定、推迟绑定

代码

来自NinjectWebCommon.js

代码语言:javascript
复制
        private static IKernel CreateKernel()
        {
            var kernel = new StandardKernel();
            kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel);
            kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>();
            kernel.Bind<IPrincipal>().ToMethod(ctx => HttpContext.Current.User);

            RegisterServices(kernel);
            _kernel = kernel;
            return kernel;
        }

ApiKeyAuthorizeAttribute.cs

代码语言:javascript
复制
public override void OnAuthorization(HttpActionContext actionContext)
        {
            var apiKey = actionContext.Request.Headers.GetValues("apiKey")?.FirstOrDefault();

            // do lookup on the user and populate user object

            var identity = new ClaimsIdentity("Signature", "subject", "role");
            identity.AddClaim(new Claim("subject", user.Email));
            var principal = new ClaimsPrincipal(identity);
            actionContext.RequestContext.Principal = principal;
            Thread.CurrentPrincipal = newIdentity;

            // Is it possible to Rebind here???

            base.OnAuthorization(actionContext);
        }

        // I added this to try to rebind, but it doesn't work
        internal static void RebindCurrentUser(System.Security.Claims.ClaimsPrincipal newIdentity)
        {
            _kernel.Rebind<IPrincipal>().ToConstant(newIdentity);
        }

依赖链中的类ctor

代码语言:javascript
复制
public class Foo
{
    private readonly ClaimsPrincipal _currentUser;
    public Foo(IPrincipal currentUser)
    {
       _currentUser = (ClaimsPrincipal)currentUser;
       // _currentUser doesn't have claims
       // Thread.CurrentUser does have claims
    }
}
EN

回答 1

Stack Overflow用户

发布于 2021-03-25 20:57:54

您绑定到HttpContext.Current.User,但填充actionContext.RequestContext.PrincipalThread.CurrentPrincipal。它们不是同一个对象。尝试在HttpContext.Current.User上设置新的主体。

此外,不确定是否粘贴错误,但newIdentity不存在于您的代码中。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66270266

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档