Since day one it was possible to support multiple authentication methods with AuthenticationHandler (see here, here and here for some background). I simply stopped searching for other credentials once I found one of the registered ones. Since one of my clients also needed a feature to support multiple simultaneous authentication methods, I finally found the time to add this feature.
AuthenticationHandler will now search for all registered credential mappings and add each resulting claims identity to a claims principal. This allows for scenarios where you want to support e.g. SSL client certificates in addition to Basic Authentication – or in delegation style scenarios where you need to transmit two sets of credentials – the direct caller as well as the original client credentials.
After all identities have been hydrated from the registered credentials, you can also optionally run a claims authentication manager to normalize the multiple identities into a unified single identity again.
The server configuration could e.g. look like this:
authentication.AddBasicAuthentication(UserCredentials.Validate);
authentication.AddClientCertificate(ClientCertificateMode.ChainValidation);
…and the corresponding client:
var handler = new WebRequestHandler();
handler.ClientCertificates.Add(
X509.CurrentUser.My.SubjectDistinguishedName.Find("CN=Client").First());
var client = new HttpClient(handler) {
BaseAddress = _baseAddress
};
client.SetBasicAuthentication("bob", "bob");
The resulting ClaimsPrincipal will then hold two identities, one containing claims for the Basic Authentication (name) and one containing claims for the client certificate (thumbprint, common name, serial number, public key, etc…)
The sample can be found here. Nuget will be updated soon.
HTH
Filed under: IdentityModel, Uncategorized, WebAPI
It’s been a little while now since I released Linq to Querystring into the wild… we’ve since solved a few issues and it’s been put to use in some real-world applications. Thanks to everyone who’s provided feedback so far!
So lets have a look now at some of the practical applications for Linq to Querystring (and for OData in general) from a beginners perspective. In this post I’ll take you through creating a sample table with paged data using Web API\Linq to Querystring from start to finish.
Getting set up
Fire up Visual Studio and start a new ASP.Net MVC 4 project:

Choose a suitable name and click OK. Then on the next screen, select the Web API template:

Leave the rest of the settings as default, and click OK again to create the project.
Once everything loads up, we just need to install LinqToQuerystring before we can get started. To do that, open the package manager console (View->Other Windows->Package Manager Console if it’s not open already), and type the following:
install-package LinqToQuerystring
If all goes well, you should see something like this:

Also make sure to add the WebAPI extension to make things even easier to use:
PM> install-package LinqToQuerystring.WebApi
Now we’re ready to get started.
Setting up the API
First we need to write some code in our API so that we can retrieve some values. Linq to Querystring can work with any type of data source or format, so long as your API method can return an IQueryable<>. Open up the ValuesController.cs file that was created for us when we started the project.
It will have the standard methods for the main HTTP verbs as usual… for this sample we’re only interested in retrieving multple records, so we can hose everything apart from the Get method.
Change this method to return an IQueryable instead of an IEnumerable; you’ll also need to use the AsQueryable() extension method on the return statement. Finally, add some more sample strings to the array and give them more imaginative values than just ‘value1′, ‘value2′ otherwise it’s very dull.
If you like you can hook this up to a source of complex objects, from Entity Framework or your favourite document database solution. I’ve just hard coded some values for simplicity as the example works just as well.
If everything has gone to plan, you should be able to fire up your solution and browse to http://localhost:<port>/api/values and get some data back:

Ugh! XML. This isn’t the 90′s. Lets remove the XML formatter from the Web API config so we don’t have to look at it anymore.
Open up the WebApiConfig.cs file in the App_Start folder, and add the first two lines to the Register method so it looks like below:
Fire it up again, and viola… some nice friendly JSON:

Now we’ve got some test data, we can look at sorting out our UI.
On the client side
So what we now want to do is render our data into a table, and provide the user with some controls for paging the data. We’ll need to tell them how many records there are in total, allow them to choose how many records they want on each page, and provide a button to click that will retrieve the data.
We’ll go ahead and modify the template Index.cshtml that came with our project to include those elements we need. I’ve made mine look something like this (photoshopped for size):

I’ve omitted it from this post for succinctness, but you can get the cshtml source here (or build it yourself if you’re not lazy!): https://gist.github.com/Roysvork/5564031
To make things easier, I’m going to use Knockout.JS to map the values and button click from our form controls onto a viewmodel, which will encapsulate all our functionality. If you’re not familiar with knockout, you can find out more here: http://knockoutjs.com/documentation/introduction.html.
To use knockout, you’ll need to reference it in Layout.cshtml… you can do this directly or use the bundle functionality in MVC 4. Anyways once you’ve done that… here’s the viewmodel and the javascript that fetches the data and wires it all up:
It’s quite straightforward, we have a getData function that makes the ajax call to our API which is also called when the page first loads. We have a bunch of observable properties, and then a pages computed observable that will provide a correct list of pages whenever the page size or record count changes. This provides the list of options for the page size drop down.
Fire up the app again and take a look at your handiwork. You should be able to see that the list of available pages changes as you select a different page size, and the data is displayed along with the correct total. Give yourself a cookie.
So what about the paging?
So now comes the hard part… well it would be if it wasn’t for Linq to Querystring. I’ve deliberately left this till last so you can see just how easy this is. First of all, we need to modify our API method to provide OData query support like so:
// GET api/values
[LinqToQueryable]
public IQueryable<string> Get()
Now on the client side, we can inform our API that we want to page the data via the OData query operators $top and $skip. As you might expect, $top specifies that we want a restricted number of results, and $skip tells our api to jump over a specified number of records beforehand.
All we need to do is modify our url to use the values from the model:
var skip = model.pageSize() * (model.currentPage() - 1);
$.get("/api/values?$top=" + model.pageSize() + "&$skip=" + skip, [...]
Very simple indeed. If you’re really paying attention though, you’ll notice there’s one last thing we need to do. Our count is now wrong as it doesn’t bring back the total number of records, only the number in the current page.
We can solve that by adding the OData $inlinecount=allpages query operator. Remember the JSON we got back earlier? After adding the inlinecount it now looks like this:

So now we can use the Count and Results properties to provide data for our model. With these tweaks in place, our final getData() implementation now looks like this.
Fire up the sample app for one last time, and we now have a working data paging implementation!


This is just a taste of what OData\Linq to Querystring has to offer. In my next post I’ll extend this sample to see how we can also use perform ordering and filtering on our data.
In the meantime, take a look at the github page for the current project progress and features. You can also find the full source for this sample here: https://github.com/Roysvork/LinqToQuerystringPagingSample
Pete
References:
[Level T1] Some of you might be doing performance analysis for living, and if so, you have access to expensive performance tools. But for those who are not and get drawn into investigating performance of their own application or their peers, there is really not a great free tool that you can just point to a URL and hammer.
Well, actually there is: Apache benchmark or ab.exe which has served the community since almost 20 years ago. It is free and very performant, i.e. does not require a lot of resources to run so does not affect the performance even if you benchmark your localhost server. But it has limitations (only GET, no HTTPS, no parameterisation) and I could not find a tool so I ended up writing one for my own use. And now I am sharing it.
SuperBenchmarker or sb.exe is a single-exe (ilmerged with dependencies inside) application that can be used to call various endpoints. It can do GET as well as other verbs, can do request templating and you can provide values for placeholders in URL or your template. It also can output a lot of tracing info in case you need it.
It requires .NET 4.5 but you can target any site or API written in Ruby, PHP, Java, ect. You can download it from here if you do not want to use NuGet. [Update: It has been reported that some people have had issue running on x64 windows. If so please comment on this GitHub issue]
So version 0.1 is out and it works although project needs some love with tests and a few features. There are also some shortcuts taken which needs to be sorted out - but it works.You can clone the code and build it (running build.ps1) or simply use NuGet to download it. [Update: preferred method is using Chocolatey - see below]
PM> Install-Package SuperBenchmarker
For usage, see the wiki on the GitHub. I value feedbacks, also if interested to get involved with the project let me know.
Update
Courtesy of Mike Chaliy, this has now a chocolatey package. So if you have chocolatey installed (and if not here are the instructions), simply run this command in command line:
cinst SuperBenchmarker
Info
Usage:
sb.exe -u url [-c concurrency] [-n numberOfRequests] [-m method] [-t template] [-p plugin] [-f file] [-d] [-v] [-k] [-x] [-q] [-h] [-?]
Parameters:
-u Required. Target URL to call. Can include placeholders.
-c Optional. Number of concurrent requests (default=1)
-n Optional. Total number of requests (default=100)
-m Optional. HTTP Method to use (default=GET)
-p Optional. Name of the plugin (DLL) to replace placeholders. Should contain one class which implements IValueProvider. Must reside in the same folder.
-f Optional. Path to CSV file providing replacement values for the test
-d Optional. Runs a single dry run request to make sure all is good (boolean switch)
-v Optional. Provides verbose tracing information (boolean switch)
-k Optional. Outputs cookies (boolean switch)
-x Optional. Whether to use default browser proxy. Useful for seeing request/response in Fiddler. (boolean switch)
-q Optional. In a dry-run (debug) mode shows only the request. (boolean switch)
-h Optional. Displays headers for request and response. (boolean switch)
-? Optional. Displays this help. (boolean switch)
Examples:
-u http://google.com
-u http://google.com -n 1000 -c 10
-u http://google.com -n 1000 -c 10 -d (runs only once)
-u http://localhost/api/myApi/ -t template text (file contains headers to be sent for GET. format is same as HTTP request)
-u http://localhost/api/myApi/ -m POST -t template.txt (file contains headers to be sent for POST. format is same as HTTP request with double CRLF separating headers and payload)
-u http://localhost/api/myApi/{{{ID}}} -f values.txt (values file is CSV and has a column for ID)-u http://localhost/api/myApi/{{{ID}}} -p myplugin.dll (has a public class implementing IValueProvider defined in this exe)
-u http://google.com -h (shows headers)
-u http://google.com -h -q (shows cookies)
-u http://google.com -v (shows some verbose information including URL to target - especially useful if parameterised)
As you probably know, the ASP.NET team is publishing the latest ASP.NET Web API on a nightly MyGet feed, and you can grab them from there and play with the latest stuff without having to deal with all the hassle … Continue reading →
The post The future is now – OWIN and multi-hosting ASP.NET web applications appeared first on StrathWeb.
With .NET Framework 4.5 (or .NET 4.0 NuGet: Microsoft.AspNet.WebApi.Client), a new HttpClient for .NET has been embraced.
The usage is as simple as it could be:
When debugging this piece of code, you might get this excecption:
System.IO.IOException “The specified registry key does not exist.”
This is caused by the security update
MS12-074: Vulnerabilities in .NET Framework could allow remote code execution: November 13, 2012
To get rid of the Exception from above, you have to add the registry key:
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\.NETFramework]
"LegacyWPADSupport"=dword:00000000
On x64 systems, the key is:
[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\.NETFramework]
"LegacyWPADSupport"=dword:00000000
For convenience, I’ve added a .reg-File which you can use (at your own risk, of course as it does change your system settings).
Ingo and I just published a new book chapter of our henriquat.re online (continuously deployed) ebook.
The topic this time is about properly integrating SignalR hubs with your AngularJS applications to realize near realtime push communication. For web browser, desktop or mobile apps.
"Pushing Data: Integrating With ASP.NET SignalR Hubs"
In modern applications the end users want to get their data. They want it now, they want it up-to date. In fact it does not matter whether these are pure web application, native desktop installations or mobile apps: everybody wants his data now!
For .NET-minded developers there are a numbers of options to implement near-real-time push style communication from the server/the services to the clients/consumers. You can choose plain HTTP or the super-new WebSockets features available in .NET 4.5 together with Windows 8 and Windows Server 2012. But the coolest and increasingly popular approach is to use a new framework: ASP.NET SignalR.
While it is not intended- and surely beyond the scope of this ebook - to give an introduction or even deep dive into SignalR, we need to have a look at some concepts and code in order to realize a smooth integration of SignalR and AngularJS.
The final goal of this chapter is to have an AngularJS-style integration of calling and listening to server-side SignalR push services.
Enjoy!
An old post. But since I am writing about AuthenticationHandler..this is still relevant!
(OK – I only included OAuth2 in the title to get your attention – this applies to whatever framework or technology you use to work with JSON web tokens aka JWTs)
Following the pattern from my two previous posts, you can also validate JWTs with a simple extension method over the basic AddMapping functionality.
For validating a JWT you need to specify three items:
- The name of the issuer that you expect the JWT to come from (an identity provider or authorization server)
- The expected audience (a symbolic name of the service consuming the JWT)
- The key material to validate the signature (either a symmetric key or a X.509 certificate)
The following method adds a mapping for an incoming Authorization header with a scheme of Bearer – the response will also contain the Bearer scheme. The key used is a symmetric key:
authentication.AddJsonWebToken(
issuer: Constants.IdSrv.IssuerUri,
audience: Constants.Audience,
signingKey: Constants.IdSrv.SigningKey);
The current extension methods of IdentityModel uses my own JWT implementation – but in the sample (as well as in the latest IdentityServer version) I have already switched to Microsoft’s JWT handler. The signature of the extension methods stay the same.
Given the flexibility of the AuthenticationHandler, you can also fetch the JWT from other places like an alternative header or a query string. Another emerging pattern is to return the audience of the service and the URL of the token endpoint in the 401 response – again – easy to accomplish:
authentication.AddJsonWebToken(
issuer: Constants.IdSrv.IssuerUri,
audience: Constants.Audience,
signingKey: Constants.IdSrv.SigningKey,
options: AuthenticationOptions.ForAuthorizationHeader("Bearer"),
scheme: AuthenticationScheme.SchemeAndChallenge(
"urn:myapi", "url=https://idsrv.local/issue/token"));
HTH
Filed under: .NET Security, IdentityModel, IdentityServer, OAuth, WebAPI
Following the last article on parameter binding from URI, I received an interesting question – “what if I wanted to prevent binding parameters from query string and only allow binding from route values”? In other words, prevent passing values to … Continue reading →
The post ASP.NET Web API and greedy query string parameter binding appeared first on StrathWeb.
If you want to self-host your ASP.NET Web API and serve static files as well, a viable solution is to use OWIN and Katana.
Filip has been writing about both a while ago here. Since then, some moving parts have changed and there have been improvements in terms of usability.
One of the improvements is Visual Studio Tooling for Katana by which you get a Visual Studio 2012 Template.
Just get the Katana.0.21.0-pre.zip from the project website at CodePlex (*sigh*
) and unzip it.
Now, install the Katana.vsix and after that, run Visual Studio.
Create a new Project from Templates / Visual C# / Katana Console Application.
Hitting F5 will fire up a new Console Window showing “Started”.
If you open http://localhost:12345 in your browser, you’ll see this:

Now, let’s add ASP.NET Web API to our host.
First, run this inside your NuGet Package Manager Console:
Install-Package Microsoft.AspNet.WebApi.Owin –Pre
This will install the ASP.NET Web API packages and the OWIN extensions for ASP.NET Web API.
After that, update the Startup.cs inside the Visual Studio Solution – this is, how the file should look before the update:
Now, the updated one:
To get some ASP.NET Web API action, let’s add a simple Controller:
Let's start our Application again by hitting F5. Pointing our Browser to http://localhost:12345/api/helloworld should result in this:

As the title of this post also promised static files to be served, we need to do some further work:
Jump back to your NuGet Package Manager Console and run:
Install-Package Gate.Middleware
This will install the middleware required for static file handling using OWIN.
As with ASP.NET Web API, we have to register the static file extensions in our Startup.cs – yet, another update:
Now let’s add a default.html document to serve some HTML.
Make sure to change the “Copy to Output Directory” property of the default.html to “Copy if newer” or “Copy always”.
Restart your application again and guess what may be the result…

Oh and by the way: if you don’t like port 12345: take a look at the Program.cs 
That’s it. Also make sure to check out the OWIN stuff at GitHub.
As of version 0.5.1 Linq to Querystring now supports Mongo DB out of the box, via the linq support provided by the C# driver. But what is really cool is that with a little bit of code, we can also write Linq queries and hence perform Linq to Querystring filtering on loosely typed data!
Fork of the MongoDb driver
When I talk about Linq queries against loosely typed data, I mean stuff like this:
var results = mongoCollection.AsQueryable().Where(o => o["Name"] == "Roysvork");
Unfortunately this is not supported by the Mongo C# linq stuff out of the box… the driver only know hows to handle indexers when dealing with arrays. There is a pull request pending to fix this issue which will hopefully be resolved very soon, but for now you can use my fork of the driver which is also available as a nuget package:
PM> Install-Package mongocsharp.linqindexers
I will try to keep this up to date with the latest source from the driver itself, but please bear in mind that although it should be sound and working, it is not official nor supported by 10gen! Hopefully it won’t be around for very long.
Serialisation info
Now for the next step… the Mongo driver needs a source of serialiation information in order to know what to do with our queries. The most common way this usually works is via class maps (either implicit or explicit) , and a BsonClassMapSerializer. When dealing with loosely typed data we don’t have this information available to us however, and documentation is quite sparse on the matter.
After a bit of digging around though, there is a class in the driver that we can use… the BsonDocumentBackedClassSerializer. As the name suggests we need to use this in conjunction with a BsonDocumentBackedClass. Both of these classes are abstract, so we need to write a bit of boilerplate in order to use them.
Here’s the class:
And here’s the serializer:
Using the MongoDocument class
The MongoDocument class has an indexer, so basic usage of the mongo document class works like this:
There’s a couple of cool things at play here… the serializer takes care of generating an _id for us by implementing IBsonIdProvider members GetDocumentId and SetDocumentId. The document class itself also has an implicit cast operator back to BsonDocument for ease of use when you need more granularity. Seems simple? It is!
Registering concrete members with the serializer
There is one more thing that I’d like to elaborate on a little bit, as you may find it useful to get a little bit more flexibility out of your loosely typed MongoDocument. If you look closely at the code above, you’ll see this property in the class:
[BsonId]
public ObjectId Id { get; set; }
And then correspondingly in the constructor for the serializer:
this.RegisterMember("Id", "_id", ObjectIdSerializer.Instance, typeof(ObjectId), null);
This allows us to control how our document gets serialized, and also how it behaves in Linq. Given these lines, the following is perfectly valid and works fine, even though the value itself is stored in the BsonDocument backing the class:
var record = mongoCollection.AsQueryable().Where(o => o.Id == ObjectId.Parse("ABCDE1234"));
You can add more of these if you like… just add a property and a corresponding register member call… the parameters should be fairly straightforward, just make sure to pick the appropriate serializer and type.
Just the start
I’m not sure why the BsonDocumentBackedClass and serializer aren’t more well documented. It seems like up until now they have only really seen internal use, but we are using this code in a project that is nearing completion, it’s stable and working really well for us.
There is much more that we can do with MongoDb and Linq by using this code, and in the next post in this series I’ll be exploring how we can work with nested objects and child collections by controlling serialization of our MongoDocument even further.
Don’t forget, you can use this in conjunction with Linq to Querystring and the [] notation to combine your loosely typed data structures with the power of OData. Why not give it a try today!
Pete
References:
http://docs.mongodb.org/ecosystem/tutorial/use-linq-queries-with-csharp-driver/
https://github.com/Roysvork/mongo-csharp-driver
https://nuget.org/packages/mongocsharp.linqindexers/
http://docs.mongodb.org/ecosystem/tutorial/serialize-documents-with-the-csharp-driver/
http://api.mongodb.org/csharp/1.8.1/html/225cb105-7edc-9bdf-9b2d-f9232bda4623.htm
https://github.com/Roysvork/LinqToQuerystring#general
In my last post, I showed how to configure the AuthenticationHandler using the AddMapping method. While you have full control here, I added a number of convenience extension methods that cover common use case. Following is an overview of the HTTP Basic Authentication related extensions.
Simple
The following code is the simplest way to setup Basic Authentication:
- Credential is expected on the Authorization header using a scheme of Basic
- Validation is done by the default membership provider
- Www-Authenticate header with scheme of Basic and a realm of localhost get sent back with the 401
var config = new AuthenticationConfiguration
{
RequireSsl = true
};
// delegate validation to membership provider
config.AddBasicAuthentication(Membership.ValidateUser);
In addition you can pull roles from the default role provider like this (or any other method with the same signature):
// delegate validation to membership and fetch roles from role manager
config.AddBasicAuthentication(
Membership.ValidateUser,
Roles.GetRolesForUser);
Custom credential validation
You can use whatever logic you like to validate the credentials. As long as your method takes two strings (user name and password) and returns a bool (success or not).
// custom username validator
config.AddBasicAuthentication(ValidateUser);
When credential validation fails, a 401 status code gets sent back. You can control the exact layout of the response by throwing an AuthenticationException inside the credential validation logic. The following code shows how to send back a 400 (bad request) instead of a 401 (sample code!):
private static bool ValidateUser(string userName, string password)
{
if (userName == "bob")
{
throw new AuthenticationException
{
StatusCode = HttpStatusCode.BadRequest,
ReasonPhrase = "Invalid client"
};
}
return true;
}
Retain password
Sometimes you want to defer validation of credentials, or need the client password for delegation. In that case you can use the retain password option to save the password as a password claim that you can access later from the claims collection:
// retain password
config.AddBasicAuthentication(ValidateUser, retainPassword: true);
Custom realm and headers
You can also specify a realm for the response header:
// different realm
config.AddBasicAuthentication(ValidateUser, “MyRealm”);
…and to look for credentials on a different header:
// different header
config.AddBasicAuthentication(
ValidateUser,
AuthenticationOptions.ForHeader("X-Authorization"),
“My Realm”);
Claims Transformation
If you need more control over the returned claims, you can specify a ClaimsAuthenticationManager derived implementation on AuthenticationConfiguration.
You can of course also create new extension methods over the raw AddMapping functionality if something you frequently need is missing.
HTH
Filed under: IdentityModel, WebAPI
AuthenticationHandler is an ASP.NET Web API message handler that can map incoming credentials to a token handler. The token handler in turn can parse credentials and create a principal.
In addition AuthenticationHandler provides some common services like claims transformation, session tokens and handling of response headers.

Your job is to do provide the mapping between credential and token handler, e.g.
- Basic Authentication credentials on the Authorization header
- JWT or SAML token on the Authorization header
- Client certificate
- Access key on the query string
- Signature over incoming HTTP request
…and which authentication hint gets sent back (along the 401 status code).
For this definition you use the AuthenticationOptionMapping class:
var mapping = new AuthenticationOptionMapping
{
// where to look for credentials
Options = options,
// how to validate them
TokenHandler = handler,
// which hint to give back if not successful
Scheme = scheme
};
Options could be e.g.:
- the Authorization header (with some scheme)
- some other HTTP header
- a query string parameter
- a client certificate
- a cookie
Thinktecture IdentityModel comes with several pre-defined token handlers, e.g.
- JWT, SWT and SAML tokens
- Basic Authentication
- client certificates
- access keys
…and last but not least, you have control over the Www-Authenticate header that get’s sent back if authorization was not successful, e.g.
- some scheme and some realm
- scheme only
- scheme and some challenge
You can add all required associations to the authentication configuration:
var config = new AuthenticationConfiguration
{
RequireSsl = true
};
config.AddMapping(mapping);
…and finally add the handler to the Web API runtime:
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
var authConfig = ConfigureAuthentication();
config.MessageHandlers.Add(new AuthenticationHandler(authConfig));
After that, authentication handler will inspect every request, look for credentials, and if successful create and populate the principal.
HTH
Filed under: IdentityModel, OAuth, WebAPI
Today, let’s kick off a series intended to look at different aspects of HTTP parameter binding in ASP.NET Web API. Why? Aside from the awesome series by Mike Stall, there isn’t really that much material on the web on this … Continue reading →
The post ASP.NET Web API parameter binding part 1 – Understanding binding from URI appeared first on StrathWeb.
It’s this time of the year again!
http://www.dotnetrocks.com/default.aspx?ShowNum=863
“Dominick Baier returns to talk to Carl and Richard about the current state of security in .NET 4.5. Dom starts out talking about how WebAPI has impacted the development of web services without much in the way of new security features – so he built some for everyone to use (check the links below). The conversation then digs into the challenges around OAuth 2 and the challenges of building specifications by committee when you’re dealing with security. Also listen for a great dig into the real goals of identity technologies that largely haven’t come to pass yet – there’s still a ways to go!”
Filed under: .NET Security, ASP.NET, Azure, IdentityModel, IdentityServer, OAuth, WCF, WebAPI
…in the context of token-based security systems.
There are many practical and philosophical ways to discuss the difference between the two terms. But since there is quite some confusion, I want to look at it from the perspective of the “usual suspects” token-based protocols we are commonly using today to build applications. In particular I try to make it very clear where OAuth2 vs OpenID Connect fits in.
But first the “formal” definitions:
Authentication is a process where a person or a computer program proves their identity in order to access information.
Authorization is the act of granting a person or other entity permission to use resources in a secured environment. This is usually tightly linked to authentication.
Authentication
My rule of thumb is, when an application requests an identity token for its own use to provide personalization or access control to application features, that’s authentication. Or technically, the requested token’s audience is the requester itself and the requesting application can parse and validate the token to use the information contained.

Typical protocols used for authentication: Kerberos, WS-Federation, SAML2p, OpenID (Connect). The resulting token is often called an identity token.
Authorization
In contrast, when the application requests a token for a different party than itself – e.g. a backend, that falls into the authorization bucket. This token is opaque to the requester and only makes sense in the context of the audience (aka the backend). The backend can parse and validate the token and control access based on the contained information.

Typical protocols used for authorization: Kerberos, WS-Trust, OAuth2. The resulting token is often called an access token.
But – what about authentication with OAuth2?
Some providers advertise OAuth2 sign-in – where does that fit in? Well – OAuth2 on its own cannot provide authentication services and when you look closer, you can see that those providers use some custom extensions to make it happen. Quoting the Google documentation (link):
“The Google endpoints described here align with the OpenID Connect specification, which at the time of this writing, is in early draft stage. For reference, the OpenID Connect specification is very similar to the OAuth 2.0 protocol. These Google endpoints will update as the specification matures.”
To find out what is necessary to teach OAuth2 the authentication trick, I can recommend reading this piece by Tim Bray, the OpenID connect specification and this and this explanation why OAuth2 on its own is not enough.
HTH
Filed under: .NET Security, IdentityModel, IdentityServer, OAuth, WebAPI
This can be very handy when having to integrate web APIs / mobile devices with ADFS!
In general I think the API design of the WS-Federation support in WIF / .NET 4.5 is a bit unfortunate.
It was a strange decision to combine the HTTP module (aka the FAM) and the more generic protocol helpers into a single class. And the fact the system.identityModel configuration sections are not declared by default, makes the FAM hard to use as a “standalone” library (for the search engines: “ID7027: Could not load the identity configuration because no <system.identityModel> configuration section was found.”). Microsoft?! Please fix this.
That all in combination makes it non-obvious how to “manually” process WS-Federation messages and since the question came up recently – here’s how to do it with ASP.NET Web API:
To create the WS-Federation request you can use this code:
public HttpResponseMessage Get()
{
var signInRequest = new SignInRequestMessage(
new Uri(“https://idsrv.local/issue/wsfed “),
“urn:realm”);
var response = Request.CreateResponse(
HttpStatusCode.Found);
response.Headers.Location =
new Uri(signInRequest.WriteQueryString());
return response;
}
The interesting bit is processing the response. As long as you can turn the post data into a NameValueCollection, it’s quite easy:
public HttpResponseMessage Post(HttpRequestMessage request)
{
var form = request.Content.ReadAsFormDataAsync().Result;
var signInResponse = WSFederationMessage.CreateFromNameValueCollection(
FederationMessage.GetBaseUrl(request.RequestUri),
form) as SignInResponseMessage;
var fam = new WSFederationAuthenticationModule();
// set all the necessary configuration
// don't forget to declare the system.identityModel config sections
fam.FederationConfiguration = new FederationConfiguration();
var token = fam.GetSecurityToken(signInResponse);
// validate token etc.
}
HTH
Filed under: ASP.NET, IdentityModel, WebAPI
Claims, WS-Federation, WS-Trust, WS-Security, ASP.NET, Federation, Single Sign-On, Home Realm Discovery, WCF, SAML, JWT, Web API, OAuth2, Thinktecture IdentityServer & IdentityModel, ADFS, Windows Azure Active Directory & Access Control…
Do the above terms sound interesting? Then join me for a two day pre-con workshop at the fantastic Norwegian Developer Conference. Will be a blast!
http://www.ndcoslo.com/Article/Workshops/claims
Filed under: Azure, IdentityModel, IdentityServer, OAuth, WCF, WebAPI
A Brief Recap
First of all I’d like to apologise for the delay in the coming of the second part of this series. It was originally intended to be a guide to building a simple oData query parser with ANTLR, but as I worked on the samples, it quickly turned into a full scale project.
I few months back I came across a need to use OData with a loosely typed data structure. I quickly found that OData support in Asp.NET Web API was readily available… but only when coding against a known entity model. Also not all features of OData are available out of the box, and even fewer work without having to jump through significant hoops. I started playing around with a solution, and this is the result.
Presenting: Linq to Querystring
The aim of the Linq to Querystring project is to provide a fast, lightweight subset of the OData URI Specification, with additional flexibility to allow use of loosely typed\dynamic data structures. It also supports the $inlinecount and $select operators, and at the time of writing support for $expand is in development.
Linq to Querystring works by parsing an OData query using ANTLR, and then mapping the resulting syntax tree on to a .NET IQueryable. This means that in theory it can work with any Queryable Provider, at present it has been tested with Linq to Objects, Entity Framework & MongoDB
To get started, first add it to your project using NuGet. Once you’ve done that, simply add the following attribute to a Web API controller action that returns an IQueryable or Task<IQueryable>:
[LinqToQueryable]
public IQueryable<Movie> Get()
And that’s all there is to it. You can now append OData query parameters to your API calls and see the results. You can also use the built in IQueryable extension methods manually if you need to.
Addressing issues with OData
One thing I should stress is that Linq to Querystring is that the OData specification itself is very extensive, and Linq to Querystring does not claim (or intend) to support all of it. In fact, OData itself seems to split opinion – see here for example: http://stackoverflow.com/questions/9577938/odata-with-servicestack.
In to the answer above, Mythz states some concerns that proponents of REST often have about OData, which Linq to Querystring goes some way towards addressing:
- Poor development practices – Linq to Querystring is simple, flexible and open source, so it can respond to new technologies and paradigms.
- Promotes bad web service practices – No longer tied to your DBMS as it works with any IQueryable, so you don’t have to expose your data model through your services.
- Only used in Microsoft technologies – The main expression parsing engine of Linq to Querystring is written in ANTLR so can be easily ported to other languages that support construction of expression trees.
- OData is slow - Leaving out certain elements of the protocol helps to keep things fast compared to full blown OData implementations. All Linq to Querystring does is map the AST produced by ANTLR onto an IQueryable expression tree.
Of course this is probably not going to convince true REST zealots, but I definately see a need and use for in-query filtering regardless if you prefer HATEOAS or CSDS.
Flexibility and extra functionality
Additionally – due to it’s flexbility – the project may also include features that are not present in the standard OData query specification. Such features are carefully designed not to detract from the power of OData, always augmenting the existing functionality.
For example, in Linq to Querystring you can use the ‘[' and ']‘ brackets to designate that a property should be interpreted dynamically. For example the following filter query
$filter=[Age] gt 18
Is equivilent to:
looselyTypedList.Where(o => o["Age"] > 18);
Current features & roadmap
Please consult the Github site https://github.com/Roysvork/LinqToQuerystring for currently supported features and documentation, as these are changing all the time. Some highlights include:
- Support for other API frameworks, NancyFX\ServiceStack
- UI plugin for constructing Linq to Querystring OData queries
- Support for the $expand operator
- Testing for other NoSQL Linq Providers
The project is still in development, so some things might not work exactly correctly so please let me know if they do by registering an issue on github, or submit a pull request. Be sure to check back in on the github page regularly for updates in the next few weeks, and l’ll also be writing a series of articles on how to make the most of OData, so stay tuned!
If you’re looking for better OData functionality in your API, I think Linq to Querystring could be just what you need. Don’t take my word for it though, take a test drive over at the demo site: http://linqtoquerystring.azurewebsites.net/ and see for yourself!
Pete
Just a heads up – in the next drop of IdentityServer we will be switching to Microsoft’s JWT token handler. This adds support for X.509 based signatures and JWT over WS*.
On github there’s a branch called “Microsoft-JWT”, if you want to test ahead of time you can use the new code base already.
Filed under: IdentityServer, OAuth, WebAPI
Within the Microsoft Web Camps Spring 2013 Tour, Web Camp Istanbul was held at Microsoft Istanbul office and we had such an incredible, enjoyable event. During the day, Jon Galloway, Umit Sunar and myself presented several topics including Windows Azure, ASP.NET MVC, ASP.NET Web API and ASP.NET SignalR.
During the day, I helped Jon by trying to be the dummy guy during his ASP.NET MVC presentation. I also presented on ASP.NET Web API and ASP.NET SignalR where I showed a few sample applications. You could find the source code for those samples on my GitHub repository: https://github.com/tugberkugurlu/IstanbulWebCamps201304.
You can also find the slides for the ASP.NET Web API session: ASP.NET Web API Intro - Microsoft Web Camp, Istanbul. Here are also some links for the stuff that I have mentioned during the sessions.
ASP.NET SignalR
ASP.NET Web API
I would like to thank Jon Galloway for coming to Istanbul for this event and allowing us to have such a fun day. I personally really enjoyed the whole event and also the small Istanbul tour I had with Jon
I also would like to thank Brady Gaster as he's one of the people who made this event happen. I'm hoping that we will keep seeing these types of web events in Istanbul more 
Today I stumbled upon an interesting Stackoverflow question, where the user was asking how to go about self-hosting Web API in LinqPad. The question has gone unanswered since December, and I’m guessing even the OP forgot about it. However, I’d … Continue reading →
The post Hosting ASP.NET Web API in LinqPad appeared first on StrathWeb.
Check out Badri’s book. Essential information about securing ASP.NET Web APIs!
http://amzn.com/1430257822
Filed under: IdentityModel, OAuth, WebAPI
[Level T2] OK, so you have created your Web API project and deployed into production and now boss says dude, we have performance problems. Or maybe head of testing wants to benchmark the application and monitor it over the course of next releases so we catch problems early. Or you are just a responsible geek interested in the performance of your code.
In any case, no serious web code can be written without having performance in mind. Problem is that existing system, .NET and ASP.NET performance counters can go as far as telling you overall picture of the performance and the metrics usually coalesced into a single value while you need to drill down to individual APIs and see what's happening. Now this can be another burden on your already squeezed time remaining. So how easy is it to publish counters for your individual API? Just these few steps! TLDR; :
- Use NuGet to install PerfIt! into your ASP.NET Web API project (make sure you get version +0.1.2 - there was a bug fixed in this version)
- Add PerfitDelegatingHandler to the list of your MessageHandlers
- Decorate those actions you want to monitor
- Use "Add New Item" to add an Installer class into your Web API project. Write just a single line of code for Install and Uninstall.
- Use InstallUtil.exe in an administrative command window to install (or uninstall) your counters. Done!
 |
| Seeing performance counters of your own project is kinda cool! |
1-Adding PerfIt! to your project
So to add PerfIt! to the project, simply use NuGet console:
PM> Install-Package PerfIt
2-Adding PerfItDelegatingHandler
Now we need to add the delegating handler:
config.MessageHandlers.Add(new
PerfItDelegatingHandler(config, "My test app"));
The string passed in here is the application name. This will be used as the instance name in the performance counter. You can see that in the screenshot above.
3-Decorate actions
For any action that you want the counters to be published, use PerfIt action filter and define the counters you want to see published:
// GET api/values
[PerfItFilter(Description = "Gets all items",
Counters = new []{CounterTypes.TotalNoOfOperations,
CounterTypes.AverageTimeTaken})]
public IEnumerable<string> GetAll()
{
Thread.Sleep(_random.Next(50,300));
return new string[] { "value1", "value2" };
}
// GET api/values/5
[PerfItFilter(Description = "Gets item by id",
Counters = new[] { CounterTypes.TotalNoOfOperations,
CounterTypes.AverageTimeTaken })]
public string Get(int id)
{
Thread.Sleep(_random.Next(50, 300));
return "value";
}
Here we have decorated GetAll and Get to publish two types of counters (currently these counters are available but more will be added - see below).
The format of the counter will be [controller].[action].[counterType] (see screenshot above). As such, please note that we had to change the first Get to GetAll to so that the counter names do not get mixed up. If you cannot do that (while ASP.NET Web API allows you do change the name as long as the action starts with the verb), alternatively use the Name property of the filter to define your own custom name (which we did not specify here to allow default naming take place).
Description property will appear in the perfmon.exe window and is known as CounterHelp. Counters is an array of string, each string being a defined against PerfIt! runtime (see roadmap for more info) as a counter type. Another option is the ability to define Category for the counter which we also did not specify so by default, it will be the assembly name. You can see the category in the screenshot above as PerfCounterWeb (see the typo!).
4-Adding Installer to your project
Now use "Add New Item" to add an installer class to your project. You might have not seen this in the new item templates but it is definitely there (screenshot from VS2012 but project is .NET 4.0 so can be done in VS2010):
After adding the class, override Install and Uninstall methods and add the code below (hit F7 to see the code):
public override void Install(IDictionary stateSaver)
{
base.Install(stateSaver);
PerfItRuntime.Install();
}
public override void Uninstall(IDictionary savedState)
{
base.Uninstall(savedState);
PerfItRuntime.Uninstall();
}
5-Use installutil.exe to install counters
Just make sure you open an administrative command window. Use Visual Studio command prompt since it has the right path for InstallUtil.exe. cd to your bin folder and register your assembly:
c:\projects\myproject\bin>InstallUtil.exe -i MyWebApplication.dll
This should do the trick. Use -u switch to uninstall the counters.
That is all that is needed. Just hit your app and start benchmarking your app in the perfmon.exe.
Turning off the publishing of counters
In normal/production circumstances, you might wanna turn off publishing of the performance counters. In this case, you can put the line below in the appSettings of your web.config:
<appSettings>
<add key="perfit:publishCounters" value="false"/>
I have kept the default behaviour to publish counters - so to eliminate one configuration step to get up and running. This may change in the future - but unlikely.
PerfIt! Roadmap
I needed to add performance counters to my Web API application. With wife away and a few Easter bank holiday days, I managed to start and finish version 0.1 of PerfIt! library.
Future work includes adding more counter types and looking at improving the pipeline. PerfIt! has been built on the top of its own extensibility framework so very easy to add your own counters, all you need is to implement
CounterHandlerBase and then register the handler in
PerfItRuntime.HandlerFactories.
Any problems, issues, comments or feedbacks, please use the
GitHub issues to get it touch. Enjoy!
In this article I am going to show how to use Redis as a data store in a ASP.NET Web API application. I will implement a basic scenario that leverages ServiceStack.Redis library and its strongly typed Redis client, show how to model and store one-to-many relationships and how to use Web API dependency injection capabilities along with Autofac to inject [...]
ASP.NET Web API does a really good job at letting you control the amount of error details returned in the framework responses. And that is for both your own (“developer-generated”) exceptions, as well as the ones produced by the Web … Continue reading →
The post Per request error detail policy in ASP.NET Web API appeared first on StrathWeb.

This is an awesome news that I am proud of to write about. I think it all started out with my reply to Brady Gaster on twitter:
And it's now a real deal thanks to awesome Web Camps team! One leg of Microsoft Web Camps spring 2013 tour will be held in Microsoft Istanbul office on the 6th of April, 2013. It will be a full day event. Jon Galloway, Umit Sunar and me will be giving talks on various latest Microsoft Web Stack technologies including Windows Azure, ASP.NET Web API, ASP.NET SignalR, ASP.NET MVC and so on. You can see the typical agenda of Web Camps here.
You can also find more about Web Camps spring 2013 tour from Jon Galloway's and Brady Gaster's blog posts:
There are finite number of seats available. So, register ASAP to participate this great event from the following link:
https://msevents.microsoft.com/CUI/EventDetail.aspx?EventID=1032548038&Culture=TR-TR&community=0
See you at Web Camps 
I have published an article at Tech.pro today, about building a real-time shopping cart with some of our favorite technologies – ASP.NET Web API, SignalR and Knockout.js (or, as Brad would say, with the “Webstack of Love”). Click here to … Continue reading →
The post Shopping cart with SignalR, ASP.NET Web API and Knockout.js appeared first on StrathWeb.
[Level T2] CacheCow is an implementation of HTTP Caching for ASP.NET Web API. It implements HTTP caching spec (defined in RFC 2616 chapter 13) for both server and client, so you don't have to. You just plug-in the CacheCow component in server and client and the rest is taken care of. You do not have to know details of HTTP caching although it is useful to know some basics.
It is also a flexible and extensible library that instead of pushing a resource organisation approach down your throat, allows you to define your caching strategies and resource organisation using a functional approach. It stays opinionated only about caching where the opinion is HTTP spec. We shall delve into these customisation points in the future posts. But first let's to caching 101.
Caching
Caching is a very overloaded and confused term in ASP.NET. Let's review the cachings available in ASP.NET (I promise not to make it too boring):
HttpRuntime.Cache
This class is used to cache managed objects in SERVER memory using a simple dictionary like key-value approach. You might have used HttpContext.Current.Cache but it is basically nothing but a reference to HttpRuntime.Cache. So how is this different to using a plain dictionary?
- You can define expiry so you do not run out of memory and your cache can be refreshed. This is the most important feature.
- It is thread-safe
- You can never run out of memory with this even with no expiry. As long as it hits a configurable limit, it purges half of the cache.
- And also: it stores the data in the unmanaged memory of the worker process and not in heap so does not lengthen GC sweeps.
This cache is useful for keeping objects around without having to acquire them all the time (could be complex calculation or IO cost such as database). No, this is not HTTP caching.
Output cache
In this approach output of a page or a route can be cached on the SERVER so the server code does not get executed. You can define expiry and let the output cached based on parameters. Output cache behind the scene uses HttpRuntime.Cache.
You guessed it right: this is also not HTTP caching.
HTTP Caching
In HTTP Caching, a cacheable resource (or HTTP response in simple terms) gets cached on the CLIENT (and not server). Server is responsible for defining cache policy, expiry and maintaining resource metadata (e.g. ETag, LastModified). Client on the other hand is responsible for actually caching the response, respecting cache expiry directives and validating expired resources.
The beauty of the HTTP caching is that your server will not even be hit when client has cached a resource - unlike other two types of caching discussed. This helps with minimising the scalability, reducing network traffic and allowing for offline client implementation. I believe HTTP caching is the ultimate caching design.
One of the fundamental differences of HTTP caching with other types of caching is that a STALE (or expired) resource is not necessarily unusable and does not get removed automatically. Instead client call server and check if the stale resource is still good to use. If it is, server responds with status 304 (NotModified) otherwise it sends back the new response.
HTTP Caching mechanism can also be used for solving concurrency problems. When a client wants to update a resource (usually using PUT), it can send a conditional call and ask for update to run if and only if the version of the server is the same as the version of the client (based on its ETag or LastModified). This is especially useful with modern distributed systems.
So as you can see, client and server engage in a dance using various headers and things can get really complex. Good new is you don't have to worry about it. CacheCow implements all of this for you out of the box.
CacheCow consists of CacheCow.Server and CacheCow.Component. These two components can be used independently, i.e. each will work regardless the other is used or not - this is the beauty of HTTP Caching as a mixed concern which I explained
here.
CacheCow on the server
How easy is it to use CacheCow on the server? You just need to get the CacheCow.Server Nuget package:
PM> Install-Package CacheCow.Server
And then 2 lines of code to be exact (actually 3 but we will see why):
var cachecow = new CachingHandler();
GlobalConfiguration.Configuration.MessageHeandlers.Add(cachecow);
So with this line of code all your resources become cacheable. By default expiry is immediate so client has to validate and double check if it can re-use the cache resource but all of this can be configured (which we will talk about in future posts). Also server now is able to respond to conditional GET or PUT requests.
CacheCow on the server requires a database (technically cache store) for storing cache metadata - but we did not define a store. CacheCow comes with an in-memory database that can be used if you do not specify one. This is good enough for development, testing and small single server scenarios but as you can imagine not scalable. What does it take to define a database? Well, a single line hence the 3rd line and you can choose from SQL Server, Memcached, RavenDb (Redis to come soon) or build your own by implementing an interface against another database (MySql for example).
So in this way we will have 3 lines (although you may combine first two lines):
var db = new SqlServerEntityTagStore();
var cachecow = new CachingHandler(db);
GlobalConfiguration.Configuration.MessageHeandlers.Add(cachecow);
With these three lines, you have added full feature HTTP caching (ETag generation, responding to conditinal GET and PUT, etc) to your API.
CacheCow on the client
Browsers that we use everyday (and usually even forget to look at as an application) are really amazing HTTP consumption machines. They implement cache storage (file-based) and are capable of handling all client scenarios of HTTP caching.
Client component of CacheCow just does the same but is useful when you want to use
HttpClient for consuming HTTP services. Plugging it into your HttpClient is as simple as the server side. First get it:
PM> Install-Package CacheCow.Client
Then
var client = new HttpClient(new CachingHandler()
{
InnerHandler = new HttpClientHandler()
});
In a similar fashion, client component of CacheCow requires a storage - and this time for the actual responses (i.e. resources). By default, an in-memory storage is used which is OK for testing or single server and small API but for persistent stores you would use from stores such as File, SQL Server, Redis, MongoDB, Memcached aleady implemented or just implement the
ICacheStore interface on the top of an alternative storage.
Constructor of the client
CachingHandler accepts an implementation of
ICacheStore which is your storage of choice.
So now cacheable resource will be cached and CacheCow will do conditional GET and PUT for you.
In the next post, we will look into server component of CacheCow.
I wrote many times about Web API, so you should know about the library and the main differences between the client part of Web API and the server side; in this post I’m going to write about the client side of this cool library.
Exactly like the “old” System.Net.WebRequest class, also the Web API client can manage the caching policy for all REST requests.
Before seeing the code, it’s important to understand what does it mean “manage the caching policy” and why we should do that.
The class HttpClient is created for web requests and it has all problems/features of a browser without the render and Javascript stuff.
All the modern browsers has an aggressive cache policy with the purpose of reducing the network traffic and increase the performances. The last point is really important: to execute operations faster browsers read a set of information from the response header (Etag, Cache-Control and Date), and, based on their values, it decides to take the data from the response or from the cache.
In one of the latest projects we are working in my company (I spoke about that here), we have to call some rest services which totally ignore the cache header values. To be clear I’ve the same headers values for different results so I’ve to disable the cache for my request to that endpoint because the default behavior use the cache:
Default cache policy (from MSDN)
Satisfies a request for a resource either by using the cached copy of the resource or by sending a request for the resource to the server. The action taken is determined by the current cache policy and the age of the content in the cache. This is the cache level that should be used by most applications.
To change the cache policy we need to do something like that:
using (WebRequestHandler handler = new WebRequestHandler())
{
handler.CachePolicy = new HttpRequestCachePolicy(HttpRequestCacheLevel.BypassCache);
using (HttpClient client = new HttpClient(handler))
{
response = await client.GetAsync("http://www.mysite.com/api/something/");
}
}
As you can see is really simple and really important so, be careful using the right Header values in your response J
Version 0.4 is out and with it a couple of features such as attribute-based cache control and cache refresh (see below). For the first time I felt that I have got to write a few notes about this version, least of which because of one breaking change in this release - although it is not likely to break your code as I explain further. Changes have been in the server components.
I and other contributors have been working on CacheCow for the last 8 months. I thought with a couple of posts I have explained the usage of CacheCow. But I now feel that with concept counts increasing, I need to start a series on CacheCow. Before doing that I am going to explain new concepts and the breaking change.
Breaking change
The breaking change was a change in the signature of CacheControlHeaderProvider from Func<HttpRequestMessage, CacheControlHeaderValue> to Func<HttpRequestMessage, HttpConfiguration, CacheControlHeaderValue> to accept HttpConfiguration.
If you have provided your own CacheControlHeaderProvider, you need to provide HttpConfiguration as well - which should be very easy to fix whether web-host or self-host.
Cache Control Policy
So defining cache policy against resource have been by setting the value of CacheControlHeaderProvider which you would define whether a resource is cacheable and if it is, what is the expiry (and other related stuff):
public Func<HttpRequestMessage, HttpConfiguration, CacheControlHeaderValue> CacheControlHeaderProvider { get; set; }
So by default CacheCow sets
Func to return a header value for private caching with immediate expiry
for all resources:
CacheControlHeaderProvider = (request, cfg) => new CacheControlHeaderValue()
{
Private = true,
MustRevalidate = true,
NoTransform = true,
MaxAge = TimeSpan.Zero
};
Immediate expiry actually means that the client can use the expired resource as long as it validates the resource using a conditional GET - as explained before
here.
But what if you want to
individualise cache policy for each resource? We could use per-route handlers but that is not ideal and generally it depends on the resource organisation approach. I have explained in my previous
post that resource organisation is one of the areas that needs to be looked at. But this is not within the scope of CacheCow. We are looking into solving this as part of another project while ASP.NET team are also looking into this. So I have decoupled the resource organisation project from CacheCow.
Having said that, in the meantime, I am going to provide some help with doing cache policy set up less painful. This means that CacheCow will come with a few pre-defined functions that help you with defining your cache control policy.
Good news! Cache policy definition using attributes
So now you can define your cache policy against your actions or controllers or both - although action attribute always takes precedence over controller. Using the popular ASP.NET Web API sample:
[HttpCacheControlPolicy(true, 100)]
public class ValuesController : ApiController
{
public IEnumerable<string> Get()
{
return new[] { "cache", "cow" };
}
[HttpCacheControlPolicy(true, 120)]
public string Get(int id)
{
return "cache cow... mooowwwww";
}
So GET call to the first action (
/api/Values) will have a max-age of 100 while GET to the second action (e.g.
/api/Values/1) will return a max-age of 120.
In order to set this up, all you have to do is to set the
CacheControlHeaderProvider property of your
CachingHandler to
GetCacheControl method of an instance of
AttributeBasedCacheControlPolicy:
cachingHandler.CacheControlHeaderProvider = new AttributeBasedCacheControlPolicy(
new CacheControlHeaderValue()
{
NoCache = true
}).GetCacheControl;
So in above we have passed a default caching policy of no-caching. This table defines which attribute value (or default provided in the constructor) is used:
Cache Refresh Policy
CacheCow works best when HTTP API is actually a REST API. In other words, it uses uniform interface (i.e. HTTP Verbs) to modify resources and this means that the caching handler will get the opportunity to invalidate and remove the cache when POST, PUT, DELETE or PATCH is used.
Problem is commonly HTTP API sits on the top of a legacy system where it has not control over modifications of resources and acts as a data provider. In such a case, the API will not be notified on resource changes and application will be responsible for removing cache metadata directly on the EntityTagStore used. And this is not always possible.
I am providing a solution for defining a time based cache refresh policy using attributes in a very similar fashion to Cache Control Policy - even the above table applies. Removal of items from cache store on the server happens upon the first request after the refresh interval has passed not immediately after interval. So we add the refresh policy provider:
cachingHandler.CacheRefreshPolicyProvider = new AttributeBasedCacheRefreshPolicy(TimeSpan.FromSeconds(5 * 60 * 60))
.GetCacheRefreshPolicy;
We have defined 5 hour refresh policy as default. And we override using controller or action attributes.
Future posts
As promised, next few posts will be a CacheCow walk-through.
Some time ago I posted a mini-series of posts about using Roslyn to script Web API, and that has gotten some great response. In that original post, I mentioned & used, without going into too much details, a very useful … Continue reading →
The post Leveraging Roslyn to author ASP.NET Web API without recompiling appeared first on StrathWeb.
In the last post I described some of the general problems with OAuth2 and its implementations. In this post I want to go into more detail and show some necessary hardening steps.
We did our best (well as much as a two people team can do) to implement as many security and validation checks as possible. If you find a bug, let us know.
Besides that standard web security practices, the following OAuth2 specific considerations apply:
You don’t need to implement every flow
The OAuth2 spec is huge. You probably only need a certain subset to get your job done. Don’t even try to implement every possible flow and protocol alternative.
We decided to implement authorization code, implicit and resource owner password flow only. That alone has reasonable complexity.
Token type and format
The OAuth2 spec does not specify a token format. We chose to use JSON Web Token (JWT) – and yes we implemented the token handling ourselves. This is not recommended, and since IdentityServer is based on .NET, we will change that to use the Microsoft JWT handler as soon as this leaves preview stage.
Redirect URI validation
This is a very common attack vector! If you don’t properly validate the redirect URI you might be sending the token or code to an unintended location.
We decided to a) always require SSL if it is an URL and b) do an exact match against the registered redirect URI in our database. No sub URLs, no query strings. Nothing. Unfortunately this breaks Microsoft’s OAuth support in ASP.NET 4.5 – but that’s a bug they have to fix. (see here).
Grant and response type validation
A number of recent hacks are based on the fact that grant and response types are input parameters. So e.g. someone could try to change the response type from code to token in the input query string, and – tada – suddenly some implementations return a token instead of just the authorization code.
We allow to bind the allowed flow to the client registration which in turn limits the allowed grant and response type. You should only allow one flow per client and rather create separate clients since they typically also have different trust levels (public vs confidential, trusted vs untrusted).
Bind tokens to the client
Make sure that when client 1 requests an authorization code that also only client 1 can use that code to request a token. Same for refresh tokens.
Don’t support credentials on the query string
We all know that credentials on query strings are the evil. Still they are allowed by the spec in certain situations (as an alternative to the authorization header). Say no to this madness and don’t implement it.
Protect client secrets
You wouldn’t store user passwords in clear text, would you? Same applies to client secrets. Use hashing – even better salted & iterated hashing. We use PBKDF2 (RFC 2898).
Encapsulated tokens are easy to get wrong
That’s why we use a handle based design to issue refresh tokens. That might not be as scalable, but makes me sleep better. Also make sure your refresh tokens are one-time use only.
References
Further recommended reading:
HTH
Filed under: IdentityModel, IdentityServer, OAuth, WebAPI
Right now there are many good “discussions” on OAuth2 security happening. Some are constructive, some rather destructive – and some simply hack one or the other website to prove the point.
In my opinion there are a number of reason OAuth2 has a rather bad reputation right now. In this post I want to focus on the problems, in the next post what we can learn and how IdentityServer (hopefully) mitigates them.
The spec is too relaxed
When you read the spec, you’ll see a lot of “out of scope” or “at the discretion of the implementer” phrases and many “SHOULDs” and “MAYs”. Or in other words, while writing the specs there were too many interests clashing, resulting in too many ways to achieve the same thing. This lead to changing the name from “OAuth2 Protocol” to “OAuth2 Framework”. WS* anyone?
Also the lack of a token type specification lead to many homegrown token formats that were missing one or the other important security features (like audience checking, encapsulated tokens…). Writing your own token format/implementation is hard, try to avoid that!
I think we really need something like a “basic” profile that hits the 80/20 use cases with exact instructions and guidance for the implementer.
OAuth2 looks too easy
Well – what I mean here is, in WS* world we all knew shit’s hard. In the mind of many people OAuth2 is just a bunch of redirects and HTTP posts. easy. job done.
All I can say is, we are still trying to solve the same non-trivial (read: hard) problems, just using different technologies. Just because one knows HTTP does not mean he also knows how to implement security protocols.
Even the big guys like Facebook got it wrong several times – and some are still playing a dangerous game (see redirect URI based attacks later in my reference links).
Lots of attack surface
Every aspect of OAuth2 can be controlled via input parameters (like query strings or the post inputs). If I were the security tester – of course the first thing I’d try is fuzzing them and see what happens. And catastrophical things happened.
Input is still evil, even when it comes via some specified protocol. Things like response types and redirect URI should come from the authorization servers configuration database, not from external input.
Security Theater
Security theater is a “technique” to make you feel secure/safe while actually doing nothing (see here).
While the OAuth2 flows for native/mobile apps have all the best intentions – namely the developer does not need to deal with the user’s password (and thus not store it) etc. – it does not help you to distinguish between good and bad apps.
No one can make sure that this windows with the authorization server UI is really the authorization server, even when it looks exactly like a browser window!
So in other words, the moment you installed an application on your device, you already made a trust decision. OAuth2 cannot safe you here.
That said, IMO developers should use the implicit flow because that’s (even with a little awkward user experience) still better than dealing with credentials yourself. Windows 8 is a very good example of a modern approach to the problem. The WebAuthenticationBroker API that is built right into the operating system allows for an easy way to do OAuth2 style authorization (and OpenID connect style authentication).
OAuth2 in not an authentication protocol
OAuth2 is an authorization protocol – that’s a huge difference. Everybody who confused the two terms has learned the hard way. Don’t follow them.
OpenID Connect specifies how authentication works on top of OAuth2 – just eight more specs to read.
But – Google, Facebook and friends do authentication with OAuth2 – what do you mean? Well they all do it either using some custom extension, or like Google, OpenID Connect and call it OAuth2 sign-in.
Bearer Tokens
Bearer tokens means that there is no binding between the access token and the HTTP request. In other words whoever manages to steal a token from you (e.g. on the wire) can use that token to do requests on your behalf.
All OAuth2 security currently relies solely on SSL/HTTPS to protect access token transmission. This would be OK in a perfect world. In the real world developers and/or infrastructure like to bypass SSL.
I can only speak for developers – NEVER EVER disable SSL certificate validation. NEVER EVER.
Unfortunately when you search for “how to handle SSL validation errors” on the internet, it is more likely to find information on how do disable validation (in any popular programming language) than a real answer to the question. Shame on them.
An alternative to bearer tokens would be MAC tokens. Yes they are a little harder to program against – but not much. We need this alternative – but there is currently no spec.
References
Here’s some further reading material. Many of the above points were inspired by the following articles. I totally recommended reading every single one:
Oh – and last but not least – please read Tim Bray’s post on OAuth2 which I think is a really good and balanced view on the topic.
Filed under: IdentityModel, IdentityServer, OAuth, WebAPI
We recently merged OAuth2 code flow and refresh token support into the main branch on Github. Please give it a try and tell us if it is working for you or not. After that feedback phase I will release v2.2 (maybe in two weeks).
The OAuth2 client configuration page has two new options now: one for enabling code flow, and one for allowing refresh tokens for that client:

Remember you should always select only one flow type per client – rather create multiple clients for each flow you want to support (see my next post on OAuth2 vulnerabilities for more details).
Also note the tokens link at the bottom which brings you to the refresh token search page where you can (based on different search criteria) view and delete refresh tokens:

We also changed the consent screen when refresh tokens are enabled for the client:

From a code point of you, we use the (or rather a) standard OAuth2 query string syntax and you can use the OAuth2Client class from Thinktecture.IdentityModel as a convenience, e.g:
var url = OAuth2Client.CreateCodeFlowUrl(
“https://idsrv.local/issue/oauth2/authorize “,
“codeflowclient”,
Constants.Scope,
“https://localhost:44303/callback “);
Which results in the following URL:
https://idsrv.local/issue/oauth2/authorize?
client_id=codeflowclient&
scope=urn:webapisecurity&
redirect_uri=https://localhost:44303/callback&
response_type=code
After IdentityServer sends back the code – you can again use OAuth2Client to request the token:
var client = new OAuth2Client(
new Uri("https://idsrv.local/issue/oauth2/token"),
"codeflowclient",
"secret");
var response = client.RequestAccessTokenCode(code);
If refresh tokens are enabled, you can request a fresh token like this:
var client = new OAuth2Client(
new Uri("https://idsrv.local/issue/oauth2/token"),
"codeflowclient",
"secret");
var response = client.RequestAccessTokenRefreshToken(refreshToken);
The full sample can be found here.
Filed under: ASP.NET, IdentityModel, IdentityServer, OAuth, WebAPI
So there’s quite a hype around REST lately, and I have to admit I’ve been on the bandwagon too. I’ve actually found it quite fun applying the constraints and trying to do things using a standard approach that will be familiar to other developers, and make my API easier to consume.
But recently I’ve become a bit disillusioned. I’ve tried to do a couple of things of late that I just couldn’t get to play nicely with REST:
- Modeling many-many relationships, assigning or breaking links between resources via a REST API.
- Bulk updates\inserts, or generally manipulating multiple resources at once.
spc
I frequently come up against the question of what makes an API RESTful, having a dig around, everyone seems to have opinions, but everyone seems to have questions too. Here are some that I’ve asked or that have come up in conversations recently:
- Is it ok to have a URI that only accepts POSTs?
- Is it ok to return a different representation on GET than the one expected by a POST to the same URI?
- Is it ok to assign a URI to the relationships between resources and allow them to be manipulated via representations?
- Can I update multiple resources by POSTing a composite representation?
Have a read through the comments in these two stack overflow questions, and you’ll quickly see what I mean:
http://stackoverflow.com/questions/511281/patterns-for-handling-batch-operations-in-rest-web-services?lq=1
http://stackoverflow.com/questions/969585/rest-url-design-multiple-resources-in-one-http-call
spc
So what is really RESTful?
RESTful architecture is governed by a set of key constraints… it must involve client-server interaction, be stateless and cacheable. It must be layered, i.e a client cannot ordinarily tell whether it is connected directly to the end server, or to an intermediary along the way.
It must provide a “Uniform Interface”, which simplifies and decouples the architecture. Said interface is subject to a set of guiding principles:
- Requests should identify an individual resource, and then a representation of that resource is returned. This representation is conceptually separate from the resource itself.
- When a client has a representation of a resource, it should have all the information it needs to manipulate that resource provided it has permission.
- Each request should include enough information to describe how to interpret the message, i.e specify a media type.
- Hypermedia as the engine of application state (aka HATEOAS) - Except for entry points to the application, the client should be able to discover actions that can be taken for a resource based on the representation, e.g via hyperlinks or location headers.
You’ll notice I’ve not made any mention of HTTP verbs yet (POST, GET, etc), or status codes. Thats because these are actually incidental to REST… although it was designed on HTTP, it is not limited to the protocol explicitly. RESTful architectures can be built upon any protocol that is sufficiently expressive and has a sufficiently well defined interface. It just so happens that these constructs are very useful for this purpose.
spc
So whats the problem?
The key element that people seem to skimp on or miss completely is the fourth bullet above, or to paraphrase, a REST API must be hypertext driven. Here’s what Roy Fielding, father of REST had to say in 2008:
http://roy.gbiv.com/untangled/2008/rest-apis-must-be-hypertext-driven
For the lazy amonst you (shame on you), here’s are the key quotes
A REST API should be entered with no prior knowledge beyond the initial URI (bookmark) and set of standardized media types that are appropriate for the intended audience
In other words, if the engine of application state (and hence the API) is not being driven by hypertext, then it cannot be RESTful and cannot be a REST API. Period.
This is also precisely the element that caused me my initial problems. Its one thing to describe the way a resource is related to another resource through hypertext, but much more difficult to describe how you should go about manipulating those relationships… one way to do this is to expose the relationships themselves as resources, but that would require some prior knowledge that the approach was being taken… it’s not implicit.
And if you are performing more than one operation at once? You can’t use location headers… you can return a bunch of links in the body of your response detailing all the resources that were affected, but again you would need some explicit knowledge that those links were present in the body.
Some of us actually don’t see anything wrong with requiring the client have some knowledge of how to interact with the server. An alternative to HATEOAS is Client Server Domain Seperation (CSDS), which defines both client and server as bounded contexts, DDD style.
spc
So that’s why I’ve decided not to worry…
Take ‘Agile’ development as a case in point… most companies take some aspects of agile and use it to their advantage. But the vast majority of us still work to concrete deadlines; anyone doing this is in direct violation of the principles and so cannot be said to be truly agile.
It’s the same with REST… if you don’t make efforts to make your service discoverable then you cannot be said to be making a truly RESTful API. And as it turns out, doing so can sometimes be a bit of a pain. We’d all do a lot better to ignore ‘RESTfulness’ and focus on developing a sensible, easy to use interface.
So while there are all these people debating the finer points about how you should be using verbs or status codes, this is actually more about how to properly use HTTP in the implementation of a REST style architecture rather than what actually defines the architecture as RESTful.
Don’t get me wrong, I’m not going to stop using REST principles to guide good API design, they are sound principles. But from now on, I’ll only be using REST as a wordpress\stackoverflow tag so that people will still be able to find things I write once I stop using the term.
spc
Pete
spc
References:
http://roy.gbiv.com/untangled/2008/rest-apis-must-be-hypertext-driven
http://en.wikipedia.org/wiki/Representational_state_transfer
http://stackoverflow.com/questions/511281/patterns-for-handling-batch-operations-in-rest-web-services?lq=1
http://stackoverflow.com/questions/969585/rest-url-design-multiple-resources-in-one-http-call
http://byterot.blogspot.co.uk/2012/11/client-server-domain-separation-csds-rest.html
Those who know me also know that I was always an advocate of Thread.CurrentPrincipal (or ClaimsPrincipal.Current in .NET 4.5). But I also understand that some people (or frameworks) don’t like ambients and rather deal with instance variables.
To cater for that, I did a small addition to Thinktecture.IdentityModel – when you set the SetPrincipalOnRequestInstance property on AuthenticationConfiguration to true (which it is by default), the resulting ClaimsPrincipal gets added to the properties collection of the HttpRequestMessage instance.
You can then access it from anywhere where you have access to the request either directly or via a new extension method like this:
public ViewClaims Get()
{
var principal = Request.GetClaimsPrincipal();
return ViewClaims.GetAll(principal);
}
The code is on github and soon on nuget.
HTH
Filed under: ASP.NET, IdentityModel, WebAPI
HEAD HTTP verb is defined in RFC 2616 as “identical to GET except that the server MUST NOT return a message-body in the response.” As such you can think of it as a twin brother of GET. There are a … Continue reading →
The post Adding HTTP HEAD support to ASP.NET Web API appeared first on StrathWeb.
[Level T2] I have explained in my Part 5 of the Web API series how the world of HTTP (URI, headers, method, payload) meets the world of code (controller, actions, parameters, etc). This has partly been done in ASP.NET Web API in the media type formatter. And then I talked about the Tower Bridge of MediaTypeFormatter. The problem is these two worlds will eventually come to collide hard - if you ever try to abstract them away.
So what am I on about?
Problem is routing - as I have raised a few times before. And here I will try to explain why - and propose a solution.
The routes basically live in the application setup. You define them outside your controllers and actions - usually inside glolbal.asax or outside while being called on application startup. The idea is that no matter what your routing is, if set up correctly, the values will be populated in your actions - all parameters, and your data. And then your return some data which will be interpreted and serialised in your MediaTypeFormatters.
So what happens if I want to set the location header in the response to a POST method (when an item has been created)? Now I need to provide the parameters to the route to create a virtual link. Now here although I have been abstracted away from the route, I have to know the parameters to pass - this is where things start to get a bit hairy. I have defined a route somewhere else and yet I need to know about it here.
And that by itself is not a big problem. A bigger issue is that ASP.NET does the route matching linearly. So if I happen to define 1000 routes, and my 1000th route gets call often, I can be in trouble as performance can suffer: ASP.NET should always try to match to 999 routes until it hits 1000th.
But why should I have 1000 routes? What is wrong with /api/controller/id? I could end up with handful of routes? OK, here is the catch: routing was designed for a flat routing structure (and originally for ASP.NET MVC) while resource organisation in a Web API has to be hierarchical.
Another issue is hypermedia. Have you tried doing clean and robust hypermedia in Web API using the existing routing? Good luck with that one!
Another problem is the resource in the Web API's really elegant HTTP pipeline (which I love) is URL until it hits the controller dispatcher and then tries to find a matching controller and then action. As such, code part of the resource (controller, action, parameters) cannot programmatically (using attributes, etc) define a strategy to the delegating handlers since we do not yet know which controller or action will respond.
Resource organisation is the responsibility of the application
There were a few issues raised with CacheCow in terms of cache invalidation of related resources. This is actually one of the fundamental scenarios that I designed CacheCow for. Problem is resource organisation is the responsibility of the application as such CacheCow cannot make any assumptions about the organisation of the resource. So the solution is for the application to describe resource organisation and the relationship of resources. This is definitely not easy - as again, world of routing is a disjoint one.
So here is what we need:
- A hierarchical routing with a natural setup rather than arbitrary route definition
- Resources aware of related resources. As such a resource can define its hypermedia for the most part
- Ability for resources to define their strategy when it comes to caching, etc
Once asked by Youssef Moussaoui - a developer in ASP.NET team - on what to improve in ASP.NET Web API, my immediate answer was routing. And not just routing, it is resource organisation.
So I know that ASP.NET will look into this but I probably will have a stab at this. We have defined the project Resourx which will look at this and try to achieve the 3 goals above. Watch the space!
Erst einmal nochmals vielen lieben Dank an alle, die in meine beiden Breakout Sessions und meinen Ganztages-Workshop in Darmstadt gekommen sind!
Da ich ja in meinen beiden Sessions keine "wirklichen" Foliensätze verwendet hatte sondern Demos und Code gezeigt habe, gibt es dieses Mal nix zum Downloaden ;) Beim Workshop war es ja genauso - interaktiv!
Hier aber die versprochenen Links zum Code & den Demos:
Danke und bis bald.
In this blog post I am going to show how you can host ASP.NET Web API services under Gentoo Linux and OS X on top of Mono’s ASP.NET implementation. I will use Nginx and FastCGI to communicate between HTTP server and Mono. A couple of months ago I’ve experimented with running ASP.NET Web API on [...]
In this article I will explain the concepts behind HMAC authentication and will show how to write an example implementation for ASP.NET Web API using message handlers. The project will include both server and client side (using Web API’s HttpClient) bits. HMAC based authentication HMAC (hash-based message authentication code) provides a relatively simple way to authenticate [...]
Protocol Buffers are a super efficient and very flexible way of serializing structured data. Developed at Google, provide the developers lightspeed serialization and deserialization capabilities. There a handful of .NET implementations, the most popular one, called protobuf-net, created by Marc … Continue reading →
The post ASP.NET Web API and Protocol Buffers appeared first on StrathWeb.
There have been quite a few examples circulating on the web on how one would use SignalR together with Web API. It all started after Brad Wilson had a great example on calling SignalR from API controllers at NDC Oslo … Continue reading →
The post SignalR, ActionFilters and ASP.NET Web API appeared first on StrathWeb.
This is great news! If you are going to NDC, you can take my identity & access control training as a pre-conference workshop.
I have divided the content in a “web apps” day and a “services & the cloud” day. This gives you maximum flexibility and you can mix and match with the other great workshops that are offered. Hope to see you there!
http://www.ndcoslo.com/Article/Workshops/claims
Filed under: .NET Security, ASP.NET, Azure, Conferences & Training, IdentityModel, IdentityServer, OAuth, WCF, WebAPI
A friend of mine was recently complaining about how Web API controller centric approach doesn’t really make sense, and that he prefers feature-oriented endpoints. While – in all honesty – I am not sure what he means by that, it … Continue reading →
The post But I don’t want to call Web Api controllers “Controller”! appeared first on StrathWeb.
I was at MSFT Istanbul office yesterday to give a presentation on Microsoft Web Stack for MSPs. It went pretty well I think. It was mostly focused on ASP.NET MVC 4, SignalR and ASP.NET Web API. You can get the slides for the presentation from my Speakerdeck account.
Source code for the sample applications I showed is available on GitHub: https://github.com/tugberkugurlu/MSPKickOff201302MSFTWebStack.
I also showed the Electric Plum's iPhone and iPad simulator and I used it right from VS. I followed through this awesome blog post from Scott Hanselman to set this up: Simulating an iPhone or iPad browser for ASP.NET Mobile Web Development with WebMatrix 2 or Visual Studio 2012. You can do the same. Here are a few other links which were touched upon during the presentation:
General Links
ASP.NET MVC
ASP.NET SignalR
ASP.NET Web API
I would like to thank our MVP Lead Sinem Eylem Arslan and Mustafa Kasap for the opportunity. Also, special thanks go to XOMNI team (Daron Yondem, Gökhan Gülbiz, ilkay ilknur) for helping me to get though those 2 days in Istanbul. I have to say this: they seriously know how to live
Breakfast was amazing 
Today I was struggling trying to work out how I can make use of the oDataMediaTypeFormatter in ASP.Net Web API when you only have a code first model to work with. For the impatient, scroll to the bottom for the quick solution!
The Problem
I’d been reading various articles about oData, Particularly the following:
spc
What I was actually trying to do was to implement partial updates to resources using the PATCH verb, and it all seemed really simple on paper. However when it came down to it, there were several problems:
- You can’t use the [FromData] attribute with a Delta<T> parameter as this throws an exception
- JsonMediaTypeFormatter doesn’t seem to be able to deserialise to Delta<T>, contrary to what the TechBrijj article suggests.
spc
Given the above, I tried to follow the instructions for ‘Doing more oData’ from Alex J’s article hoping to make use of the oDataMediaTypeFormatter. From the article:
// Create the OData formatter and give it the model
ODataMediaTypeFormatter odataFormatter = new ODataMediaTypeFormatter(model);
spc
There were more issues though:
At this point I did what any upstanding developer would do, I swore loudly and went to lunch.
The Solution
Isn’t it annoying when things turn out to be so simple? Poring over the oData package source I found out it’s actually very easy to instantiate the media type formatter. Additionally, it was also a one liner to interpret the code first model (see below)
For additional reasons not explained here, I chose to wrap everything up in another custom MediaTypeFormatter, but anywhere you have a reference to an HttpContent object would work fine too.
public override Task<object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)
{
var serialiser = new JsonSerializer();
var builder = new ODataConventionModelBuilder();
// This line will allow you to interpret all the metadata from your code first model
builder.EntitySet<EfContext>("EfContext");
var model = builder.GetEdmModel();
var odataFormatters = ODataMediaTypeFormatters.Create(model);
var delta = content.ReadAsAsync(type, odataFormatters).Result;
var tcs = new TaskCompletionSource<object>();
tcs.SetResult(delta);
return tcs.Task;
}
spc
So there we go. Hopefully someone will find this useful and not lose a morning because of it! Thanks to @filip_woj for his assistance on this issue.
spc
spc
Pete
In the past with EF if you wanted to update a record you would need to do something like this:
public HttpResponseMessage PutCustomer(Customer customer)
{
using (var context = new ChinookContext())
{
var request = context.Customers.Single(c => c.CustomerId == customer.CustomerId);
// todo this has to have an easier way. Customer.Attach throws an error
request.FirstName = customer.FirstName;
request.LastName = customer.LastName;
request.Address = customer.Address;
request.City = customer.City;
request.PostalCode = customer.PostalCode;
request.State = customer.State;
request.Country = customer.Country;
request.Fax = customer.Fax;
request.Email = customer.Email;
request.Company = customer.Company;
context.SaveChanges();
var response = Request.CreateResponse(HttpStatusCode.Accepted, customer);
response.Headers.Location = new Uri(Request.RequestUri, string.Format("Customer/{0}", customer.CustomerId));
return response;
}
}
As you may notice this can get tedious and rather large as more fields need updating. In Entity Framework 5 we get a wonderful new method ‘SetValues’. With this new method we can change the above code from that to this:
public HttpResponseMessage PutCustomer(Customer customer)
{
using (var context = new ChinookContext())
{
var original = context.Customers.Find(customer.CustomerId);
if (original != null)
{
context.Entry(original).CurrentValues.SetValues(customer);
context.SaveChanges();
}
var response = Request.CreateResponse(HttpStatusCode.Accepted, customer);
response.Headers.Location = new Uri(Request.RequestUri, string.Format("Customer/{0}", customer.CustomerId));
return response;
}
}