.NET tanker & tips

.Net, jQuery og andre nørdede emner

Do you have trust issues? You really should have...

april 19
by steffen 19. april 2019 10:27

Do you trust the data you receive over the internet? If you do, you are very naive and really shouldn’t. Especially when it comes to data relating to authentication and authorization you must tread very carefully and only trust parties that you truly now who are and expect to provide extra care for your data. You have to make sure that the data that you’re trusting has not been tampered with and verify that the data is coming from who you expect it to come from. The interwebs is a dangerous place my friend...

 

The need to transfer data securely over the internet has never been bigger. JSON Web Tokens (JWT, prenounced like jaw with a t at the end, jawt) fits perfectly into this landscap. It provides a secure and easy way of transferring data between two parties.

JWT is an open standard which defines how the format can be used for transmitting information between two parties, in a secure, compact and self-contained way. A JWT can always be verified by the recipient, because it is digitally signed using either the HMAC algorithm using a secret or by using RSA or ECDSA, with a public/private key set. This does not mean that the data cannot be read by others during the network transport, but the recipient can verify that the JWT was actually sent by the expected party in the other end. If the data contained is sensitive, the content can be encrypted, providing data privacy for the parties involved.

 

Use cases for JWT’s

The most common scenario for using JWT’s, is to handle authorization. The JWT can contain information regarding the users identity, which resources can be accessed and which operations are permitted by the user. Many implementations of OAUTH2, which is the most popular protocol for providing authorization, rely heavily on JTW’s. Another use case is simple data transfer. In scenarios where it is essential that the data in question, has not been tampered with and the sender is who they say they are, JWT provides an easy way to secure the data.

 

JWT format

A JWT consists of three parts, separated by dots:

[theHeader].[thePayload].[theSignature]

 

The header

The header consists of two parts: the type of token, which in the case of JWT is “typ”:”JWT” and the algorithm used for signing the token. The normal algorithms are HMAC SHA256 or RSA. The header could look like this: { “alt”:”HS256”, “typ”:”JWT” } When the JWT is being built, the header JSON is Base64Url encoded and is put in the as the first part of the JWT payload.

[theHeader].[thePayload].[theSignature]

 

The payload

The payload part of the JWT are called “claims”. A claim is some information regarding the user (or entity if it is not a user authorization scenario, but a data transfer).

 

Registered claims

There is a set of claims that is a part of the standard. These claims are called the registered claims. They are almost always a part of the payload, in order for the recipient to know which user the other claims in the payload are related to.

The registered claims are:

  • iss - Issuer, identifying the sender of the JWT
  • exp - Expiry, when does the token expire
  • sub - Subject, user identifier
  • aud - Audience, identifying who the token is meant for
  • nbf - Not Before, when the token is valid from
  • iat - Issued at, the time when the JWT was issued
  • jti - JWT Id, unique identifier of the JWT

It is not mandatory that all registered claims are a part of a JWT, but it is recommended. Please note that all the claim names are only three characters long. This is to keep the total payload size as small as possible. It is recommended that you try to mimic this and keep all your claim names as short as possible, in order to keep the total size small.

Public claims

The next type of claims are public claims. Public claims are registered in the IANA JSON Web Token Registry. IANA makes sure that there are no name collisions. Before adding your own custom claim names, please check if IANA already have a name for the data you are trying to save in the JWT or that the name that you want to use is not occupied by some other data type already.

Private claims

The last claim type are private claims. A public claim is a custom claim name that is neither a registed claim or a public claim. It could be some data, that is specific to you application and is not already registered with IANA. An example of a JSON payload could be:

{
   “iss”:”someIssuer”,
   “exp”:”2019-10-10 22:00:00”,
   “sub”:”someSubjectId”,
   “aud”:”someAudience”,
   “nbf”:”1900-01-01 00:00:00”,
   “iat”:”2019-04-10 22:00:00”,
   “jti”:”someJwtId”,
   “name”:”Foo Barson”,
   “xyz”:”MyPrivateClaimValue”
}

Just like the header, the payload is Base64Url encoded and added as the middle part of the JWT.

[theHeader].[thePayload].[theSignature]

The last part of the JWT is the signature. The signature is an encoding of the two preceeding parts of the JWT (the base64Url encoded header and the base64Url encoded payload separated by a dot).

 

For instance:

[SomeBase64UrlEncodedHeader].[SomeBase64UrlEncodedPayload]

 

This string will be encoded with the encoding algorithm stated in the header and added as the last part of the JWT.

[theHeader].[thePayload].[theSignature]

The resulting string is a very compact and secure representation of the data. Especially when comparing it to the “old” SAML standard, which produces much larger payloads. Since bandwith is always an issue - especially for mobile devices - the smaller the data is the better.

 

If you want to play around with how a JWT looks like and how it all works, https://jwt.io is a great resource with a lot of background information. The site also has a JWT debugger, where you can paste in a JWT and see the content or add content to the clear text payload and see the encoded JWT change live. They also have a long list of libraries, which can be used when working with JWT’s in different programming languages and environments.

 

 

 

 

Tags: , ,

General

You are not Mozart - get help with composition

januar 07
by steffen 7. januar 2019 15:21

Mozart In one of my previous blog posts I wrote about dependency injection and why this should be a core principle when designing software architecture. The benefits from injecting dependencies into the classes who need them are many. One of the most important benefits is that your code will be loosely coupled, which makes the code flexible and make it much easier to reuse the code in multiple scenarios. A great benefit from loosely coupled code is also, that the code will be much easier to unit test. This allows us to assert that the code behaves as in the way that it was intended.

The most common way of implementing DI is by using constructor injection. This means that each class will take all their dependencies as an argument in the constructor. This pattern ensures that it is not possible to create an instance of a class, if you do not provide all the required dependencies. You can also inject dependencies by exposing the class dependencies through properties, allowing the client to initialize the dependencies. Personally I am not a fan of this approach, since this put the responsibility of initializing the correct dependencies on the client, which may or may not have the knowledge on the inner workings of the class. This can result in runtime exceptions, if a method is called, which depend on a uninitialized dependency.

When using DI the classes needed for a software system to work, must be build as close to the entry point of the system as possible. In a console application this would be in the Main method and in a MVC application it should be before the controller is executed. This is easily accomplished by using a DI framework (e.g. StructureMap). When using a DI framework, which I highly recommend, it will be responsible for creating the entire object graph, required for the system to function. The DI framework will analyze the dependencies of you code and based on convention and/or configuration it will spin up the required objects and inject them into the program.

A great example of a mature and well functioning DI framework is StructureMap (soon to be called Lamar). One of the cool features in StructureMap is that it has some default conventions, that allows you to get up and running with fewer lines of code. The main convention is that, unless specified in the composition root (the configuration method of StructureMap), for an interface called IFoo it will look for a concrete class called Foo. As such StructureMap rely on the normal naming convention where the name of an interface always start with an "I". This convention means that StructureMap will automatically map all interfaces to the respective concrete implementations, without you writing a single line of code.

Obviously most scenario will not consist exclusively of interfaces and classes with this naming relation. For all the other interface/class combinations, you must define which concrete classes must be used for which interfaces. An example could be that you have a ICar interface and you want StructureMap to inject an instance of the Jeep class (which implements the ICar interface). This is easily done with a short line of code in the configuration of StructureMap.

public class DefaultRegistry : Registry {

public DefaultRegistry() {

            Scan(

                scan => {

                    scan.TheCallingAssembly();

                    scan.WithDefaultConventions();

                });

            For<ICar>().Use<Jeep>();

        }

    }

The DefaultRegistry class and the code in the constructor, is responsible for creating the object graph. This is called the "composition root" and in a more complex application this class will be significantly bigger as the entire object graph of the application is defined here. One of the strong points by having all the configuration centralized in the composition root, is that you always know exactly where the object tree is constructed.

When using StructureMap to control the composition root, an added benefit is that it integrations seamlessly into most application types. When installing StructureMap from NuGet, you can almost certainly find a flavor of StructureMap that suit you application type. This means that as soon as StructureMap has been installed, it will be "plugged into" your application pipeline, ensuring that the composition root is called whenever the application needs an object graph.

Tags:

Dependency Injection | General

Don't let Tony Stark down - use enums!

november 04
by steffen 4. november 2018 16:56

Photo credit Marvel Studio

As a software developer you have many tools in our toolbox, that help create powerful and useful software applications. One of the most important concepts in software development is the principle of simplicity aka. the KISS principle. The more simple your code is, the easier it is to understand and to change, when a change request comes (and it will come sooner or later).

 

One of the most simple concepts that we have is the concept of flags. A flag is a marker that enable the program to recognize different program states and to decide how to proceed in the program flow. The most simple flag is the boolean, which has two states; true or false. But often the state of the program has more than two states and for this scenario the Enum solves the need perfectly.

 

An example of the use of enum, could be the software that defines which type of drivetrain a car has. A normal car is either front wheel drive, rear wheel drive or four wheel drive. This can be clearly represented with the following enum.

 

enum DriveTrain

{

    FrontWheelDrive,

    RearWheelDrive,

    FourWheelDrive

}

 

The drivetrain of a car can be clearly stated with the use of the DriveTrain enum.

 

This is all good and well, but as it turns out you work for Stark Industries and mr Stark has come up with a brand new design for a car, which can direct power to all four wheels independently. At any given time, depending on the situation, any combination of the four wheels can have power. It could be only the left frontwheel, the two right wheel or all four wheels. This requirement could be solved by adding a enum value for each of the wheel combinations, however this is not the most elegant solution.

 

Instead it is possible to use a neat little feature in C#, where it is possible to use the bitwise operators. First we will change our enum to reflect each wheel instead.

 

[Flags]

enum DriveTrain

{

    LeftFrontWheel = 1,

    RightFrontWheel = 2,

    LeftRearWheel = 4,

    RightRearWheel = 8

}

 

Let's start with looking at what we can do with this and we'll look into the nitty gritty stuff afterwards.

 

With this new enum we could do something like this:

DriveTrain wheelsWithPower = DriveTrain.LeftFrontWheel | DriveTrain.RightRearWheel;

 

A call to wheelsWithPower.ToString() returns "LeftFrontWheel, RightRearWheel" to indicate which of the enum values are set in the variable wheelsWithPower. If we have the need to query if a certain flag is set in the variabel we can do this with

 

bool powerToLeftRear = wheelsWithPower.HasFlag(DriveTrain.LeftRearWheel);

 

Very simple and concise!

 

Now let's dig in to some of the details. The most important thing to notice is the fact, that each enum value has a designated value (1, 2, 4 and 8). These number must be a power of 2. If this is not done the code will not work as expected. This has to do with the implementation of the HasFlags, which is a bitwise AND operation and hence each value must have it's own bit.

 

The second thing to notice is the [Flags] attribute. This is not needed for the HasFlags to work. This is only for getting nicer feedback while debugging. If the attribute was not added to the enum, a call to ToString() like above would return 9 instead of "LeftFrontWheel, RightRearWheel". Again this has to do with the underlying implementation, which rely on bit wize logic. The HasFlags works regardless of the Flags attribute.

 

Now mr. Stark can have his car, which alternates between powering each wheel independently and can go kick some bad guy ass.

Tags:

c# | General

Dependency Injection Principle and the Geekmobile

marts 17
by steffen 17. marts 2017 06:28

Almost everyone in the development environment agrees that Dependency Injection (DI) is a corner stone of good software design. When implemented correctly it gives quite a few advantages to the code. The biggest advantages are that the code becomes easier to unit test and that the code will be more loosely coupled. However the concept of Dependency Injection can be a little hard to grasp at first. I will therefore try to first in explain in it general terms and afterwards provide some code examples.

There are two rules to the Dependency Injection Principle:

  • High-level modules should not depend on low-level modules. Both should depend on abstractions
  • Abstractions should not depend on details. Details should depend on abstractions

Let's take a look at what that means. The first rule means that each class should have as few references (none, if possible) to concrete classes as possible. Not to say that a class can't use a concrete class, but it is a clear code smell if there is. Instead you should use abstractions ie. interfaces or abstract classes where possible. The use of interfaces makes the code loose coupled, hence making it much more flexible and handling changing requirements much easier.

The basic idea that, in order to prepare your code for future changes, it should be structured in a way that will make changes easy, without causing a tsunami of changes other places in your code. This is commonly referred to as loose coupling.

The second rule, means that you have to design your code, so that if you change something in your concrete class, it must not change the outcome from what the abstraction expects.

This is best illustrated with an example (inspired by Vincent Ramdhanie's answer on SO). When I get into my car, all the controls (eg. pedals and steering wheel) are abstractions (or interfaces if you will) between me and the mechanics of the car. I understand the abstractions and by using the controls I can control the car: when I press the right pedal the car will accelerate and when I press the middle pedal (or left if you're not driving a stick), the car will decelerate.

Steering wheel from the geek-mobile

Steering wheel from the Geekmobile (image from xboxfreedom.com)

If we change some of the implementation details (eg. changing the engine in the car), you cannot change the abstractions. For instance you cannot swap the pedals, so that the brake pedal is now on the right. The same rules should apply to you code. If you have a calculator class, which implements an interface with a method called Add, you can change the code in the concrete implementation, but never in a way that it changes the abstraction (eg. dividing instead of adding). This is of course a very simple example and you might think your code is much more complex. That might be true, but this is one more reason for you to try to design your code to be as simple and loosely coupled as possible. If you design your classes with the Single Responsibility Principle in mind, your interfaces should become more simple and it should be easier to determine if a change in the details effects the abstraction.

To sum up the Dependency Injection Principle is a way to design you classes, so that the have loose coupling and being aware that do not change the abstractions (the implied understanding of what a interface promise to do) of the system. The next blog post will be much more code heavy and will describe how to use Dependency Injection to put the Dependency Injection Principle into use.

Tags:

Dependency Injection | General

IIS is dead - Long live IIS!

december 22
by steffen 22. december 2014 14:35

A major part developing is debugging. Stepping through your code, inspecting variable and verifying the the program flow behaves as predicted is an essential skill for any developer. The debugger in Visual Studio is pretty good. Place you desired breakpoint, hit F5 and Visual Studio will fire up the local IIS and open up a new browser window (if it is a web application) and you're good to go.

The process of perfecting the code is usually requires alot of "trial and error", where each time you start the debugger, find a bug, stop the debugger, fix the bug and start over. By default Visual Studio will shut down the local IIS when you stop the debugger. That means that if you make a small fix in the code and compile it, you can't just refresh the browser and see the result of the new code instantly. 

Luckily there is an easy fix for this. In Visual Studio go to "Tools -> Options" and in this small popup window, find "Debugging -> Edit and Continue". Remove the checkmark in the "Enable Edit and Continue" from the checkbox and you're all good to go.

IIS will always shut down, when you close Visual Studio. If you want to shut down IIS without closing Visual Studion, go to the system tray, right click the IIS icon and choose close.

 

Tags: ,

ASP.NET | ASP.NET MVC | CodeProject | General

Fejl ifm. opdatering af service reference

juni 11
by steffen 11. juni 2014 14:34

I forbindelse med et projekt, skulle der bruges en web service fra en 3. partsleverandør. Det er jo heldigvis nemt at tilføje og bruge web services i Visual Studio. Et højre-klik på projektet i Project exploreren, vælg "Add Service Reference" og så er man stort set kørende. Denne gang virkede det også fint, lige indtil der var kommet en udvidelse til web servicen og der derfor skulle laves en opdatering af referencen, for at Visual Studio kunne opdatere proxy klasserne. 

Pludselig kastede Visual Studio en fejl:

Custom tool error: Failed to generate code for the service reference 'ServiceReference1'.  Please check other error and warning messages for details

Ikke en specielt hjælpsom besked. Som fejlbeskeden foreslog blev de andre warnings/errors undersøgt, men uden at det gjorde problemet særligt meget nemmere:

Warning1Custom tool warning: Cannot import wsdl:portType

Detail: An exception was thrown while running a WSDL import extension: System.ServiceModel.Description.DataContractSerializerMessageContractImporter

Error: Type 'Newtonsoft.Json.Linq.JToken' is a recursive collection data contract which is not supported. Consider modifying the definition of collection 'Newtonsoft.Json.Linq.JToken' to remove references to itself.

Efter at have googlet lidt rundt og have mistet en hårtot eller to, lykkedes det dog at finde en løsning. Det viser sig at problemet bundede i at Visual Studio forsøgte at genbruge nogle assemblies, som ikke længere var gyldige. Problemet blev nemt løst ved at højre-klikke på referencen i Project Exploreren, vælge "Configure Service Reference" og fjerne fluebenet i "Reuse types in reference assemblies". Hvis referencen tilføjes på ny, findes denne valgmulighed under "Advanced" i dialog boksen, hvor URL'en på servicen indtastes.

 

Tags: ,

General

Windows authentication på localhost

maj 07
by steffen 7. maj 2014 12:13

Jeg oplevede forleden et problem med en af mine intranet applikationer, som kører med ASP.NET's Windows authentication, hvor applikationen bruger dét Windows login som man er logget på computeren med. 

Når jeg startede applikationen fra Visual Studio, fik jeg en fejlbesked:

Access is denied


Når jeg gik på applikationen i produktionsmiljøet, fungerede det fint og der var således ikke nogen problemer med den måde jeg var logget ind på min computer på. Jeg travede nettet igennem for at finde en løsning og det lykkedes heldigvis at finde frem til en let løsning

Man skal bare vælge projektet i Solution exploreren i Visual Studio og trykke F4, for at åbne Properties. Her kan man vælge at enable eller disable Windows Authentication. Den skal naturligvis være sat til Enabled.

Opsætning af Windows Authentication

Desværre er det ikke lykkedes mig at hitte ud af, hvor denne indstilling pludselig var blevet ændret, omend jeg i en anden forbindelse har været inde og rode med en globale applicationhost.config fil, hvor man tilsyneladende kan sætte denne værdi globalt. Jeg syntes dog ikke at jeg har været inde og pille ved nogen værdier, som har med ovenstående problem at gøre - omvendt har jeg taget fejl før :-)

Tags: , , , ,

General

Tving IE compability mode off

april 25
by steffen 25. april 2014 12:01

Jeg løb for nyligt ind i et problem, hvor Internet Explorer 9's compability mode som standard var slået til, hvis man gik på intranet sider. Det gav mildest talt nogle forfærdelige konsekvenser for Bootstrap layoutet som jeg bruger til siden.

Heldigvis er det relativt nemt at angive i HTML-dokumentets HEAD sektion, hvilken rendering metode der skal benyttes. Ved at tilføje nedenstående meta tag, kan man angive til IE, hvilken rendering der skal benyttes.

<meta http-equiv="X-UA-Compatible" content="IE=9" />

Ovenstående angiver at IE skal rendere siden som IE 9. Man kan også angive at IE altid skal bruge den nyeste rendering:

<meta http-equiv="X-UA-Compatible" content="IE=edge" />

"edge" angiver at der altid skal benyttes den nyeste rendering, men man skal bruge denne indstilling varsomt, da det potentielt kan have konsekvenser når der kommer en ny version af IE, hvor renderingen af indholdet på siden ændrer sig ift. ældre versioner. 

Ovenstående er fundet på Stack Overflow.

Tags: , ,

General