Promoting SoC Through Application Layering

Creating a layered design in an application is a fundamental element of modern software architecture. The goal is to promote the Separation of Concerns (SoC) design principle. Separation of Concerns The ideas behind SoC date back to Dijkstra's 1974 paper "On the role of scientific thought" . In computer science, separation of concerns (sometimes abbreviated as SoC) is a design principle for separating a computer program into distinct sections. Each section addresses a separate concern, a set of information that affects the code of a computer program. A concern can be as general as "the details of the hardware for an application", or as specific as "the name of which class to instantiate". A program that embodies SoC well is called a modular program. Modularity, and hence separation of concerns, is achieved by encapsulating information inside a section of code that has a well-defined interface. - Wikipedia SoC is a broad design principal th...

JWT DateTimes in .NET

When you're working in .NET and creating JSON Web Tokens (JWTs), there can be some challenges. There are numerous libraries that can aid in the creation of JWTs, and Microsoft provides the System.IdentityModel.Tokens.Jwt namespace to help.

When creating a JWT manually, you'll need to set values such as:

  • exp (expiration time): Time after which the JWT expires
  • nbf (not before time): Time before which the JWT must not be accepted for processing
  • iat (issued at time): Time at which the JWT was issued; can be used to determine age of the JWT
Visual Studio Screenshot - Creating JWT

One thing to keep in mind is that JWT datetimes are represented in Unix time (number of seconds since January 1, 1970). Fortunately, .NET offers the ToUnixTimeSeconds method in the DateTimeOffset class. To make this easier, you can use a function to convert a .NET DateTime to a JWT date/time format.

private long DateTimeForJSONWebToken(DateTime dateTime)
{
	return (new DateTimeOffset(dateTime)).ToUnixTimeSeconds();
}

Working with DateTimes and DateTimeOffsets can get complicated, especially when crossing technology boundaries and timezones. It may be necessary to specify the DateTimeKind before passing the DateTime to the DateTimeForJSONWebToken method.

For more information, check Converting between DateTime and DateTimeOffset.