Appropriate request method to send tokens - c#

What is the correct method to consume a resource passing a token after i am correctly authenticated? For example, is it right to do a GET with a Bearer Authorization to get an array of JSON objects or should i make a POST request?

According to Wikipedia
GET requests a representation of the specified resource. Note that GET
should not be used for operations that cause side-effects, such as
using it for taking actions in web applications. One reason for this
is that GET may be used arbitrarily by robots or crawlers, which
should not need to consider the side effects that a request should
cause.
and
POST submits data to be processed (e.g., from an HTML form) to the
identified resource. The data is included in the body of the request.
This may result in the creation of a new resource or the updates of
existing resources or both.
So, it does not depend on passing a token. It depends whether your request just retrieves the resource or it creates/updates an existing resource.
For just retrieving a resource use GET.
For creating a new resource/updating a new resource use POST.

Related

Get original origin of request with .NET Core API

I know that Request.Headers["Origin"] gets the origin header of a request, but this is changeable on the client-side by setting the header manually. Thus not that safe.
Is there such a value that contains the original, readonly/unchangeable origin of a request? Like the one CORS is using?
I need this value to check if the request is officially coming from the site it's supposed to come from. The trick is that I need it in the controller method to search an object in the database based on this value and a key only used for that site.
The problem with CORS is that it can whitelist a list of URLs but not check if the site and the key belong to each other, thus can whitelisted site 1 access the data of whitelisted site 2 if it mimics the Request.Headers["Origin"] and the key of site 2
Unfortunately (or perhaps fortunately?) there is no reliable way to check this from the data that the browser sends to your server. The user is able to forge any and all information that you receive from the browser.
This is why mechanisms that need to reliably determine the origin of a user use some sort of token mechanism, public/private signatures, certificates and the sort to determine it. Unfortunately this is never as simple as looking up some information that the browser provides you with, so it seems like you might need to redesign your whitelisting mechanism by relying on something else than origin, possibly implicating single-sign-on measures (like SAML). It's hard to provide further suggestions without more information on the underlying problem that the origin-check is intended to solve.

Commonly used Web API parameters - route vs header?

I'm looking for best way of passing a common parameter between pretty much all of my web API methods. The parameter in this case is a repository identifier as there is a choice on login into the SPA over which database is to be used to read and write data from/to. This choice is then stored in the app and used in all future API calls.
The choices I'm considering are:
Route value - this means adding a route parameter to all of the routes and ensuring it's sent for each call the SPA makes: [Route("api/{repo}/{user}/{id}")]. The advantage here is it's maybe more explicit.
Custom header value which is applied blindly by the app on every API request and used by the API whenever required. It is therefore a requirement that this header is passed. The advantage here is there's a separation of concern - the part of the SPA managing the users screen doesn't need to know which repo it's working with.
Are there any best practise guidelines for parameters that are commonly used in an API? Where's the distinction over when parameters should be passed FromUri and FromBody over using custom header values?
It depends on the situation but if you have made APIs in which every time you need to pass certain parameter then better you send this parameter in header. HTTP header meant to send extra information about request context, but be aware of adding too much header key-value.
Through header and querystring (through URL) you can only send data in key-value pair whereas through HTTP body you can send different types of payload (data) i.e. JSON, XML, txt, FileStream etc.
There are certain limitations on the data size based on which methods choose to send data. Through header you can pass data up to 8KB size for each key-value pair, in querystring you can add up to 2048 chars and through body we can send as much as 0 to >= 2 MB of data (Size may vary from server to server).
For more detail please refer RFC 7231
Its depends of use cases
If you need to share links between users you will definitely need to use path
It is also looks more transparent and understandable
I believe you need to use headers if you want to hide information for the end user
If you are trying to achieve some kind of multi tenancy here I can also propose use different sub domains for each repository and then add midleware/filter/etc to resolve repository based on request subdomain. You can automate subdomain creation (most of popular providers have API to do this)

Advantages of REST URI over URI of querystring format?

All,
For a new project that we have started with .NET we wanted to exercise pure REST. Hence we chose .NET Web API which has been released as part of .NET Framework 4.5 (instead of WCF) with the consideration that it enables pure REST nature. But as we explored more based on our requirements, we realized that it doesn't have URI templating support that provides REST like URL formats. we were still OK as we didn't feel much bad about WebAPI having query string kind of formats.
When we engaged a new team, they started to enforce that they need REST kind of URL formats only as it is the standard norm and likes.
When asked about the enforcement they just mentioned that it is a standard and we have to adhere to it which didn't convince me.
So, I am interested to know what does REST architecture provides out of the box? Also having querystring format URI doesn't qualify to be a REST approach?
REST URI: http://myapplicationdomain.com/apps/appId
Querystring URI: http://myapplicationdomain.com/GetAps/appId={appId}
Thanks in advance.
REST is not only the URL format, and REST does not restricts you from using parameters.
One part of REST philosophy is to identify resources, so your resource has URL, and HTTP verbs (Get, Post, Delete, Put, etc.) define operations on this resource.
You can still use parameters, for example
http://myappfomain.com/product/?page=1&pageSize=10
It is a GET request to the list of products (since ID is not specified) and paging/sorting criteria is specified in a query string. It is perfectly correct.
Or
http://myappdomain.com/product/123/?format=json
Here you access product with the ID od #123, but request it to be returned as JSON. It is also fine.
From this perspective it is just more logical that a resource has its own URL. Parameters may add some specifics.
Look at it this way:
URI defines the subject
HTTP Verb defines the operation (what to do)
Query parameters provide some specifics (how to do it)
Hope it helps.
The REST (see wiki Representational state transfer) "style" of the URI is there for a reason. An extract from wiki:
Uniform Interface
...
Identification of resources Individual resources are identified in requests, for example using URIs in web-based REST systems....
Manipulation of resources through these representations When a client holds a representation of a resource, ... it has enough information to modify or delete the resource on the server ...
I used these cites as nice explanation of the fact, that REST style of URI is in fact about resource identification. We can have
1) a table in DB and
2) an ID column which allows to
3) UPDATE or DELETE the record.
The URI in REST does do the same:
1) Identify the resource type (entity/table)
2) Identify the resource ID
3) set the operation
HTTP Method URI Operation
GET \ResourceType\ResourceId SELECT, READ
POST \ResourceType INSERT, Add, create new
PUT \ResourceType\ResourceId UPDATE the record with ResourceID
DELETE \ResourceType\ResourceId DELETE that record
So as we can see, the REST URI style does make sense in the complete context of the resource management

How to cache a json proxy

I am looking for the best way to cache a json proxy on .NET with C#.
The web service we are using restricts the number of hits per IP and is periodically unavailable. Luckily the data isn't very volitile, but it does change.
Ideally I'd like to do is cache the web response only when the request is valid. We would determine a vaid response by two factors, the http response code and the json code doesn't give us a "too many requests" error.
I'd like to store the proxy request in cache using the proxied URL and query string so we could use the same proxy for multiple external resources and multiple queries.
I'd also like to store the request either on disk as a file or in the data base in case the URL is unavailable and the Cache is empty.
Here is the proposed process:
Check the Cache for results by using query string
If the cached versions exists use it. If not make a new request.
If the reqeust succeeds, store a new set of results to the cache and write the results to disk or database or disk.
If that request fails use the file or database cached version.
I have read the MSDN articles and a few other blog posts, but it would be great to get a specific example on how to do this efficiently.
Thanks!

What's the differences between HttpContext.Current.Items[] and HttpContext.Current.Request[]?

I really can't find out what is really the differences between these two methods in C#/.NET.
In fact they should do the same actions!
The first contains a safe read/write storage location that could be used throughtout the entire HTTP request. You could use it for example to store some object in the Begin_Request method and it will be available up until the page renders. It's like a Session but that lives only for the lifetime of a single HTTP request. You can access it from everywhere during during this request and it is specific to the context of the current request only.
The second is readonly storage for query string, POSTed form parameters, server variables and cookies.
Items is a NameValueCollection useful for storing and sharing data for the life of the HTTP Request. The Request meanwhile provides access and methods specific to the HTTP Request. Neither are methods however.

Categories

Resources