Asp.Net Identity Invalid Token for password reset or email confirmation

I’m an avid user on StackOverflow in questions about Asp.Net Identity and I attempt to answer most of the interesting questions. And the same question comes up quite often: users try to confirm their email via a confiramtion link or reset their password via reset link and in both cases get “Invalid Token” error.

There are a few possible solutions to this problem.

Continue reading

Strongly-Typed ID References to Razor-Generated Fields

The title is quite vague, but this is the best I can call this post. Bear with me, I’ll explain what I mean.

While working with Asp.Net MVC, in Razor views I use Html helpers a lot. My view end up looking like this:

@Html.TextBoxFor(m => m.Title)
@Html.TextAreaFor(m => m.Description)

And later if I write JavaScript and need to reference one of the input fields, I usually do this:

var title = document.getElementById("Title");
var description = document.getElementById("Description");

or if you use jQuery you go like this:

var title = $("#Title");
var description = $("#Description");

This is fine and works. Until you start renaming field names in your model. And then you need to track down where you hard-coded the input id. And many times these references slip away (they do from me!) and remain unchanged.

Would it not be great if these changed could be picked up automatically? or even better, do some sort of strongly-typed reference to the element if it is used in JavaScript?

Just use @Html.IdFor(m => m.Name)

And your JS code would look like this:

var title = document.getElementById("@Html.IdFor(m => m.Title)");
var description = $("#@Html.IdFor(m => m.Description)");

Below I’ve re-invented the wheel. [Facepalm]

So I trolled through MVC source code and figured out how it generates id’s for elements and here are my findings:

using System;
using System.Linq.Expressions;
using System.Web.Mvc;

public static class HtmlHelpers
{
    public static String ElementId<T, TResult>(this HtmlHelper<T> htmlHelper, Expression<Func<T, TResult>> selector)
    {
        var text = System.Web.Mvc.ExpressionHelper.GetExpressionText(selector);
        var fullName = htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(text);
        var id = TagBuilder.CreateSanitizedId(fullName);

        return id;
    }
}

As you can see, I have not made any custom code, all components are from MVC and are applied in the same order as MVC does when it generates id for elements when you call for @Html.EditorFor(). So this guarantees the provided id from this function will match the id in your form.

In the view you use it like this:

@Html.ElementId(m => m.Title)

And your JS code would look like this:

var title = document.getElementById("@Html.ElementId(m => m.Title)");
var description = document.getElementById("@Html.ElementId(m => m.Description)");

A bit of mouthful, but gives you the safety net of strong types. I have not actually used it widely, so not sure how it’ll work out in the longer run.

Can’t find the valid AspnetCompilerPath

A note to myself, next time I try to do view compilation in msbulid and see exception

Can’t find the valid AspnetCompilerPath

I should either install VS2013 on my build server. Or choose a different version of msbuild.exe:
C:\Program Files (x86)\MSBuild\12.0\Bin\msbuild.exe.

The problem is caused by version mis-match. New msbuild is part of Visual Studio 2013 and not part of .Net framework itself. And by default your PATH variable points to .Net folders where older msbuild is found. So you in your scripts you need to explicitly specify what msbuild you need to use.

Sending Emails in Asp.Net Identity using Dependency Injection, Sendgrid and debugging it with Mailtrap.io

Part 1: AspNet Identity and IoC Container Registration

Sounds like I’m making a series of articles about ASP.Net Identity and how to use it with Depenency Injection. Part 1 have seen a lot of hits from Google in just a few days. I suppose it is worth extending the tutorial.

Building up on Part 1 where I wired all Identity components to be injected by Unity container, now I’m going to add emailing service for email confirmation and password reset.

My plan is to use SendGrid as a email service and email debugging service Mailtrap.IO as a hosted fake SMTP server.

Continue reading

Rename Authentication Cookie Name of Asp.Net Identity

When I’d like to find out about technologies used on the site, I look on HTTP header, then on cookies. Usually combination of these can give me a pretty detailed information about underlying technology used. Cookie names are very bad for that – search for any cookie name and you’ll get a lot of information about the technology.

To hide yourself, you can rename cookies from standard to something random. In Asp.Net Identity you can do that via CookieName property on CookieAuthenticationOptions class in configuration:

app.UseCookieAuthentication(new CookieAuthenticationOptions
{
    AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
    LoginPath = new PathString("/Account/Login"),
    Provider = new CookieAuthenticationProvider
    {
        OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<UserManager, ApplicationUser>(
            validateInterval: TimeSpan.FromMinutes(0),
            regenerateIdentity: (manager, user) => manager.GenerateUserIdentityAsync(user))
    },
    CookieName = "jumpingjacks",
});

See the jumpingjacks string? that will be the cookie name when users login. You can find the full project source code in my Github repository

Deploy Web Solution on Build

There are plenty of articles about how to deploy a solution to Azure Web-Sites. I’ll just leave this here for myself:

msbuild .\SolutionName.sln /p:DeployOnBuild=true /p:PublishProfile=ProfileName /p:Password=passwordForAzurePublishing /p:AllowUntrustedCertificate=true

This builds solution according to previously configured Publish Profile.

  • Good thing that all the configurations parameters are stored within Profile, where you can tell the thing to pre-compile the views and publish to folder where you need it.

  • Bad thing – you can’t specify where deploy to, as that is specified in the Publishing Profile. But you can configure different profiles to publish to testing and to production.

  • Another very bad thing – you can’t provide it with a pre-built web-deploy package, this builds the solution again every time you execute it. And this breaks the rule of Continuous Integration and Deployment: “Build once, deploy everywhere”. Suppose you have a Build Server with process that looks like this: Build => Run Unit Tests => Run Integration Tests => Deploy to Testing => Deploy to Production. And if for deployment you use the line I quoted above, you will be compiling your sources 3 times: first time to run tests, then every time to deploy. In some sense this is OK, because you are building from the same sources, but this is a waste of time. If I build my application with pre-compiled views, this can take a while. One of the applications I work on has 800 views and compilation of all these views takes about 7 minutes. If I compile them once, and re-use that, I don’t need to wait another 7 minutes for deployment to production. Well, OK, OK! Msbuild has got some clever stuff in it and probably will not re-compile all the views if nothing have changed and second time it’ll take less time to do compilation, but that still bothers me. Hopefully new Asp vNext will do something to make my life easier in this sense.

ASP.NET Identity – User Lockout

I’ve spent a few hours trying to figure out why my code does not work, and I have not found any explanations to the issue, so might just write it down here.

In ASP.NET Identity there is a concept for user locking out. You can specify how many attempts user can gets before the lock-out kicks in and for how long the lockout is enabled. This is a widely known, from all the articles online. But what these articles don’t say is that users can be opted-in and opted-out from this process.

If you look on IdentityUser class, there are 2 fields that relate to lockout: LockoutEnabled and LockoutEndDateUtc. My first reaction was that LockoutEnabled says that user is locked-out and LockoutEndDateUtc is time when the lockout expires.

Turned out that I was wrong. LockoutEnabled is a flag saying that user can (or can not) be locked in principle. I.e. opt-in flag for locking. So if we have an admin user who we don’t want to lockout ever, we’ll set this flag to be false. And for the rest of user-base this should be set to true.

To check if user is locked-out use UserManager.IsLockedOutAsync(user.Id). Function UserManager.GetLockoutEnabledAsync() checks if user is opted in for lock-out, it does not check if user is actually locked-out.

And fields on IdentityUser – don’t use them to detect is user is locked out, they are lies! Use UserManager functions to detect user state.

Hope this will save some people a head-banging, cause that caused me some stress!

Update 27 Aug 2014

To enable locking-out UserManager should have these flags set:

//lockout users for 10 minutes
UserManager.DefaultAccountLockoutTimeSpan = TimeSpan.FromMinutes(10);

// takes 6 incorrect attempts to lockout 
this.MaxFailedAccessAttemptsBeforeLockout = 6;

// when new user is created, they will be "lockable". 
this.UserLockoutEnabledByDefault = true;

To lockout user you can do this:

user.LockoutEnabled = true;
user.LockoutEndDateUtc = DateTime.UtcNow.AddMinutes(42);
await userManager.UpdateAsync(user);

This will set the user to be locked out for 42 minutes from now. However, this is not recommended way to lock-out user, this is what the framework does in the background. There are ways users can lock themselves out.

If you are updated to AspNet Identity 2.1 (which has been released recently). You should use SignInManager:

var signInManager = new SignInManager(userManager, authenticationManager);
var signInStatus = await signInManager.PasswordSignInAsync(username, password, isPersistent, shouldLockout);

If shouldLockout is true, user is getting locked out after a number of failed attempts to login.

PasswordSignInAsync method does the following steps:

  • checks if user with given username exists;
  • then checks if this user is not locked out;
  • if password is correct, redirects logic to 2FA (if it is enabled);
  • if shouldLockout is true, then on incorrect password increases number of failed log-ins on user record.

If you have not updated and still using Identity v2.0 do the following. On every failed attempt to login, call the following

await userManager.AccessFailedAsync(user.Id); 

IdentityUser class have property AccessFailedCount. The method above increases count on this property. If count is greater than UserManager.MaxFailedAccessAttemptsBeforeLockout, then user is getting locked out: user.LockoutEndDateUtc is set to a date in the future and resets AccessFailedCount to zero.

When user is signed-in successfully, you need to reset AccessFailedCount to zero. Do it by calling:

await userManager.ResetAccessFailedCountAsync(user.Id);

User impersonation with ASP.Net Identity 2

UPD July 2017: If you are looking to do User Impersonation in Asp.Net Core, read this article: http://tech.trailmax.info/2017/07/user-impersonation-in-asp-net-core/

Recently I’ve migrated my project to ASP.NET Identity. One of the features I had in the project is “Impersonation”. Administrators could impersonate any other user in the system. This is a strange requirement, but business behind the project wanted it.

This is the old impersonation way:

  1. When admin wanted impersonation, system would serialise information about admin account (mostly username).
  2. Find account for impersonated user
  3. Create a new authentication cookie for impersonated user
  4. As data add serialised information about admin account to the cookie
  5. Set the cookie
  6. Redirect admin to client page.
  7. Bingo, admin logged in as a client user.

To de-impersonate repeate the process in reverse. Get data about admin from cookie data (if it is present), delete cookie for client-user, login admin user again. Bingo, admin is logged in as admin again.

Here is the article how the old way is implemented

This exact code did not work with Identity framework. I tried finding the solution online, but nothing was available. My question on Stackoverslow immediately got 4 up-votes, but no answers. So people are interested in doing it, but nobody published any material on this. So here I am -)

Continue reading

C# Homoiconicity in practice or Rendering Identical Résumé in Word and PDF From a Single Serializable Domain Structure.

TL;DR: Watch video by Mark Seemann about Homoiconicity in C#. Appreciate his sample implementation. Go see my simplistic implementation that is actually is used in production.

Homoiconicity is ability of code to be manipulated as data and data presenting code. I’m not sure I completely understand the concept, so I’m not going to try to explain it here. Honestly, just watch the video by Mark Seemann about Faking Homoiconicity in C#. After the video all what I’m talking here will make much more sense!

In his talk, Mark describes an application that generated loan proposal document that had complex logic and had to output document to a printer. For my project I had to generate a résumé into both Word and PDF formats. I inherited the project, so PDF generation was already done. I only needed to create Word document. Easy said!

Problem was that PDF generation was tightly coupled with PDF rendering engine and was in a bit of a “state”. When this part of project was written the developers did not know any better way to do it. And I did not imagine this can be done in a neater way. Until I saw Mark’s talk.

Continue reading