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

Functional Injection Discussion

I’m reading a lot of blogs about development and .Net. One of the blogs I read is from Jimmy Bogard and one of the recent posts there is about guidelines for using Dependency Injection container.

I got involved in comments and one of the commenters was suggesting using Func<IFoo> as injection instead of injecting the instance for IFoo. And reasons for that were:

  1. The “captive dependency” problem… objects with more constrained lifetime being held by objects with longer->lived lifetime.

  2. The (wasteful) big-bang object graph problem… when an MVC action only requires 1 dependency, but the dependency graph for all dependencies within the controller need to be resolved.

  3. The occasional property injection… when its 2am and I don’t feel like fixing a circular dependency issue (don’t hate).

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

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

Open XML SDK Tool to analyse documents and generated C# code

Yesterday I discovered Package Explorer for opening up OpenXML documents, validating and editing. Today I have found OpenXml SDK Tool.

SDK Tool is a great software from Microsoft for every developer working with OpenXml. SDK Tool is similar to Package Explorer, but you don’t have edit functionality. And validation messages are not as good. But you get an instant access to documentation about any possible element you can imagine.
And the killer function is CODE GENERATION! It generates C# code for any element that is available on the page.

You can create a Word Document, open it up in SDK Tool and it will produce you a full C# listing to create exactly the same document from your code! This is just fantastic! Using this tool today I was discovering how things done in a simple way: add page numbers to an empty Word-doc, open it up in SDK Tool, find the part about page numbers (probably this was the hardest part), copy the generated code, slightly refactor and I had page numbers in my generated documents. All it took about 15 minutes and I did not use Google or any other documentation.

Anyway, download SDK Tool from here: http://www.microsoft.com/en-gb/download/details.aspx?id=30425. Select only SDK Tool to download, you won’t need anything else available on the page.

Once installed find Open XML SDK Productivity Tool in your start menu and open a Word document.

You can select any element of the document and see documentation to that, with all available child node types

Documentation

You can run validation of any element in the document:

Validation

And the promised killer feature – Generated code:

See_Generated_Code

Another quite useful function is to compare the documents. Yesterday I had to do that to find out how a particular feature is implemented. Now, when you have a generated code, this may be not so useful, but you can compare 2 Word documents and it’ll show you the differences in containing XML.

Validating of OpenXml generated documents or The file cannot be opened because there are problems with contents.

Stackoverflow is useful until you have a quite specific question and you have used Google before asking a question. My last 11 questions were left with no answers for one or another reason.

Today was not an exception. My question about debugging process during OpenXml development was left unnoticed. So I had to figure out for myself! Sigh!

UPDATE: I have discovered Open XML SDK Tool that adds a lot of features to this game

Anyway, I digress. My current task involves generating a MS Word document from C#. For that I’m using OpenXml library available in .Net. This is my first time touching OpenXml and maybe I’m talking about basic stuff, but this was not easily googleable.

Many times after writing a Word file, I try to open it and see this message:

The file .docx cannot be opened because there are problems with the contents. Details: Unspecified error

The file .docx cannot be opened because there are problems with the contents. Details: Unspecified error

Continue reading

How We Do Database Integration Tests With Entity Framework Migrations

There is a follow-up article about integration tests in 2016. Recommended for reading if you are using VSTS and looking at Cake build system

Unit tests are fine and dandy, but if you persist your data in database, persistence code must be tested as well. Some possible bugs will never be picked up only by unit tests. One of the issues I’ve been burned by is entity validation, another is a missing foreign key relationship.

Validation issues can burn you very easy. Look at this bit of code:

public class Person 
{
    [Key]
    public Guid PersonId { get; set; }

    [Required]
    public String FirstName { get; set; }

    [Required]
    public String LastName { get; set; }
}

public void CreatePerson(string firstName, string lastName)
{
    var newPerson = new Person();
    newPerson.FirstName = firstName;

    // dbContext was injected via constructor
    dbContext.Persons.Add(newPerson); 
    dbContext.SaveChanges();
}

NB: This is just a sample code. Nowhere in my projects we do such things.

Continue reading

Attempt to do View Compilation for Azure Web Role

We are hitting the deck with our site performance and optimisation. It is fast, but we want it uber-fast! So next stage is to have IIS up and active all the time with all the views being compiled and ready before any user comes to them.

By default, IIS compiles views only when a request for that view comes in. So first time a user visits some rare page in your application, user is waiting a bit longer while IIS does Just-In-Time compilation. And actually if you look under the hood IIS does stacks of things before it shows you a web-site.

Despite of common believe, IIS does not run your web-application from /bin folder, it copies all required files to a temp folder. To be more specific, it copies files to c:\Windows\Microsoft.NET\Framework64\v4.0.30319\Temporary ASP.NET Files\. Reason for that – file locking. For just-in-time compilation, it needs to update binaries, but in /bin folder binaries can be locked.

Continue reading