.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:



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.



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:

   “exp”:”2019-10-10 22:00:00”,
   “nbf”:”1900-01-01 00:00:00”,
   “iat”:”2019-04-10 22:00:00”,
   “name”:”Foo Barson”,

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


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:



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


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: , ,


Windows authentication på localhost

May 07
by steffen 7. May 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: , , , ,


Rettigheder i ASP.NET MVC

March 21
by steffen 21. March 2014 23:13

Det er dejligt nemt at sætte rettigheder på et MVC projekt. Det er faktisk muligt at styre det på applikations niveau, som vi kender det fra webforms, hvor man laver en overordnet definition af hvem der må komme ind og hvem der ikke må i web.config. Men det er også muligt at gøre det på controller niveau, hvor man opsætter krav til hvilke brugere, der overordnet har adgang til controllerens action metoder. Og sidst men ikke mindst kan man opsætte rettighedskravene på action metode niveau. 

Det er endvidere så smart skruet sammen, at hvis der er angivet på controller niveau (se nedenfor), at kun brugere med rollen X må tilgå kontrolleren, kan man opsætte strammere regler for en action metoderne og kun give bruger Y lov til at tilgå dén. Således vil bruger Y kunne kalde action metoden, men kun så længe at Y også overholder rettighederne, der er angivet på controller niveau. På denne måde kan man opsætte et hierarki af sikkerhed, hvor man kan stramme reglerne på metode niveau, såfremt det er nødvendigt.

Der er to metoder man kan authorize brugere på: Users og Roles

Users er angivelse af de brugernavne som har adgang. Her er det vigtigt at notere at hvis man benytter windows authentication mode (det vil sige at der tjekkes op imod et Active Directory - typisk en intranet løsning), skal man også angive domænet som brugeren er logget på. 

Roles er angivelsen af de brugerroller, som har adgang. Det er den mest elegante måde at styre adgangen på, da det ikke kræver en recompilering, hvis der er ændringer til hvem der har adgang. Hvis man benytter Users, skal der en recompilering og redeploy til, når der er ændringer til rettigheder. Hvis man tjekker på Roles, skal man blot tilføje eller fjerne brugere til de respektive roller og herefter vil det automatisk slå igennem, næste gang de tilgår applikationen.

Eksempel på rettigheder i web.config

    <compilation debug="false" targetFramework="4.5" />
    <httpRuntime targetFramework="4.5" />
    <authentication mode="Windows" />
<allow roles="BrugereMedDenneRolleHarAdgang" /> <deny users="*" /> </authorization> </system.web>

Her angiver vi at vi bruger windows authorization - det vil sige at der tjekkes op imod et Active Directory, med den bruger som er logget ind på computeren. Herefter angives det at alle brugere, der har rollen 'BrugereMedDenneRolleHarAdgang' har adgang til applikationen og alle andre har ikke adgang.

Eksempel på rettigheder på controller niveau

public class TestController : Controller
    [Authorize(Roles = "GruppeSomHarAdgang")]
public ActionResult Index() { return View(); }

public ActionResult SomeOtherMethod()
return view();

Her har alle brugere som er logget ind adgang, men kun de brugere der har gruppen 'GruppeSomHarAdgang' har adgang til at eksekvere Index action metoden. Bemærk at hvis man benytter Authorize attributten uden at angive Roles eller Users, tolkes det som at brugeren blot skal være logget ind. Det vil sige alle ikke-anonyme brugere får adgang.

En lille gotcha

Hvis man ved en fejl forsøger at validere brugere op imod en gruppe, der ikke findes får man en lidt kryptisk fejlbesked:

The trust relationship between the primary domain and the trusted domain failed

Det kan virke noget forvirrende og hvis det sker, skal man lige tjekke at man har stavet rolle-navnet rigtigt i Authorize attributten og selvfølgelig at rollen rent faktisk eksisterer.


Tags: , ,