本文介绍了在自定义控制器工厂中进行通用授权的良好做法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的控制器共享一个客户端ID.路线:
My controllers share a client id. Route:
clients/{clientId}/{controller}/{action}/{id}示例网址:
clients/1/orders/details/1 clients/2/children/index clients/2/cars/create您需要获得客户的适当授权.我不想在每个控制器中都执行相同的客户端授权.我想到了在这样的自定义控制器工厂中进行自动化的想法:
You need proper authorization for a client. I don't want to do the same client authorization in every controller. I came up with the idea to do the autorization in a custom controller factory like this:
public class CustomControllerFactory : DefaultControllerFactory { private readonly IAuthService _authService; public CustomControllerFactory(IAuthService authService) { _authService = authService; } protected override IController GetControllerInstance( RequestContext requestContext, Type controllerType) { var doAuth = requestContext.RouteData.Values.ContainsKey("clientId"); if (doAuth) { var principal = requestContext.HttpContext.User; var clientId = long.Parse( requestContext.RouteData.Values["clientId"].ToString()); var authorized = _authService.Client(principal, clientId); if (!authorized) { return new AuthController(); } } return base.GetControllerInstance(requestContext, controllerType); } }您认为这是一种好习惯吗?为什么?
Do you consider this a good practice or not? Why?
推荐答案不,我不认为这是一个好习惯.自定义 AuthorizeAttribute 似乎更适合处理授权而不是控制器工厂.
No, I don't consider this as a good practice. A custom AuthorizeAttribute seems far more adapted to handle authorization rather than a controller factory.
更多推荐
在自定义控制器工厂中进行通用授权的良好做法?
发布评论