I followed this tutorial http://www.tugberkugurlu.com/archive/api-key-authorization-through-query-string-in-asp-net-web-api-authorizationfilterattribute
to create custom Authorization filter.
I have CarController with my custom Authorize Attribute:
[ApiKeyAuth("apiKey", typeof(ApiKeyAuthorizer))]
I send two parameters in the url .. host/Car/4?username=xxx&pass=xxx
It works basically fine, however I want to allow only car owners to see information about their cars.
E.g. user ABC can see only host/Car/5 and user DEF can see host/Car/6 and host/Car/10
how can I solve this scenario?
How can I access the id of the car used in query (host/Car/ID) in my ApiKeyAuthorizer.
Greetings
If you look at his code, https://github.com/tugberkugurlu/ASPNETWebAPISamples/tree/master/TugberkUg.Web.Http/src/samples and https://github.com/tugberkugurlu/ASPNETWebAPISamples/tree/master/TugberkUg.Web.Http/src/TugberkUg.Web.Http, I think you'll find that he's pulling the data directly from the query string. It should simply be a matter of extending that method to pull in the id parameter. You might also want to look at the RequestContentKeyValueModel on the HttpActionContext parameter passed into the OnAuthorization method. The documentation is sketchy and I haven't played with it yet, but that seems like a likely candidate to me. However, the route data is available indirectly through the HttpRequestMessage via an extension method, specifically:
message.GetRouteData();
Related
Given I am posting to an endpoint as so:
POST http://foo.com/user/:user_id/articles
{
"content": "some text"
}
when I configure the Validator within the config I am struggling to find how to inject the :user_id from the route along with the "content" from the body. So my Validator is stuck trying to validate if "content" is ok without the :user_id.
What is the proper Apigility way to inject IDs (or even ideally objects) from route parameters into the Validator(s) along with the normal body $data payload?
Many thanks
As far as i know, apigility has no way to validate the route parameters.
Personally i validate them in de resource or the controller.
That way i can do some more complex validation, like does this id exist?
If you want an object as a route parameter, you van try serializing the object and putting that in your parameter.
But i would advice against this. Would you even trust an external party to provide you with whole objects?
If you need some user info you could look into JWT or similar techniques.
JWT is a authorisation token that also contains any data (it's json based).
Now, any body params can be validated.
In the apigility ui, you can go to fields, and add the fields you want to validate there (or it should be all of them for simplicity).
Then you can assign filters and validators here. Even custom ones you have configured in your zf2 application.
Let's say I've got a FooEnity with an id of 35 exposed by a web service, and it is located at at /myhost/api/fooentity/35.
Now I want to implement a PATCH call to allow partial updates to FooEntity (so let's say 2 of the 25 available fields are passed up to be updated).
My question is, should the PATCH content (json/xml) include the id of 35? The address of the entity is specified by the URI, and id is not an updateable field, and if it was included it is an extra validation to make sure both ids match. All of this suggests No. Still, it feels weird not having it in there.
What is the appropriate way to do this?
(Note, question is language independent, but is implemented in the ASP.NET 4.0 Web API framework, if that influences anyone's answer).
That's a great question!
There are two ways you can handle that. You can either raise a validation error if the id in the body is different from the id in the URI. Or you can just ignore whatever id is in the request body. If you're patching by manually copying properties, you would just not copy the id property to ignore it. If you're using a helper class to patch the entity, you could apply the patch and then set the entity's id to be whatever came in on the URI just to make sure that it keeps the same id after the patch.
Whichever option you pick is really up to you. Sending back a 400 if the request body id doesn't match the entity id might be a little clearer for clients so they understand that the id won't be changed, but it also requires you to write more code to implement.
I am porting a legacy application to Symfony2 and I am struggling because routing doesn't include query string parameters. Some quick examples: Suppose you have a search page for books where you can filter results based on criteria:
http://www.bookstore.com/books?author=Stephen+King&maxPrice=20
The nice thing about query string parameters in a case like this is you can have any number of filters, use the ones you want for any given request, and not crowd the URL with filters you're not using.
Let's say we rewrote the routing for the above query using the Symfony2 routing component. It might look like this:
http://www.mybookstore.com/book/any_title/stephen%20king/any_release_date/max_price_20/any_min_price/any_format/any_category
Even not taking into account how arbitrarily long an unclean that URL is I still don't think it is as intuitive because each 'segment' of that route is not a key value pair but instead just a value (e.g. author=Stephen+King > /stephen%20king/).
You can of course access query string parameters in the controller by passing the Request object into the action method (e.g. indexAction(Request $request) {) but then validating them and passing them into other parts of the application becomes a hassle (i.e. where I find myself now). What if you are using the Knp Menu Bundle to build your sidebar and you want parts to be marked as .current based on query string parameters? There is no functionality for that, just functionality to integrate with Symfony2 routes.
And how to validate that your query string parameters are acceptable? I am currently looking at validating them like a form to then pass them into the database to generate a query. Maybe this is the way the Symfony2 team envisioned handling them? If so I'd just really like to know why. It feels like I'm fighting the application.
I ended up actually asking Fabien this question at Symfony Live San Francisco 2012. There was another talk at the same conference in regards to this question and I will share with you the slides here:
http://www.slideshare.net/Wombert/phpjp-urls-rest#btnNext
Basically in the slides you can see that the author agrees with me in that query string parameters should be used for filtering. What they should not be used for is determining a content source. So a route should point to a product (or whatever) and query string parameters should then be used in your controller to apply whatever logic you require to filter that content source (as per Fabien).
I ended up creating an entity in my application that I bind all my query string parameters to and then manipulate, much the same way forms are handled. In fact when you think about it it's basically the same thing.
Like in Symfony1, query strings are independent from the route parameters.
If you have a path defined as #Route("/page/{id}", name="single_page"), you can create a path in your view like this:
{{ path('single_page', { id: 3, foo: "bar" }) }}
The resulting URL will be /page/3?foo=bar.
If this is a duplicate, please let me know - because i had a quick look and couldn't find anything that really answers my question.
I'm experimenting with ASP.NET MVC 2. Now coming from a Web Forms background, i only really dealt with HTTP GET and HTTP POST.
I'm trying to see how i could apply GET/PUT/POST/DELETE to the respective CRUD operations on my repository (Find, Insert, Update, Remove).
Say i have a single controller, with the following action methods:
[HttpGet] // GET: /Products/{id}
[ActionName("Products")
public ActionResult Get(int id = 0) { ... }
[HttpPut] // PUT: /Products
[ActionName("Products")
public ActionResult Put(Product product) { ... }
[HttpPost] // POST: /Products/{product}
[ActionName("Products")
public ActionResult Post(Product product) { ... }
[HttpDelete] // DELETE: /Products/{product}
[ActionName("Products")
public ActionResult Delete(Product product) { .. }
Couple of questions on that - is that how you would name/separate the action methods? Should i be passing through the entire model (Product), or just the id?
The problem i'm having is i'm not sure how to handle invoking these action methods with the relevant HTTP Verb in my View.
At this stage, I'm thinking i would have 3 Views:
"Index" - bind to IEnumerable<Product> model, listing all products, with "Edit", "Details" and "Delete" links
"Single" - bind to single Product model, listing all details for a product, with an "Update" button.
"New" - bind to single Product model, with form for creating product, with an "Create" button.
So - my question is, how do i specify i want to invoke a particular controller method with a specific HTTP Verb?
With Html.BeginForm, you can specify a FormMethod enumeration - but it only has GET and POST.
How can i perform a PUT and DELETE command?
Will i need a seperate View for each HTTP Verb?
If i have a link called "Delete", can i invoke a HTTP DELETE command to my controller, or does it need to be redirected to a new View with the form action delete?
Or, is this a silly/overkill design in the first place, should i just stick with "GET" and "POST"?
I'm (fairly) new to this style of web development (REST), so please be kind. :)
UPDATE
So i came across this interesting article from Stephen Walther, regarding this very topic.
He indicates a HTML Form only supports GET and POST (because i'm new to REST-style web development, i did not even know this, to which i am partially ashamed).
Apparently the only way to invoke a Controller action with PUT/DELETE is to do it with AJAX. Seriously?
So what should i do here, should i stick with GET/POST, or should i create a JavaScript file which wraps the underlying XmlHttpRequest code behind a nice function?
Which way are ASP.NET MVC developers leaning? Surely someone has asked themselves this same question.
The reason that you're mostly familiar with GET and POST is because a regular old browser can only GET or POST a URL, especially when submitting a form.
Setting up your controllers this way, you're looking at something more along the lines of a REST API vs. a web site at least in spirit.
And yes, you are correct that only AJAX requests can set their request methods explicitly, so you're good to go if you'll be performing actions like deleting products via AJAX (in which case I would suggest only passing the ID since it is much lighter than serializing the entire product and you'll likely have easy access to the ID in your markup).
Here's the thing. If you are building a modern web application you're probably using AJAX and without getting too dogmatic you should expect your users to have JavaScript. If you want to do CRUD without AJAX then you can always POST a Product or use GET for a delete method with the ID in the URL (caveat to that, make sure the Delete method is protected behind authorization or a web crawler will gladly consume your GETs and delete all your data...)
If you don't want to build a REST API then don't sweat the fact that you're not using DELETE (just use GET with the ID in the URL) or you're not using PUT (just use POST with the product entity in the POST body).
REST is a great style for building APIs (no presentation tier, data sent in raw format to clients who consume them, could be a phone or a website, etc.) over HTTP. HTTP is great on its own for building web pages. Use what you need for what you need it for.
If you want to build a REST API to be used by both other people AND your web site, then do that, and just have your site's controller action methods call your API methods directly. I do that all the time. Use a web client like Hammock to make it easier on you.
Personally I stick to as simple as possible full requests, instead of going AJAX all over. I use ajax, but in specific places where it enhances the experience (and I do with a progressive javascript approach).
Because of the above, I always just use GET and POST.
As for the naming, for those I'd do: Get, Update, Create, Delete, which makes it pretty clear. I actually use more like an action name that's related to what the operation does, but for simple things those work fine.
HtmlHelper.HttpMethodOverride Method (System.Web.Mvc)
How about this?
Is there a standard way to create unique web page address in ASP.NET? I'm sending surveys to customers and will be including a link to the web page. For example:
http://www.mysurveypages.foo/survey/UniqueID
I would then customize the survey based on who I sent it to. I know it can be done by passing in a unique parameter to a page but I curious about doing it this way.
You can use Routing to map your url structure onto a particular page and parameter collection. Essentially, it allows you to convert parts of the url into url parameters for your page. This works in standard WebForms and is the basis upon which MVC chooses the appropriate controller/action signature to invoke.
Yup like dcp said GUID is a reasonable solution http://mywebsite.com/survey.aspx?ID=GUID
Suppose you are going to sent the survey to a list of users.
List<User> users = GetSurveyUsers();
foreach(User u in users)
{
Guid guid = Guid.NewGuid();
//Then store the user-guid pair into DB or XML...
}
The simplest solution would seem to be making UniqueID an incrementing field that can be used to get the appropriate user information out of the database. You could use numbers, or a Guid, or some alpha-numeric value, it really doesn't matter.
If you go with ASP.Net MVC then it is quite easy to map the Url (like the one you specified) to a controller action which gets the ID passed in as a parameter. Otherwise you will probably want to look into some sort of Url rewriting to make sure the Url can be nice and pretty.
A GUID approach is safest, if you're able to store it somewhere. If not you could use some existing unique data (e.g. customer id or email address) either directly (but be careful about leaking sensitive data) or hashed (but need to consider collisions).