Calling Web API action from within an actionfilter to take advantage of outputcache for repeated authorization - asp.net-mvc-4

I wanted to take advantage of the OutputCache attribute for a authorization check to be made on an Action in a Controller. Based on a related thread and what I could tell the following design made sense, I was looking for feedback or corrections.
In other words:
1. a client calls an action on a controller which has my custom authorization filter attribute
2. The filter makes an HTTPClient call to another action on a web API controller (in the same site)
3. This action has an outputcache attribute to ensure I don't repeat an access check for the same parameters
Questions I had:
1. Is my use of OutputCache appropriate? I'm assuming a 5 minute cache lifetime.
2. In step#2 is a HttpClient call from my authorization filter the only way to make sure the pipeline for caching is built and used?
There are several related threads but I couldn't quite find one that tried to use this pattern for authorization.

FYI I did build out the solution I'd designed.
Answers for the questions I had:
Q1: OutputCache attribute on the authorization check call seems to work fine, I had to vary it using the cookie parameter, I'm a little concerned about this given cookies come from the client, but I still have the forms authorization filter higher and that should reject completely un-authenticated requests from coming in, would be happy to change to a better solution.
Q2: If i didn't make an HTTP call from my filter, the cache pipeline was not being built, so this is necessary as far as i can tell.

Related

RESTful / Crud based approach to controlling an entity behavior that is typically implicit

I am modifying a CakePHP application to have an API available on it. My intention is to try to keep keep the endpoints as close to being RESTful / Crud oriented as possible. Although I have a use case that that I am unsure of.
I have the following requests for adding and editing tasks:
PUT /tasks
PATCH /tasks/:id
One of the behaviors of task entity in the system I am working on is that they send emails to the effected users associated with the task, when a save or edit is performed. This allows the various parties surrounding the task to be updated on the status of the particular task.
However the the one issue is that in some uncommon cases the end user will need to be able to toggle if they want an email to be sent on the front end.
What is the proper RESTful / Crud oriented approach to flag the task endpoints to not fire the email in the API request?
There is no record of the email in the application's database and it is nice to have to functionality tied into the task life cycle hooks and called implicitly. So I am not crazy about doing something like creating an /emailTask set of endpoints. It seems like an optional flag in the task request would be cleaner, but might not be maintainable if we begin to have similar needs for other behaviors associated with tasks.
Thanks in advance for the help!
PUT /tasks
If you're intending to use this for adding tasks, use POST instead. PUT /tasks implies that you are overwriting all tasks.
As for side-effects, this to me feels like a decent use-case for a custom HTTP header. Perhaps something like Suppress-Notifications: ?1 ?
Why ?1 as a value? This is going to be the future default for new HTTP headers that specify a boolean:
https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-header-structure-15#section-4.1.9

AuthenticationScheme & IAuthenticationHandler

Hope everyone keeping safe,
I am trying to understand some of the abstractions in asp.net core authentication / authorization (and browsing the source code for additional insight).
There is an abstraction called "AuthenticationScheme" which seems to only bring in a ‘name’ property to the actual IAuthenticationHandler (which seems to be is the type that does the work).
I am trying to understand why asp.net has this the scheme abstraction, if the intent is just to give the handler a name, why not just include a name property in the handler's interface definition ?
To allow usage of the handler multiple times at least.
If you make an API that allows JWT Bearer tokens from two identity providers, then you might want to specify the JWT Bearer authentication handler twice.
And since each handler needs a unique name so we can invoke the right one, the developer must define those names.

¿Is there a way to call a class method on every controller action?

I'm implementing a cache system to handle my JWT on server side to emulate a Session State , everytime an action is called i must validate the token on the server cache to see if it's still valid, is there a way to create a something like
[Authorize] or [AllowAnonymous]
To search over the request and do whatever is needed to valide it? i already have a singleton class that handles the cache system, all i need is an easy way to call the right methods.
I want to avoid calling via Dependency Injection the method on every action on every method.
I'm using Net Core 3.0, Distributed Cache, and a Web API with JWT validation.
Thank you.
You need to implement an Action Filter. See the documentation for more details

Can Webapi be used in an application which is not excessed by any external application?

I'd read it somewhere that whenever one needs to do data intensive work then Webapi could be used. Ex: autocomplete textbox where we get data from using ajax on key press.
Now someone told me that Webapi shouldn't be used within applications which are not externally accessed. Rather action should be used to the same work as it is capable of returning the data back in a similar fashion to webapi.
I'd like to know your suggestions over it.
Depends on how you look at it. If all you need is ajax-ification of your controller actions, then you really don't need Web-API. Your actions can return a JsonResult and it is very easy to consume that from your client side through an AJAX call.
Web-API makes it easy for you to expose you actions to external clients. It supports HTTP protocol and Json and XML payloads automatically, out of the box, without you writing the code for it. Now, there is nothing preventing you from consuming the same Web-API actions from your own internal clients in an AJAX manner.
So the answer to your question depends on your design. If you don't have external clients, then there is no string need for you to have Web-API. Your standard controller actions can do the job.

MVVM on top of claims aware web services

I'm looking for some input for a challenge that I'm currently facing.
I have built a custom WIF STS which I use to identify users who want to call some WCF services that my system offers. The WCF services use a custom authorization manager that determines whether or not the caller has the required claims to invoke a given service.
Now, I'm building a WPF app. on top of those WCF services. I'm using the MVVM pattern, such that the View Model invokes the protected WCF services (which implement the Model). The challenge that I'm facing is that I do not know whether or not the current user can succesfully invoke the web service methods without actually invoking them. Basically, what I want to achieve is to enable/disable certain parts of the UI based on the ability to succesfully invoke a method.
The best solution that I have come up with thus far is to create a service, which based on the same business logic as the custom authorization policy manager will be able to determine whether or not a user can invoke a given method. Now, the method would have to passed to this service as a string, or actually two strings, ServiceAddress and Method (Action), and based on that input, the service would be able to determine if the current user has the required claims to access the method. Obviously, for this to work, this service would itself have to require a issued token from the same STS, and with the same claims, in order to do its job.
Have any of you done something similar in the past, or do you have any good ideas on how to do this?
Thanks in advance,
Klaus
This depends a bit on what claims you're requiring in your services.
If your services require the same set of claims, I would recommend making a service that does nothing but checks the claims, and call that in advance. This would let you "pre-authorize" the user, in turn enabling/disabling the appropriate portions of the UI. When it comes time to call your actual services, the user can just call them at will, and you've already checked that it's safe.
If the services all require different sets of claims, and there is no easy way to verify that they will work in advance, I would just let the user call them, and handle this via normal exception handling. This is going to make life a bit trickier, though, since you'll have to let the user try (and fail) then disable.
Otherwise, you can do something like what you suggested - put in some form of catalog you can query for a specific user. In addition to just passing a address/method, it might be nicer to allow you to just pass an address, and retrieve the entire set of allowed (or disallowed, whichever is smaller) methods. This way you could reduce the round trips just for authentication.
An approach that I have taken is a class that does the inspection of a ClaimSet to guard the methods behind the service. I use attributes to decorate the methods with type, resource and right property values. Then the inspection class has a Demand method that throws an exception if the caller's ClaimSet does not contain a Claim with those property values. So before any method code executes, the claim inspection demand is called first. If the method is still executing after the demand, then the caller is good. There is also a bool function in the inspection class to answer the same question (does the caller have the appropriate claims) without throwing an exception.
I then package the inspection class so that it is deployed with clients and, as long as the client can also get the caller's ClaimSet (which I provide via a GetClaimSet method on the service) then it has everything it needs to make the same evaluations that the domain model is doing. I then use the bool method of the claim inspection class in the CanExecute method of ICommand properties in my view models to enable/disable controls and basically keep the user from getting authorization exceptions by not letting them do things that they don't have the claims for.
As far as how the client knows what claims are required for what methods, I guess I leave that up to the client developer to just know. In general on my projects this isn't a big problem because the methods have been very classic crud. So if the method is to add an Apple, then the claim required is intuitively going to be Type = Apple, Right = Add.
Not sure if this helps your situation but it has worked pretty well on some projects I have done.