# Thursday, February 25, 2016

Part 1 here

c#

https://vimeo.com/154708153 Something C# 7 This Way Comes - Bill Wagner (c#7 wish list is https://github.com/dotnet/roslyn/issues/2136 )
https://vimeo.com/155107766 C# Language Internals - Bart De Smet
https://vimeo.com/155521073 Under the hood of C# 6.0 - Bart De Smet

Practices/Design

https://vimeo.com/156402866 .NET Deployment Strategies (Octopus Deploy)
https://vimeo.com/156264107 Versions are evil - how to do without in your API - Sebastien Lambla
https://vimeo.com/155653145 Distributed Systems principles
https://vimeo.com/155646004 Best Practices for Building a REST-ful API - kevin Dockx

Case studies


https://vimeo.com/156420622 The Times - tools behind a newspaper website (Nodejs, Chef, aws, &, atom-json in S3)
https://vimeo.com/156417164 Azure Portal - tools behind a big SPA
https://vimeo.com/155521095 Polyglot Persistence -Ayende on RavenDb


Javascript


https://vimeo.com/156551919 - ES 2015: The next javascript version today

Security:


Not NDC London, but another NDC event (security day) had several Troy Hunt security talks. Some repetition over the his other talks (e.g. https://vimeo.com/153220272 50 Shades of AppSec), but watch these anyway for a very entertaining and informative introduction to security

https://vimeo.com/154962595 Web Security Essentials by Example
https://vimeo.com/154956509 Both Sides of the Attack
https://vimeo.com/154958732 Lessons from 220 Million Breached Records

posted on Thursday, February 25, 2016 7:54:25 PM (Romance Standard Time, UTC+01:00)  #    Comments [0]
# Monday, February 08, 2016

Not all videos are up yet, a few I may add in a second link dump. I saw most of these live, but several are worth seeing again. See also my slides/github rep link dump

.net
https://vimeo.com/153745433 - The changing state of immutability C# - Jon Skeet
https://vimeo.com/153900560 - What does an "Open Source Microsoft Web Platform look like?" - Scott Hanselman
https://vimeo.com/154034601 - A brief history of ASP.NET: From 1.0 to 5.0 - Damian Edwards and David Fowler

Security
https://vimeo.com/153220272 - Troy Hunt, 50 Shades of AppSec
https://vimeo.com/153908385 - Making Hacking Child's Play - Troy Hunt
https://vimeo.com/154041158 - What's new in Security in ASP.NET 5 and MVC 6 - Dominick Baier
https://vimeo.com/154172925 - Introduction to IdentityServer - Brock Allen (not actually asp 5)
https://vimeo.com/153102690 - .Net Core Authorization Stack - Barry Dorrans

.Net Core (Asp.Net 5 at the time!)
https://vimeo.com/153212604 - .Net Core CLI, Damian Edwards and David Fowler
https://vimeo.com/153749266 - Middleware introduction - Scott Allen

Practices
https://vimeo.com/154049610 - Knowledge Work Culture - Michael Norton
https://vimeo.com/154312751 - Testing with No Harm - Enrico Campidoglio
https://vimeo.com/154301830 - Case Studies in Terrible Testing - Todd Gardner

General
https://vimeo.com/154588594 - Docker - Mark Rendle
https://vimeo.com/154025470 - Mark Rendle, Everything I know about computers, I learned from the movies

posted on Monday, February 08, 2016 8:30:21 PM (Romance Standard Time, UTC+01:00)  #    Comments [0]

Note: this is written in February 2016. If you read this in summer 2016 or later, it's ancient history, just ignore.

There's a lot of buzz about the new Asp.Net Core (previously Asp.Net 5) - blog posts, articles and tweets from enthusiastic developers.

It's nice to see Microsoft being open, and to be able to see the git pull requests. RC1 is out and it has a "Go Live" license- Microsoft says you start using it in production.

Don't use this in production. Don't start your next project with it. You probably don't want to spend too much time playing with it for a few months. It's not ready. It's still changing.

As of start February 2016, the blogs and the official docs still refer to "dnx" and "dnu", which will be as dead as the old "k" stuff from a year ago. Want to try the new "dotnet.exe"? All you can do is a "hello world" console with this: http://dotnet.github.io/getting-started/. The promise is great- this will integrate with the .net native efforts, which for now is vapourware. You can't use it with asp.net core yet, even if you take the unstable RC2 packages- the work hasn't been done (check those pull requests). The best information about it was at the NDC conference (video now available).

There's a lot of changes in MVC APIs between RC1 and the unstable RC2 stuff - and there's more changes coming. There's little or no documentation about it yet outside of the github issues and raw pull requests.

Even the project.json structure will be changing. The tooling packages that got lumped in with runtime references in "dependencies" may be separated into "tools", and there may be other changes. The "dnx451" and "dnxcore50" targets are being renamed (I think to "net" and "netstandardapp"). There's some discussion about this (see the video), but as yet nothing is committed to github, let alone documented.

The visual studio tooling is still incomplete and weak. The only testing framework is XUnit (still via a MS fork I think). We've known for some time that Entity Framework Core (was EF7) won't be fully ready even at release (the big one: no lazy loading; "the lack of these features will make EF6.x a better option"). The ADO GetSchema side (needed for any other ORM) has only just started to get a design.

RC1 is nowhere near being what we'd normally call a "release candidate". RC2 might be feature complete- but there's still a lot of churn going on. RC2 was planned for end February 2016 (with RTM end March), but the dates have recently changed to "TBD".

Unless you're working on a popular nuget library, I don't think it's worth investing much time playing with or learning Asp.Net Core just yet. After we get a stable RC2 we can play with the new toys. For "real work", ignore any more "Go Live" licenses - wait until the RTM. I suspect it may be sensible to wait until v1.1 until shifting fully into the new framework.

The multi-targeting (windows/max/linux) is a nice new feature, but no-one is going to ditch all their windows servers. Some of us remember similar things being said about Silverlight, and a few people jumped for that too. My inclination is to dump the restricted "dot net core" experience and run it on full .net 4.6 framework so we can use EF 6, existing libraries and ADO providers, but still benefit from xproj and the new asp stack. Fortunately that's a nice "transitional" story.

Don't get me wrong - this is a positive direction for .net, with lots of very welcome changes. But it's a huge change which is still ongoing. The new open source Microsoft, coupled with some clumsy marketing, means we're looking at something not fully cooked. If you're enthusiastic about the new changes, save yourself some frustration and wait a few more months.

posted on Monday, February 08, 2016 6:38:21 PM (Romance Standard Time, UTC+01:00)  #    Comments [0]
# Tuesday, January 26, 2016

VS 2015 Update 1 had big problems on one of my machines.

This was helpful: How to restore Visual Studio 2015 after the Update 1 (dependency dance)

A MS engineering guy has a full solution (basically a new devenv.config): here

posted on Tuesday, January 26, 2016 10:13:31 AM (Romance Standard Time, UTC+01:00)  #    Comments [0]
# Tuesday, January 19, 2016

A link dump (slides and source) from NDC London, January 2016

ASP.Net 5

https://github.com/damianedwards/aspnet5-workshop
Workshop by David Fowler, Damian Edwards. See docs: https://docs.asp.net/en/latest/

https://github.com/blowdart/AspNetAuthorizationWorkshop
Asp.Net 5 authorization workshop by Barry Dorrans

https://docs.asp.net/projects/mvc/en/latest/views/tag-helpers/intro.html
Asp.net 5 Razor taghelpers
Source code: https://github.com/aspnet/Mvc/tree/dev/src/Microsoft.AspNet.Mvc.TagHelpers

https://onedrive.live.com/view.aspx?resid=600FD0DBAAE1E40F!368067
Asp.Net 5 Security - slides, by Barry Dorrans

https://speakerdeck.com/leastprivilege/whats-new-in-asp-dot-net-5-and-mvc-6-security
Dominick Baier on Asp 5/MVC6 security

http://1drv.ms/1PLU4DV
Brock Allen introduction to Identity Server

Other .net

https://github.com/jskeet/DemoCode/tree/master/Immutability
Jon Skeet on immutability in .net

https://github.com/iancooper/Presentations
Ian Cooper on service discovery

https://vimeo.com/144824826 - Video of Jimmy Bogard's "Full Stack REST" talk, from another conference (Nov 2015)

Other

https://speakerdeck.com/tastapod/business-mapping - Dan North on Business Mapping
Agile doesn't scale, so this maps people skills (and aspirations) to business KPIs

http://www.slideshare.net/Kevlin/solid-deconstruction - Kelvin Henney on SOLID (yes, open/closed is confusing, but it's really just don't publish public API prematurely)

http://bodil.lol/generators/#0 - Bodil Stokke on Javascript generators

posted on Tuesday, January 19, 2016 1:21:31 PM (Romance Standard Time, UTC+01:00)  #    Comments [0]
# Monday, January 11, 2016

I'm at the NDC London conference, doing the Asp.net 5 introduction by Microsoft's Damian Edwards and David Fowler, who are the guys leading the team writing it. I've downloaded a couple of previous milestones, but it was clear the API was changing radically, so I didn't follow too closely. Now we're on release candidate 1, with 2 due in Feb and the final release at the end of March 2016.

Workshop files are here: https://github.com/damianedwards/aspnet5-workshop

Asp.Net 5 docs are here: https://docs.asp.net/en/latest/

My first impressions from the first day:

It's still changing a lot- we're working off the CI builds nuget feeds, so it's RC1+update 1+lots of changes. RC2 has some big changes still to do, including renaming stuff. It's still too early to start playing in depth, let alone thinking about doing real work in it. There's a lot that isn't there at all. Surprisingly, no MsTest, you have to use XUnit.

But. it's not long until it will be out. And it has some major changes, as big a shift as MVC was from web forms. Developers will have to spend a lot of time learning a new framework.

Asp MVC and WebApi are pretty stable, simple and powerful, but System.Web is a huge beast with legacy going back to ASP classic compatibility. Asp 5 doesn't use System.Web, although some concepts are copied over (there's still something called HttpContext, it just has a lot less in it). So it's faster, more consistent, more portable - for cloud, and cross-platform.

The main changes (from the first day):

There's a new project structure. The website is built into a wwwroot folder - the old VS publish is redundant. On the solution level, there's a global.json (the project list), although .sln still exists. On the project level, there's a project.json and (not seen in VS) an .xproj file that between them replace the .csproj. You can also add other json files- hosting, appsettings.

It's based on nuget packages, so it's easily deployed side-by-side. This downside is the packages are very granular and manual. Visual Studio auto-suggests from nuget feeds while entering the dependencies in project.json. To make it easier, there will be standard packages with simple names that bring in a bunch of other packages (but they aren't there yet). On the MVC level, the Microsoft.AspNet.Mvc package is probably the one you want, unless you want to individually reference Microsoft.AspNet.Mvc.Core and half a dozen other packages for the precise combination of features you're using. Still, we've swapped dll hell for version hell when packages start updating independently.

There is a plan for zero day patching from Windows Update (presumably this is where the GAC comes back). The proposal is that packages are supported for 12 months- so when an update comes out, you have a year to update. In most organizations, applications get released and the team disperses, and no updates are ever done. With Asp.net 5, that could be a problem.

It's bootstrapped just like a classic console- with a public static void Main(string[] args) method. (This was hidden away in IIS before). IIS will now use the static void Main, and more things get done in asp and it's Kestrel server (Kestrel now sits behind IIS, as well as being able to run standalone. HttpListener sounds like it's gone).

Dependency Injection is built in and pervasive. It's used when configuring your asp.net 5 environment, in preference to base classes or interfaces.  In controllers it's not too bad, but in your startup class and middleware you don't have any way to discover what you can do. You have a Configure method which is magically called with the arguments you specify- say, an IApplicationBuilder or an ILoggerFactory. We're going to be relying on the documentation website (and I hope the docs cover updates and and are versioned.)

posted on Monday, January 11, 2016 10:33:05 PM (Romance Standard Time, UTC+01:00)  #    Comments [0]
# Tuesday, August 04, 2015
One of my 4 machines immediately offered to upgrade to Windows 10. The rest are just sitting there, probably because Microsoft is stacking up upgrades over weeks or months.

It's simple to force an update.

Use the Windows 10 media creation tool: http://www.microsoft.com/en-us/software-download/windows10
Download it (it's 18Meg), and run it. Select "Upgrade this PC now". It downloads the multiple Gigs of Win10, then installs.

Privacy settings


Near the end of installation, there will be a screen "Get Going Fast" with the default button "Use Express Settings". Instead click the small link "Customise settings" (it's "Customize" in US versions, "Customise" in UK).

On "Customise Settings" first page, turn off "use page prediction" (2nd option), and at least the first 2 "Connectivity" options below that (automatically connect to open hotspots, networks shared by contacts).
"Smartscreen" and "Send error and diagnostic information" are acceptable.


On "Customise Settings" second page ("Personalisation" and "Location"), turn off all of them.

If you use a local account, it will show "Make it yours" which will convert you to a Microsoft (hotmail/outlook.com) account. Click the small link at the bottom "Skip this step".

Edge is the default browser

Settings > System > Default apps
You can change the Browser, Music, Photo and other defaults here.

Chrome and Firefox will both complain they are no longer default browser- Windows 10 will open the default apps page for you.

Settings

Settings is the new control panel. If you followed the defaults, you can fix them here

If you accidentally switched to a Microsoft account, Accounts > Your account > "Sign in with a local account instead".

In Privacy, fix the options under "General", "Location", and "Speech, inking and typing".

In Network & Internet > Wi-Fi > Manage Wi-Fi Settings > "Wi-Fi Sense" turn off both options (Connect to open hotspots, connect to networks shared by contacts).

In Update & Security > Windows Update > Advanced Options > Choose how updates are delivered > make sure you don't use "PCs on my local network, and PCs on the internet" (the "PCs on my local network" should be okay on a home network).


posted on Tuesday, August 04, 2015 9:17:38 AM (Romance Daylight Time, UTC+02:00)  #    Comments [0]
# Sunday, March 29, 2015

I finally moved my project "database schema reader" from Codeplex to Github.

Github import was simple and quick. I didn't import the historical issues (the project went on Codeplex in 2010, and it was a couple of years old then). I just added an "upstream" remote so I can still push to Codeplex and keep it updated. 

Codeplex comments and discussions are disabled at the moment; "we're anticipating that this functionality will be re-enabled early next week"! The codeplex blog hasn't been updated in 2 years, and the "codeplex" discussions are full of spam (fortunately I've never had spam in the project discussions). There are many third-party services that integrate with Github, but nothing links into Codeplex.

The main advantage of the move to Github was hooking into Appveyor for CI builds. It took a few builds to experiment with things. I'm using database integration tests with SqlServer, SQLite, PostgreSql and MySql. Now these are working, the tests are more portable - I can easily recreate the databases. The packaging of the builds (dlls into a zip, plus a nuget packages) was also easy, and can create releases within Github. The appveyor.yml file isn't the easiest way to configure builds, and I soon figured out it's better to use the website UI.

Overall, much better than TFS (ugh!) and TeamCity builds. I played a little with Travis CI (building in Mono), but for now it's not worth pursuing.

I tried Coverity for code analysis, which flagged a few (minor) things, but didn't seem to add a lot more than FxCop.

I looked at Coveralls,  a code coverage service. Code coverage is 77%, incidentally, which I think is quite good for something that includes code to support Oracle, DB2, Ingres, 3 different Sybase databases, VistaDb, Firebird and Intersystems Cache (for now, these must continue to be tested on my machine only.). I don't believe code coverage is very useful, so for now I won't include this into the Appveyor build.

I'm very impressed, and very happy with Appveyor.

posted on Sunday, March 29, 2015 5:41:03 PM (Romance Daylight Time, UTC+02:00)  #    Comments [0]
# Wednesday, July 23, 2014

System.Version

The mscorlib System.Version class accepts 2, 3 or 4 integers to represent a version.
var v = new Version(2014010110, 7383783, 38989899, 893839893);
Console.WriteLine(v.ToString()); //shows 2014010110.7383783.38989899.893839893

The values are Major.Minor[.Build[.Revision]]

As we'll see shortly, actual assembly versions are much more limited!

SemVer

Semantic versioning can be mapped into the .net scheme.

In SemVer, the scheme is Major.Minor.Patch.

  • Major is breaking changes
  • Minor is backwards compatible changes including additions
  • Patch is backwards compatible bug fixes.

So .net Build is equivalent to semver Patch, and revision, which is optional anyway, is disregarded. (The original .net convention was that build used the same source with different symbols).

Version attributes

The version attributes are normally in Properties/AssemblyInfo.cs (but could be anywhere).
You can also access AssemblyVersion and AssemblyFileVersion via the project properties - application - [Assembly Information...] button.

There are 3:

//CLR uses this as the version 
[assembly: AssemblyVersion("1.0.0.0")]

//Not used by CLR, often the specific build
[assembly: AssemblyFileVersion("1.0.0.0")]

//If not present, == AssemblyVersion. 
[assembly: AssemblyInformationalVersion("v1.0 RC")]

AssemblyInformationalVersion used to error if it wasn't a System.Version (all ints). Since Visual Studio 2010, you can put in free-form strings, which is useful for tags like "RC".

To access these via code:

var executingAssembly = Assembly.GetExecutingAssembly();
var ver = executingAssembly.GetName().Version; //AssemblyVersion
var fv = System.Diagnostics.FileVersionInfo.GetVersionInfo(executingAssembly.Location);
Console.WriteLine(ver);
Console.WriteLine(fv.FileVersion); //AssemblyFileVersion
Console.WriteLine(fv.ProductVersion); //AssemblyInformationalVersion

There is also a fv.ProductMajorPart and fv.ProductMinorPart but these aren't populated if the AssemblyInformationalVersion can't be parsed into a System.Version.

The values- major, minor, build, revision - are ints, up to 2,147,483,647. But there's a big gotcha. For operating system reasons, the compiler limits values to 65,534, int16.

For AssemblyVersion, you get a CSC Error: "Error emitting 'System.Reflection.AssemblyVersionAttribute' attribute -- 'The version specified '65536.65535.65535.65535' is invalid'"

For AssemblyFileVersion, you get a CSC Warning    "Assembly generation -- The version '65536.65535.65535.65535' specified for the 'file version' is not in the normal 'major.minor.build.revision' format". It will build, at least.

Versioning Strategy

  • For all version types major and minor parts should be manually set.
  • To simplify CLR versioning, we don't need to increment the AssemblyVersion except once, manually, at final release. For AssemblyVersion, just set major and minor (and perhaps build for semver). Normally build and revision will always be 0.0.  We don't want any version numbers changing during developer builds, or even continuous integration builds unless they are automatically deployed to test.
  • When a dll is published/deployed, we should increment the AssemblyFileVersion.
  • We should be able to trace back to the build.

There are several candidates for traceable build and revision numbers, but none are "semver" (both build and revision are significant).

  • Increment by date, as in wildcards (below): build is days since a specific date, revision is seconds since midnight. But there is no obvious connection between the dll and the build on the build-server.
  • Date, except we can't fit "year-month-day-hour-minute-second" into an int16. You could overflow it: build is mmdd, revision is hhmm.
  • Build name. TFS uses a buildDef_yyyymmdd.n format for the build name.
  • Changeset number if numeric, and it is less than 65535.

Both build name and changeset number might be better set in AssemblyInformationalVersion.

Wildcards

For AssemblyVersion only, you can use wildcards for build and revision.

If you use it for file version, you get a warning:
CSC : warning CS1607: Assembly generation -- The version '1.2.0.*' specified for the 'file version' is not in the normal 'major.minor.build.revision' format

  • AssemblyVersion build = number of days since 01/01/2000.
  • AssemblyVersion revision = number of seconds since midnight.

If you build twice without changing, the revision goes up. If you build the next day without changes, the build goes up.

Wildcards are pretty useless.

Build Tasks

Build tasks run after source control get-latest, before compilation. They find the AssemblyInfo.cs files, flip the readonly flag, and find and replace the AssemblyFileVersion, then compile. The changed AssemblyInfo file should not be checked in. The process is not run in developer builds, only in "publish" builds.

MSBuild Extension Pack is a set of msbuild tasks, which is also available as a Nuget package (MSBuild.Extension.Pack). One task, MSBuild.ExtensionPack.VisualStudio.TfsVersion, edits the AssemblyFileVersion given a date or tfs-format build name.

Another project, Community TFS Build Extensions, made by some of the same people, hooks up into TFS 2012/2013 xaml workflows and includes a TfsVersion build activity.

posted on Wednesday, July 23, 2014 8:22:40 PM (Romance Daylight Time, UTC+02:00)  #    Comments [0]
# Friday, March 07, 2014

Forms Authentication is ASP.net is simple but the FormsIdentity and GenericPrincipal/RolePrincipal are a little too simple. All we get are IIdentity.Name and IPrincipal.IsInRole(x)

Most real applications need a bit more, like the user's full name or email address, or domain-specific data.

Custom Principal

The usual way to do this was to create a custom principal, the UserData field in the forms authentication cookie, and the asp.net pipeline event "PostAuthenticateRequest".

Here's our custom principal:

    public class UserPrincipal : GenericPrincipal
    {
        public UserPrincipal(IIdentity identity, string[] roles)
            : base(identity, roles)
        {
        }

        public string Email { get; set; }
    }

Here's the login action. Instead of the normal FormsAuthentication.SetAuthCookie, we do it manually (see below):

        [AllowAnonymous]
        [HttpPost]
        public ActionResult Login(LoginModel model, string returnUrl)
        {
            if (ModelState.IsValid) //Required, string length etc
            {
                var userStore = new UserRepository();
                var user = userStore.FindUser(model.UserName, model.Password);
                if (user != null)
                {
                    //FormsAuthentication.SetAuthCookie(user.Name, false);
                    SetAuthCookie(user);
                    //redirect to returnUrl
                    if (!string.IsNullOrEmpty(returnUrl) &&
                        Url.IsLocalUrl(returnUrl) &&
                        !returnUrl.Equals("/Error/NotFound", StringComparison.OrdinalIgnoreCase))
                    {
                        return Redirect(returnUrl);
                    }
                    return Redirect("~/");
                }
                ModelState.AddModelError("UserName", "User or password not found");
            }
            return View(model);
        }

And here's where we set the authentication cookie, here putting our user object as Json into the userData field of the cookie.

        private void SetAuthCookie(User user)
        {
            var userData = JsonConvert.SerializeObject(user);
            var authTicket = new FormsAuthenticationTicket(
                  1, //version
                  user.Name,
                  DateTime.Now, //issue date
                  DateTime.Now.AddMinutes(30), //expiration
                  false,  //isPersistent
                  userData,
                  FormsAuthentication.FormsCookiePath); //cookie path
            var cookie = new HttpCookie(FormsAuthentication.FormsCookieName,
                                        FormsAuthentication.Encrypt(authTicket));
            Response.Cookies.Add(cookie);
        }

Finally, we hook up the PostAuthenticationRequest event. Normal forms authentication will have recognised the authentication cookie and created a GenericPrincipal and FormsIdentity. We unpack the userData field, and create our custom principal.

        protected void Application_PostAuthenticateRequest(Object sender, EventArgs e)
        {
            var context = HttpContext.Current;
            if (context.User == null || !context.User.Identity.IsAuthenticated)
            {
                return;
            }

            var formsIdentity = context.User.Identity as FormsIdentity;
            if (formsIdentity == null)
            {
                return;
            }

            var id = formsIdentity;
            var ticket = id.Ticket;
            var userData = ticket.UserData; // Get the stored user-data, in this case, our roles
            var user = JsonConvert.DeserializeObject<User>(userData);
            var customPrincipal = new UserPrincipal(formsIdentity, user.RolesList.ToArray());
            customPrincipal.Email = user.Email;
            Thread.CurrentPrincipal = Context.User = customPrincipal;
        }

The userdata is encrypted and safe from tampering, but it can make the cookie rather large.

.Net 4.5 making claims

Now in ASP.net 4.5, we have Windows Identity Foundation (WIF, pronounced "dub-i-f") and claims principals and identities. Usually this is discussed with "federation" and single-sign-on identity providers, but actually claims can be useful in "traditional" stand-alone websites like we've just discussed.

ClaimsPrincipals and Identities have a list of Claims. This can be just a property bag with names and values, but there are many standard claim names, defined by OASIS, in the ClaimTypes enum. In addition to ClaimTypes.Name and ClaimTypes.Role, there are Email, GivenName, Surname, DateOfBirth, MobilePhone and so on. These standard defined types mean libraries can discover these claims without defining common interfaces or contracts. But it is also extensible with application specific claims. The old fixed custom principal is starting to look old-fashioned.

The WIF session authentication module can take over from forms authentication, storing the claims in cookies. You don't need to use the federation aspects. The module handles cookies a little better than forms authentication- if it gets too large, it's chunked over several cookies. There is also a ReferenceMode = true, which keeps the claims data in server side memory and only sends a simple key in the cookie (it's obviously not webfarm safe).

FormsAuthentication with Claims

First, the configuration. You'll need to define the configuration sections. We are still using forms authentication, so keep the authentication mode=Forms. Add the WIF session authentication module, which will handle the cookie.

<configuration> 
  
  <configSections>
    <section name="system.identityModel"
             type="System.IdentityModel.Configuration.SystemIdentityModelSection,
             System.IdentityModel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"
/>
    <section name="system.identityModel.services"
             type="System.IdentityModel.Services.Configuration.SystemIdentityModelServicesSection,
             System.IdentityModel.Services, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"
/>
  </configSections>
  <system.web>
    <compilation debug="true" targetFramework="4.5" />
    <httpRuntime targetFramework="4.5" />
    <authentication mode="Forms">
      <forms loginUrl="~/Account/Login" />
    </authentication>
  </system.web>
  <system.webServer>
    <modules>
      <add name="SessionAuthenticationModule"
           type="System.IdentityModel.Services.SessionAuthenticationModule,
           System.IdentityModel.Services, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"

           preCondition="managedHandler" />
    </modules>
  </system.webServer>

If you aren't using SSL, you need to add the following (note the configSection defined above):

  <system.identityModel.services>
    <federationConfiguration>
      <cookieHandler requireSsl="false" />
    </federationConfiguration>
  </system.identityModel.services>

In the login page, set the user properties into claims.

        private void SetClaimsCookie(User user)
        {
            var claims = new List<Claim>();
            claims.Add(new Claim(ClaimTypes.Name, user.Name));
            claims.Add(new Claim(ClaimTypes.Email, user.Email));
            foreach (var role in user.RolesList)
            {
                claims.Add(new Claim(ClaimTypes.Role, role));
            }
            //needs an authentication issuer otherwise not authenticated
            var claimsIdentity = new ClaimsIdentity(claims, "Forms");
            var claimsPrincipal = new ClaimsPrincipal(claimsIdentity);
            var sessionAuthenticationModule = FederatedAuthentication.SessionAuthenticationModule;
            var token = new SessionSecurityToken(claimsPrincipal);
            sessionAuthenticationModule.WriteSessionTokenToCookie(token);
        }

You don't need the PostAuthenticateRequest event- the WIF session module is doing that bit.

And that's it! [Authorize("Admin")] attributes work as normal. Retrieving the claims is simple.

var cp = (ClaimsPrincipal)User;
var email = cp.FindFirst(ClaimTypes.Email);

Logging out looks like this:

        public ActionResult SignOut()
        {
            var sessionAuthenticationModule = FederatedAuthentication.SessionAuthenticationModule;
            sessionAuthenticationModule.CookieHandler.Delete();

            //FormsAuthentication.SignOut();
            return Redirect("~/");
        }
posted on Friday, March 07, 2014 8:59:14 PM (Romance Standard Time, UTC+01:00)  #    Comments [0]