In our MVC project we are attempting to make everything as generic as possible.
Because of this we want to have one authentication class/method which covers all our methods.
As a example: The following code is a MVC class which can be called to from a client
public class Test
{
public void Test()
{
}
public int Test2(int i)
{
return i
}
public void Test3(string i)
{
}
}
A customer of our webservice can use a service reference to get access to Test(), Test2() and Test3().
Now i'm searching for a class, model, interface or anything else which I can use to alter the access to the method (Currently using [PrincipalPermission] attribute) as well as alter the parameter value.
Example:
Customer A calls Test2(150)
The class/method checks whether Customer A has access to Test2. The class/method validates the user but notices that the user does not have access to 150. He only has access to 100.So the class/method sets the parameter to 100 and lets it follow through on it's journey.
Customber B class Test()
The class/method checks whether Customer B has access to Test. After validation it shows that the user does not have access so it throws a SecurityException.
My question:
In what class, interface, attribute or whatever can I best do this?
(ps. As example i've only used authentication and parameter handling, but we plan to do a lot more in this stage.)
Edit
I notice most, if not all, assume I'm using actionResults. So i'd like to state that this is used in a webservice where we provide our customers with information from our database. In no way will we come in contact with a ActionResult during the requests to our webservice. (Atleast, not our customers)
Authentication can also be done through an aspect. The aspect oriented paradigm is designed to honor those so-called cross-cutting concerns. Cross-cutting concerns implemented in the "old-fashioned" oo-way make your business logic harder to read (like in Nick's example above) or even worse to understand, because they don't bring any "direct" benefit to your code:
public ActionResult YourAction(int id) {
if (!CustomerCanAccess(id)) {
return new HttpUnauthorizedResult();
}
/* the rest of your code */
}
The only thing you want here is /* the rest of your code */ and nothing more.
Stuff like logging, exception handling, caching and authorization for example could be implemented as an aspect and thus be maintained at one single point.
PostSharp is an example for an aspect-oriented C# framework. With PostSharp you could create a custom aspect and then annotate your method (like you did with the PrincipalPermissionAttribute). PostSharp will then weave your aspect code into your code during compilation. With the use of PostSharp aspects it would be possible to hook into the method invocation authenticating the calling user, changing method parameters or throw custom exceptions (See this blog post for a brief explanation how this is implemented).
There isn't a built-in attribute that handles this scenario.
I find it's usually best to just do something like this:
public ActionResult YourAction(int id) {
if (!CustomerCanAccess(id)) {
return new HttpUnauthorizedResult();
}
/* the rest of your code */
}
This is as simple as it gets and easy to extend. I think you'll find that in many cases this is all you need. It also keeps your security assertions testable. You can write a unit test that simply calls the method (without any MVC plumbing), and checks whether the caller was authorized or not.
Note that if you are using ASP.Net Forms Authentication, you may also need to add:
Response.SuppressFormsAuthenticationRedirect = true;
if you don't want your users to be redirected to the login page when they attempt to access a resource for which they are not authorized.
Here's how I've made my life simpler.
Never use simple values for action arguments. Always create a class that represents the action arguments. Even if there's only one value. I've found that I usually end up being able to re-use this class.
Make sure that all of teh properties of this class are nullable (this keeps you from running into default values (0 for integers) being automatically filles out) and thatallowable ranges are defined (this makes sure you don't worry about negative numbers)
Once you have a class that represents your arguments, throwing a validator onto a property ends up being trivial.
The thing is that you're not passing a meaningless int. It has a purpose, it could be a product number, an account number, etc. Create a class that has that as a property (e.g An AccountIdentifier class with a single field called 'id). Then all you have to do is create a [CurrentUsedCanAccessAccountId] attribute and place it on that property.
All your controller has to do is check whether or not ModelState.IsValid and you're done.
There are more elegant solutions out there, such as adding an action filter to the methods that would automatically re-direct based on whether or not the user has access to a specific value for the parameter, but this will work rather well
First, just to say it, that your own methods are probably the most appropriate place to handle input values (adjust/discard) - and with the addition of Authorize and custom filter actions you can get most done, and the 'MVC way'. You could also go the 'OO way' and have your ITest interface, dispatcher etc. (you get more compiler support - but it's more coupled). However, let's just presume that you need something more complex...
I'm also assuming that your Test is a controller - and even if it isn't it can be made part of the 'pipeline' (or by mimicking what MVC does), And with MVC in mind...
One obvious solution would be to apply filters, or action filters via
ActionFilterAttribute
Class
(like Authorize etc.) - by creating your own custom attribute and
overriding OnActionExecuting etc.
And while that is fine, it's not going to help much with parameters manipulation as you'd have to specify the code 'out of place' - or somehow inject delegates, lambda expressions for each attribute.
It is basically an interceptor of some sort that you need - which allows you to attach your own processing. I've done something similar - but this guy did a great job explaining and implementing a solution - so instead of me repeating most of that I'd suggest just to read through that.
ASP.NET MVC controller action with Interceptor pattern (by Amar, I think)
What that does is to use existing MVC mechanisms for filters - but it exposes it via a different 'interface' - and I think it's much easier dealing with inputs. Basically, what you'd do is something like...
[ActionInterceptor(InterceptionOrder.Before, typeof(TestController), "Test1")]
public void OnTest1(InterceptorParasDictionary<string, object> paras, object result)
The parameters and changes are propagated, you have a context of a sort so you can terminate further execution - or let both methods do their work etc.
What's also interesting - is the whole pattern - which is IOC of a
sort - you define the intercepting code in another class/controller
all together - so instead of 'decorating' your own Test methods -
attributes and most of the work are placed outside.
And to change your parameters you'd do something like...
// I'd create/wrap my own User and make this w/ more support interfaces etc.
if (paras.Count > 0 && Context.User...)
{
(paras["id"] as int) = 100;
}
And I'm guessing you could further change the implementation for your own case at hand.
That's just a rough design - I don't know if the code there is ready for production (it's for MVC3 but things are similar if not the same), but it's simplistic enough (when explained) and should work fine with some minor adjustments on your side.
I'm not sure if I understood your question, but it looks like a model binder can help.
Your model binder can have an interface injected that is responsible for determining if a user has permissions or not to a method, and in case it is needed it can change the value provided as a parameter.
ValueProviders, that implement the interface IValueProvider, may also be helpful in your case.
I believe the reason you haven't gotten ay good enough answer is because there are a few ambiguities in your question.
First, you say you have an MVC class that is called from a client and yet you say there are no ActionResults. So you would do well to clarify if you are using asp.net mvc framework, web api, wcf service or soap (asmx) web service.
If my assumption is right and you are using asp.net mvc framework, how are you defining web services without using action results and how does your client 'call' this service.
I am not saying it is impossible or that what you may have done is wrong, but a bit more clarity (and code) would help.
My advice if you are using asp.net mvc3 would be to design it so that you use controllers and actions to create your web service. all you would need to do would be to return Json, xml or whatever else your client expects in an action result.
If you did this, then I would suggest you implement your business logic in a class much like the one you have posted in your question. This class should have no knowledge of you authentication or access level requirements and should concentrate solely on implementing the required business logic and producing correct results.
You could then write a custom action filter for your action methods which could inspect the action parameter and determine if the caller is authenticated and authorized to actually access the method. Please see here for how to write a custom action filter.
If you think this sounds like what you want and my assumptions are correct, let me know and I will be happy to post some code to capture what I have described above.
If I have gone off on a tangent, please clarify the questions and we might be one step closer to suggesting a solution.
p.s. An AOP 'way of thinking' is what you need. PostSharp as an AOP tool is great, but I doubt there is anything postsharp will do for you here that you cannot achieve with a slightly different architecture and proper use of the features of asp.net mvc.
first create an attribute by inheriting from ActionFilterAttribute (system.web.mvc)
then override OnActionExecuting method and check if user has permission or not
this the example
public class CheckLoginAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (!Membership.IslogedIn)
{
filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary
{
{ "area",""},
{ "action", "login" },
{ "controller", "user" },
{ "redirecturl",filterContext.RequestContext.HttpContext.Request.RawUrl}
});
}
}
}
and then, use this attribute for every method you need to check user permission
public class Test
{
[ChecklLogin]
public void Test()
{
}
[ChecklLogin]
public int Test2(int i)
{
return i
}
[ChecklLogin]
public void Test3(string i)
{
}
}
Related
Update#2 as of year 2022
All these years have passed and still no good answer.
Decided to revive this question.
I'm trying to implement something like the idea I'm trying to show with the following diagram (end of the question).
Everything is coded from the abstract class Base till the DoSomething classes.
My "Service" needs to provide to the consumer "actions" of the type "DoSomethings" that the service has "registered", at this point I am seeing my self as repeating (copy/paste) the following logic on the service class:
public async Task<Obj1<XXXX>> DoSomething1(....params....)
{
var action = new DoSomething1(contructParams);
return await action.Go(....params....);
}
I would like to know if there is anyway in C# to "register" all the "DoSomething" I want in a different way? Something more dynamic and less "copy/paste" and at the same time provide me the "intellisense" in my consumer class? Somekind of "injecting" a list of accepted "DoSomething" for that service.
Update#1
After reading the sugestion that PanagiotisKanavos said about MEF and checking other options of IoC, I was not able to find exactly what I am looking for.
My objective is to have my Service1 class (and all similar ones) to behave like a DynamicObject but where the accepted methods are defined on its own constructor (where I specify exactly which DoSomethingX I am offering as a method call.
Example:
I have several actions (DoSomethingX) as "BuyCar", "SellCar", "ChangeOil", "StartEngine", etc....
Now, I want to create a service "CarService" that only should offer the actions "StartEngine" and "SellCar", while I might have other "Services" with other combination of "actions". I want to define this logic inside the constructor of each service. Then, in the consumer class, I just want to do something like:
var myCarService = new CarService(...paramsX...);
var res1 = myCarService.StartEngine(...paramsY...);
var res2 = myCarService.SellCar(...paramsZ...);
And I want to offer intellisense when I use the "CarService"....
In conclusion: The objective is how to "register" in each Service which methods are provided by him, by giving a list of "DoSomethingX", and automatically offer them as a "method"... I hope I was able to explain my objective/wish.
In other words: I just want to be able to say that my class Service1 is "offering" the actions DoSomething1, DoSomething2 and DoSomething3, but with the minimum lines as possible. Somehow the concept of the use of class attributes, where I could do something similar to this:
// THEORETICAL CODE
[RegisterAction(typeOf(DoSomething1))]
[RegisterAction(typeOf(DoSomething2))]
[RegisterAction(typeOf(DoSomething3))]
public class Service1{
// NO NEED OF EXTRA LINES....
}
For me, MEF/MAF are really something you might do last in a problem like this. First step is to work out your design. I would do the following:
Implement the decorator design pattern (or a similar structural pattern of your choice). I pick decorator as that looks like what you are going for by suplimenting certain classes with shared functionality that isn't defined in those clases (ie composition seems prefered in your example as opposed to inheritance). See here http://www.dofactory.com/net/decorator-design-pattern
Validate step 1 POC to work out if it would do what you want if it was added as a separate dll (ie by making a different CSProj baked in at build time).
Evaluate whether MEF or MAF is for right for you (depending on how heavy weight you want to go). Compare those against other techniques like microservices (which would philosophically change your current approach).
Implement your choice of hot swapping (MEF is probably the most logical based on the info you have provided).
You could use Reflection.
In class Service1 define a list of BaseAction types that you want to provide:
List<Type> providedActions = new List<Type>();
providedActions.Add(typeof(DoSomething1));
providedActions.Add(typeof(DoSomething2));
Then you can write a single DoSomething method which selects the correct BaseAction at run-time:
public async Task<Obj1<XXXX>> DoSomething(string actionName, ....params....)
{
Type t = providedActions.Find(x => x.Name == actionName);
if (t != null)
{
var action = (BaseAction)Activator.CreateInstance(t);
return await action.Go(....params....);
}
else
return null;
}
The drawback is that the Client doesn't know the actions provided by the service unless you don't implement an ad-hoc method like:
public List<string> ProvidedActions()
{
List<string> lst = new List<string>();
foreach(Type t in providedActions)
lst.Add(t.Name);
return lst;
}
Maybe RealProxy can help you? If you create ICarService interface which inherits IAction1 and IAction2, you can then create a proxy object which will:
Find all the interfaces ICarService inherits.
Finds realizations of these interfaces (using actions factory or reflection).
Creates action list for the service.
In Invoke method will delegate the call to one of the actions.
This way you will have intellisence as you want, and actions will be building blocks for the services. Some kind of multi-inheritance hack :)
At this point I am really tempted to do the following:
Make my own Class Attribute RegisterAction (just like I wrote on my "Theoretical" example)
Extend the Visual Studio Build Process
Then on my public class LazyProgrammerSolutionTask: Microsoft.Build.Utilities.Task try to find the service classes and identify the RegisterAction attributes.
Then per each one, I will inject using reflection my own method (the one that I am always copying paste)... and of course get the "signature" from the corresponding target "action" class.
In the end, compile everything again.
Then my "next project" that will consume this project (library) will have the intellisence that I am looking for....
One thing, that I am really not sure, it how the "debug" would work on this....
Since this is also still a theoretically (BUT POSSIBLE) solution, I do not have yet a source code to share.
Meanwhile, I will leave this question open for other possible approaches.
I must disclose, I've never attempted anything of sorts so this is a thought experiment. A couple of wild ideas I'd explore here.
extension methods
You could declare and implement all your actions as extension methods against base class. This I believe will cover your intellisense requirements. Then you have each implementation check if it's registered against calling type before proceeding (use attributes, interface hierarchy or other means you prefer). This will get a bit noisy in intellisense as every method will be displayed on base class. And this is where you can potentially opt to filter it down by custom intellisense plugin to filter the list.
custom intellisense plugin
You could write a plugin that would scan current code base (see Roslyn), analyze your current service method registrations (by means of attributes, interfaces or whatever you prefer) and build a list of autocomplete methods that apply in this particular case.
This way you don't have to install any special plugins into your Dev environment and still have everything functional. Custom VS plugin will be there purely for convenience.
If you have a set of actions in your project that you want to invoke, maybe you could look at it from CQS (Command Query Separation) perspective, where you can define a command and a handler from that command that actually performs the action. Then you can use a dispatcher to dispatch a command to a handler in a dynamic way. The code may look similar to:
public class StartEngine
{
public StartEngine(...params...)
{
}
}
public class StartEngineHandler : ICommandHandler<StartEngine>
{
public StartEngineHandler(...params...)
{
}
public async Task Handle(StartEngine command)
{
// Start engine logic
}
}
public class CommandDispatcher : ICommandDispatcher
{
private readonly Container container;
public CommandDispatcher(Container container) => this.container = container;
public async Task Dispatch<T>(T command) =>
await container.GetInstance<ICommandHandler<T>>().Handle(command);
}
// Client code
await dispatcher.Dispatch(new StartEngine(params, to, start, engine));
This two articles will give you more context on the approach: Meanwhile... on the command side of my architecture, Meanwhile... on the query side of my architecture.
There is also a MediatR library that solves similar task that you may want to check.
If the approaches from above does not fit the need and you want to "dynamically" inject actions into your services, Fody can be a good way to implement it. It instruments the assembly during the build after the IL is generated. So you could implement your own weaver to generate methods in the class decorated with your RegisterAction attribute.
In an intranet web application at my company, numerous operations have a granular, custom security system which is used in each action/http method in our MVC controllers. Basically there are two enums; one is a set of actions that can be performed (this is extremely granular; practically every possible action has a corresponding value in the enum) and one is a set of our subcompanies. For the context of this question, I will call these enums Action and Company.
Each user in our system is associated to one Company and zero or more Actions. Inside each method in our controllers, somewhere along the way there is a check for if the current user has the right Action and Company value to be using that feature. Every controller has a "UserHelper" injected into it which contains the Company and list of Actions the authenticated user is associated with.
Approaching it this way, there is a lot of code duplication in that every method is doing its own check on these enum values and reacting to violations when necessary. I am hoping to reduce this all to a System.Attribute or System.Web.Mvc.AuthorizeAttribute which we can put on controllers or methods to automatically handle violations in a uniform way and not have to check for it within the methods. Something akin to:
public class MyController : Controller
{
[RequireActionAndCompanyAttribute(Action = Action.MyMethod, Company = Company.AbcInc)]
MyMethod()
{
// do stuff, but don't bother checking for the security values
}
}
As mentioned, I am assuming I can inherit from System.Attribute or System.Web.Mvc.AuthorizeAttribute for this purpose. However, I'm struggling. I'm not sure how to adapt AuthorizeAttribute to use our own internal security implementation (based on Action and Company) rather than one of the ASP.NET Membership systems. And the plain old System.Attribute seems so vague that I'm thinking it wasn't designed for this kind of use at all. I'm also not sure how I'm supposed to pass anything to the methods in the attribute. When I put the attribute on a method, I just want to specify what Action and Company are required to continue, like in the code snippet above. But then, how do I pass the user's actual values for these into the attribute's validation method?
Use a custom attribute inherited from ActionFilterAttribute instead of the AuthorizeAttribute. You can inject your UserHelper in this class and override the OnActionExecuting method and set the Result property of the context when your condition isn't met.
Let's suppose I have a layer of abstract controllers, which delegates the request to its child controller class, until it reaches the implementation.
Think of it like a pipeline of controllers, that the request must go through, and includes caching the responses, authorizing and authenticating the user, validating the input and output data, handling repository access, etc.
My leaf class (the last child of the hierarchy), may have the following signature:
public class SeasonsController : DefaultPersistenceRestController
<int, Season, SeasonPutDTO, SeasonPostDTO, SeasonQueryData> {
/** Controller implementation here **/
}
The base classes have a lot of reusable code located in one module, this is good and has helped me a lot when changing the logic of my controllers at a global level.
Now, suppose SeasonsController need to call EpisodesController, for irrelevant reasons.
The call would be like this:
EpisodesController episodeController = new EpisodesController();
//Do something with EpisodesController
The problem is that I don't want EpisodesController to be accessed from the outside, such as client's request. ASP.NET automatically identifies controllers and creates a public endpoint for them, such as http://localhost:80/episodes.
I created EpisodesController because it uses a lot of logic from the controller's base classes, but I intend to use it internally.
I can desactivate authentication, authorization, cache and all other stuff that will be useless if a controller is used in this way, so that's not a problem.
However, I cannot manage to prevent ASP.NET to ignore my EpisodesController class, and to not consider it like a controller.
Is there an attribute or annotation maybe that will tell the compiler to do this? Maybe some modification in Web.config?.
Also note that I don't want to change EpisodesController's class name to another name, as it is really a controller, but an internal one.
You could try to use the IgnoreRoute extension method. Or you could try the internal as suggested by beautifulcoder. If it's in another assembly (and you can modify it) you could also make it visible to other assemblies with InternalsVisibleToAttribute.
Although to be honest, using one controller within another controller doesn't seem right to me. I would try and refactor you common functionality to services/helpers, then you could probably also make your EpisodesController into a simple service. Composition over inheritance and all that :)
If you make a controller public it will be accessible. From what I understand, you can change it to protected or internal.
I wanna test the controller action, but one point is not coveraged by visual studio Code coverage tool.
public ActionResult Activate(int? id)
{
if (id == null)
return View("PageNotFound");
var city = repository.GetCityById(id.Value);
if (city == null)
return View("PageNotFound");
city.IsActive = !city.IsActive;
if (TryUpdateModel(city))
{
repository.Save();
return RedirectToAction("MyCities");
}
***return View("PageNotFound");***
}
in the code coverage, *return View("PageNotFound");* is not coveraged.
Because, I can not simulate the TryUpdateModel false stuation. TryUpdateModel can get false if model can not updated. Can u help about this?
TryUpdateModel will return false if the model validation fails.
(in which case you should not be showing a not found page)
In situations like these there are all kinds of options for you. One of them is creating a stub that overrides the actual functionality of the method you want to control.
For example, you can declare TryUpdateModel as virtual. In your unit test, instead of working with the original class, you inherit it and override the TryGetModel to simply return false. All other functionality is retained as is.
Now you call the Activate method on the derived class that has the exact same functionality apart from the simulated TryUpdateModel method, allowing you to test the desired use case without breaking your head as how to simulate a certain execution path.
This technique is not without drawbacks: it makes you declare the method as virtual only for testing purposes, thus preventing you from making it sealed, or static. There are other, more advanced techniques (Mock objects, isolation frameworks) but I think that this is a good enough solution for this scenario.
You don't include code to show how the lifetime of the cargo dependency is handled, so I'm only guessing, but...
It should be possible to pass a mock or fake instance of this class to the controller as part of your test setup (if it isn't currently possible, refactor until it is).
With the mock in place you can isolate and test the behaviour as you want.
Aside: I disagree with the comment from #dreza... testing this sort of business logic is very important.
I would also caution against faking the implementation of TryUpdateModel as suggested by #Vitaliy, after all you want to test what happens if the cargo model is invalid (not just pretend that it is by providing a new version of core code).
OK,
I solved solution. I deleted the TryUpdatemodel if condition. Directly used repository.Save() method. Because I did not send parameter a model to activate method.
I have a very large (77 actions) controller that I am using to make a site with wizard-like functionality. The site is like a "job application manager" with multiple components such as an admin component and an end-user component. The component I'm working with is the part where the user would actually fill out a job application. The way things are structured with the other components, it makes the most sense to put all of the job application stuff in the same controller. All of these actions perform similar things but on different models, like so:
public class ExampleController : Controller
{
public ActionResult Action1()
{
Guid appId = new Guid(Session["AppId"].ToString());
... // logic to pull up correct model
return View(model)
}
[HttpPost]
public ActionResult Action1(FormCollection formValues)
{
Guid appId = new Guid(Session["AppId"].ToString());
... // logic to update the model
return RedirectToAction("Action2");
}
public ActionResult Action2()
{
Guid appId = new Guid(Session["AppId"].ToString());
... // logic to pull up the correct model
return View(model)
}
... // on and on and on for 74 more actions
}
Is there any way to reduce some of the constant redundancy that's in every one of the actions? Here is what I am thinking:
Creating a member variable Guid to store the appId and then overriding OnActionExecuting to populate this variable. Is this a good idea?
Implementing some kind of paging to cut down on the number of actions. Any suggestions on how to do that?
I would say yes to your first point and "it depends" to your second. Don't change your design just because you have a lot of methods, if all 77 ActionResult methods make sense to have, then keep them around.
Using a member variable and overriding OnActionExecuting seems like a great way to refactor that appID Guid code into a single place, so you can quickly and easily modify it in the future.
Normally for wizard view, a single action and page is used with multiple divs which can be shown according to the steps.
For example, a registration wizard screen having 4 steps, can be be handled in a single page with divs for each steps. You can make use of JavaScript and css to make it a wizard flow.
Make use of ajax to update different models, if necessary in between the steps.
You may want to put your logic (Job Manager related) in a single repository/manager class. Different controllers associated with different views(e.g AdminController, EndUserController etc) can call methods from same repository/manager class.
Another option could be replacing this..
Guid appId = new Guid(Session["AppId"].ToString());
..with a call to something like the following:
private Guid GetAppId(){
return new Guid(Session["AppId"].ToString());
}
Now you could just use GetAppId() instead wherever you currently use appId. You could of course cache the GUID in the form of a class variable, as you suggest, but it might be a good idea to limit the access and use of that variable to a method like this (get it's value via the method). Might be a little more flexible in case you want to change something later.
As for dividing the page into several pages; sure, go ahead, if it makes sense and feels right. Over 70 actions in one class does sound like a lot. If it makes more sense to keep them there however, you could try to move as much logic as possible out from the methods themselves, and into helper-classes instead. I always try to keep the actions as small as possible, and put the logic in separate classes, each of which is tailored to do one specific thing.
My point is, if each action is no more than 2-4 lines, then 70+ actions is not necessarily a problem.