我正在尝试实现IAuthenticationFilter( Web Api 2风格, 而不是 MVC风格),我正在努力执行代码的顺序。 我原本期望在任何基于控制器的东西之前运行身份验证过滤器,这样我就可以设置适当的主体,然后在某种基本ApiController中从我的DbContext加载相关的用户数据。
这是我追求的流程:
AuthenticationFilter ==> BaseController ==> Controller/ActionAuthenticationFilter: -测试授权标头,如果一切正常,则设置主体。
BaseController: -使用principal来查找数据库中的完整用户记录并将其分配给protected属性。
控制器/操作: -正常完成操作,可以访问BaseController中设置的用户记录。
我不知道将代码放在BaseController中的哪个位置,以便在验证过滤器之后但在解析的控制器/操作之前执行它。
题
所以我的问题是双重的:我是否采取了错误的方式? 如果没有,我该如何执行第2步?
I'm trying to implement an IAuthenticationFilter (the Web Api 2 flavour, not the MVC flavour) and I'm struggling with the order the code is executed. I would have expected the Authentication filter to be run before any controller-based stuff, so that I could set the appropriate principal and then load the relevant user data from my DbContext in some kind of base ApiController.
This is the flow I'm after:
AuthenticationFilter ==> BaseController ==> Controller/ActionAuthenticationFilter:- Test Authorization header and set the principal if all is well.
BaseController:- Use the principal to find the full User record in database and assign it to a protected property.
Controller/action:- Complete action as normal, has access to the user record as set in the BaseController.
I'm not sure where to put the code in a BaseController in order to have it execute after the authentication filter, but before the resolved controller/action.
Question
So my question is two-fold: Am I going about this the wrong way? If not, how should I be performing step 2?
最满意答案
这就是我最终做的事情。 在我的BaseController中,我创建了一个名为LoggedInUser的受保护属性,并创建了一个特殊的getter:
private User _loggedInUser; protected User LoggedInUser { get { if (_loggedInUser != null) return _loggedInUser; var identity = RequestContext.Principal.Identity; var userId = identity.GetUserId(); _loggedInUser = MyDbContext.Users.Find(userId); return _loggedInUser; } }这允许我将代码保存在一个位置BaseController中,同时仍然允许我推迟获取用户的尝试,直到进行身份验证。
Here's what I ended up doing. In my BaseController I made a protected property called LoggedInUser, and made a special getter:
private User _loggedInUser; protected User LoggedInUser { get { if (_loggedInUser != null) return _loggedInUser; var identity = RequestContext.Principal.Identity; var userId = identity.GetUserId(); _loggedInUser = MyDbContext.Users.Find(userId); return _loggedInUser; } }This allowed me to keep the code in one place, the BaseController, while still allowing me to defer the attempt to fetch the user until after the authentication has taken place.
更多推荐
发布评论