<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[Wesley Cabus]]></title><description><![CDATA[Wesley is a Microsoft MVP, board member at VISUG (Belgian Visual Studio User Group) and Customer Success Engineer at Duende Software.]]></description><link>https://wesleycabus.be</link><generator>RSS for Node</generator><lastBuildDate>Sun, 12 Apr 2026 15:46:54 GMT</lastBuildDate><atom:link href="https://wesleycabus.be/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Are you sure your access tokens are really secure?]]></title><description><![CDATA[Chances are high that if you’re building a Web API, you’re relying on access tokens when client applications or services interact with your API in order to perform authentication and authorization. The two most common types of access tokens are opaqu...]]></description><link>https://wesleycabus.be/are-you-sure-your-access-tokens-are-really-secure</link><guid isPermaLink="true">https://wesleycabus.be/are-you-sure-your-access-tokens-are-really-secure</guid><category><![CDATA[Security]]></category><category><![CDATA[JWT]]></category><category><![CDATA[oauth]]></category><category><![CDATA[APIs]]></category><dc:creator><![CDATA[Wesley Cabus]]></dc:creator><pubDate>Tue, 05 Nov 2024 19:34:52 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1730835262958/d6c9c5e8-7cd8-49e6-9355-c8326eacdf5a.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Chances are high that if you’re building a Web API, you’re relying on access tokens when client applications or services interact with your API in order to perform authentication and authorization. The two most common types of access tokens are opaque (or reference) tokens and JSON Web Tokens (aka JWTs).</p>
<p>These two types of tokens have their pros and cons:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td><strong>Opaque token</strong></td><td><strong>JWT</strong></td></tr>
</thead>
<tbody>
<tr>
<td>+ Better privacy</td><td>- JWT can contain sensitive data</td></tr>
<tr>
<td>+ Easier to revoke</td><td>- Lifetime of a JWT is encoded within</td></tr>
<tr>
<td>+ Very small in size, since it’s just a reference</td><td>+/- Can be kept small, but can also easily grow large when including lots of claims</td></tr>
<tr>
<td>- Additional server requests are needed to check the token’s validity and to retrieve user data</td><td>+ Self-contained</td></tr>
<tr>
<td>- There’s no real defining standard</td><td>+ Standardized</td></tr>
</tbody>
</table>
</div><p>Let’s focus on JWT tokens, since this type of token is still the most frequently used type. A JSON Web Token consists of three parts:</p>
<pre><code class="lang-json">eyJhbGciOi...VCJ9 . eyJzdW....MDgxMTMzMX0 . GvHaTrJuFo...s15Ss
      header      .         payload       .     signature
</code></pre>
<p>The first two parts are Base64url-encoded JSON objects, representing the token’s header information and the payload of the token. The third part is a Base64url-encoded array of bytes representing the signature of the first two parts combined.</p>
<h1 id="heading-whats-in-the-header">What’s in the header?</h1>
<p>The header of a JWT typically includes the following three properties, but can contain additional information. I’ll circle back to the additional information later, but for now, here are the most common properties:</p>
<ul>
<li><p>“typ”: the media type of the token. Sometimes omitted, this value is typically set to “JWT” to indicate that this is a JSON Web Token. For access tokens, you can also see the value “at+jwt” to further specify that the JSON Web Token is an access token.</p>
</li>
<li><p>“alg”: the cryptographic algorithm used to sign the token. Examples are “HS256” for tokens signed using the HMAC SHA-256 algorithm, “RS256” for tokens signed using a private/public RSA key pair and SHA-256, etc.<br />  You can find a complete list in <a target="_blank" href="https://datatracker.ietf.org/doc/html/rfc7518#section-3.1">RFC 7518</a>.</p>
</li>
<li><p>“kid”: the key ID of the key that was used to sign the JSON Web Token. When validating a JWT signature, the “kid” value is used to look up the correct public key in case multiple JSON Web Keys (JWKs) are available to sign or validate JSON Web Tokens. For example, this is the current list of available JWKs for https://demo.duendesoftware.com: <a target="_blank" href="https://demo.duendesoftware.com/.well-known/openid-configuration/jwks">https://demo.duendesoftware.com/.well-known/openid-configuration/jwks</a></p>
</li>
</ul>
<h1 id="heading-and-in-the-payload">And in the payload?</h1>
<p>The payload is a JSON object containing claims. Some claim types are registered and frequently used, or even mandatory, but you can include as many custom claims as you wish. Just remember that every claim adds data to your token, and tokens can become too large to be delivered to client applications depending on the delivery mechanism.</p>
<p>The most commonly used claim types are:</p>
<ul>
<li><p>“iss”: the issuer of the JWT. This claim typically points to the service that issues your tokens. In OAuth 2.0 flows, you can most likely use the claim value to find the <code>/.well-known/openid-configuration</code> discovery document.</p>
</li>
<li><p>“sub”: the subject of the JWT. The value indicates the user or application who can access your API resource server.</p>
</li>
<li><p>“aud”: the audience, or intended recipients for the JWT. The audience value points to your API, to indicate that the JWT was meant to be used to gain access to your API.</p>
</li>
<li><p>“exp”: the expiration time. When this timestamp passes, the JWT is no longer valid for use.</p>
</li>
<li><p>“nbf”: the not-before time. The JWT only becomes valid for use after this timestamp.</p>
</li>
<li><p>“iat”: the issued-at time. This is the timestamp when the JWT was originally created, and can be used to determine the age of the JWT.</p>
</li>
<li><p>“jti”: a unique identifier for the JWT, which can be used to prevent replay attacks.</p>
</li>
</ul>
<h1 id="heading-validating-a-jwt">Validating a JWT</h1>
<p>It would be pretty bad if your API would just accept any access token if it contains the correct audience claim value, so we ensure our API only accepts tokens which satisfy a few rules:</p>
<ol>
<li><p>The “aud” claim contains (only) values that we expect for our API.</p>
</li>
<li><p>The current date/time falls between the “nbf” and “exp” values. Some leeway can be granted using a clock skew, to accommodate for time drifting between different servers.</p>
</li>
<li><p>The “iss”, or issuer of the token, is a known service which our API trusts.</p>
</li>
<li><p>The “alg”, or signature algorithm, is on our allowed list of cryptographic algorithms.</p>
</li>
<li><p>The signature can be successfully validated using the “kid” and the corresponding public key material of the issuer.</p>
</li>
</ol>
<p>Luckily, there are plenty of open-source libraries out there for a variety of frameworks or programming languages, which you can use to validate JSON Web Tokens. You can find a list of JWT libraries at <a target="_blank" href="https://jwt.io/libraries">https://jwt.io/libraries</a>.</p>
<p>But… What if this library contains a vulnerability? Or what if an update breaks one of the critical validation paths? Or if some of the library’s methods work every-so-slightly different when validating tokens, causing some invalid tokens to slip through the maze?</p>
<h1 id="heading-trust-but-verify-test-your-jwt-validation">Trust, but verify: test your JWT validation!</h1>
<p>The easiest method to add some trust into your API, is by writing tests which validate that various JSON Web Tokens, both valid and invalid, are being properly validated and respectively accepted or rejected by your API. Every time you then update the JWT library you use, you can automatically rerun your tests and verify that the validation still works as expected.</p>
<p>You might wonder what could go wrong. Well, let’s give some examples of tokens that may try to fool the validation logic.</p>
<h2 id="heading-algorithm-what-algorithm">Algorithm? What algorithm?</h2>
<p>The “alg” property in the token’s header, again, indicates which cryptographic algorithm is used to sign the token. But this property can also be set to “none”, to indicate that the JWT is not signed at all.</p>
<p>Yes. The following token is a valid JWT:</p>
<pre><code class="lang-json">eyJhbGciOiJub25lIiwidHlwIjoiSldUIn0.eyJzdWIiOiIxMjM0IiwibmFtZSI6Ildlc2xleSIsImlhdCI6MTczMDgxMTMzMX0.

<span class="hljs-comment">// The JWT above equals the following:</span>
{
  <span class="hljs-attr">"alg"</span>: <span class="hljs-string">"none"</span>,
  <span class="hljs-attr">"typ"</span>: <span class="hljs-string">"JWT"</span>
}
.
{
  <span class="hljs-attr">"sub"</span>: <span class="hljs-string">"1234"</span>,
  <span class="hljs-attr">"name"</span>: <span class="hljs-string">"Wesley"</span>,
  <span class="hljs-attr">"iat"</span>: <span class="hljs-number">1730811331</span>
}
.
<span class="hljs-comment">// no signature</span>
</code></pre>
<p>This poses a problem, exactly because this is valid as far as <a target="_blank" href="https://datatracker.ietf.org/doc/html/rfc7519#section-6">RFC 7519</a> is concerned. Luckily, most validation libraries will allow you to specify which signature algorithms your API allows, and some even disallow “none” from being used by default.</p>
<p>There are some people out there, however, who don’t play nice and think outside the box. These people may try to authenticate against your API using a JWT where the “alg” property is set to “nONe”, or “some-random-value-here”. Which could be enough to fool a poorly written JWT validation library, and yes, some accepted “nONe” as a valid token…</p>
<p>Writing an integration test to catch these invalid or unsupported signature algorithms, can be very easy:</p>
<pre><code class="lang-csharp"><span class="hljs-function"><span class="hljs-keyword">public</span> class <span class="hljs-title">SignatureAlgorithmTests</span>(<span class="hljs-params">TargetApiWebApplicationFactory factory</span>) : <span class="hljs-title">JwtGuardTestBase</span>(<span class="hljs-params">factory</span>)</span>
{
    [<span class="hljs-meta">Theory(DisplayName = <span class="hljs-meta-string">"When a token uses an unsupported signature algorithm, the API should return a 401 Unauthorized response."</span>)</span>]
    [<span class="hljs-meta">MemberData(nameof(GetDisllowedAlgorithms))</span>]
    <span class="hljs-function"><span class="hljs-keyword">internal</span> <span class="hljs-keyword">async</span> Task <span class="hljs-title">Accessing_AuthorizedUrl_Is_Unauthorized_For_Unsupported_Signature_Algorithms</span>(<span class="hljs-params"><span class="hljs-keyword">string</span> signatureAlgorithm</span>)</span>
    {
        <span class="hljs-comment">// Arrange</span>
        <span class="hljs-keyword">var</span> jwt = <span class="hljs-keyword">await</span> GetJwtAsync(signatureAlgorithm);
        Client!.DefaultRequestHeaders.Authorization = <span class="hljs-keyword">new</span> AuthenticationHeaderValue(<span class="hljs-string">"Bearer"</span>, jwt);

        <span class="hljs-comment">// Act</span>
        <span class="hljs-keyword">var</span> response = <span class="hljs-keyword">await</span> Client.GetAsync(TestSettings.CurrentTestSettings.TargetUrl);

        <span class="hljs-comment">// Assert</span>
        Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
    }

    <span class="hljs-function"><span class="hljs-keyword">private</span> Task&lt;<span class="hljs-keyword">string</span>&gt; <span class="hljs-title">GetJwtAsync</span>(<span class="hljs-params"><span class="hljs-keyword">string</span> signatureAlgorithm</span>)</span>
    {
        <span class="hljs-comment">// Use a JwtBuilder instance to build an access token</span>
        <span class="hljs-keyword">return</span> Factory.CreateJwtBuilder()
            .WithSignatureAlgorithm(signatureAlgorithm)
            .BuildAsync();
    }
}

<span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">JwtBuilder</span>
{
    <span class="hljs-comment">// Most other properties and methods are omitted for brevity...</span>

    <span class="hljs-keyword">public</span> Microsoft.IdentityModel.Tokens.SigningCredentials? SigningCredentials { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">private</span> <span class="hljs-keyword">set</span>; }
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">string</span>? SignatureAlgorithm { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">private</span> <span class="hljs-keyword">set</span>; }

    <span class="hljs-function"><span class="hljs-keyword">public</span> JwtBuilder <span class="hljs-title">WithSignatureAlgorithm</span>(<span class="hljs-params"><span class="hljs-keyword">string</span> signatureAlgorithm</span>)</span>
    {
        SignatureAlgorithm = signatureAlgorithm;
        SigningCredentials = <span class="hljs-literal">null</span>;

        <span class="hljs-keyword">return</span> <span class="hljs-keyword">this</span>;
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">async</span> Task&lt;<span class="hljs-keyword">string</span>&gt; <span class="hljs-title">BuildAsync</span>(<span class="hljs-params"></span>)</span>
    {
        <span class="hljs-keyword">if</span> (!<span class="hljs-keyword">string</span>.IsNullOrEmpty(SignatureAlgorithm) &amp;&amp;
            (<span class="hljs-keyword">string</span>.Equals(SecurityAlgorithms.None, SignatureAlgorithm, StringComparison.OrdinalIgnoreCase) ||
            !TestSettings.KnownSecurityAlgorithms.Contains(SignatureAlgorithm)))
        {
            <span class="hljs-comment">// Either using "none" (case-insensitive) or an unknown algorithm. Return an unsigned token.</span>
            <span class="hljs-keyword">return</span> BuildJwtHeader().Base64UrlEncode() + <span class="hljs-string">"."</span> + BuildJwtPayload().Base64UrlEncode() + <span class="hljs-string">"."</span>;
        }

        <span class="hljs-comment">// default logic which signs and returns the token</span>
    }
}
</code></pre>
<p>With a bit of modification, the same test logic can also be used to test that validly signed tokens are rejected if they’re signed using an algorithm which your API doesn’t want to use, like HS256 for example.</p>
<h2 id="heading-but-wait-theres-more-shenanigans">But wait, there’s more shenanigans…</h2>
<p>Remember when I told you earlier that I would circle back on the claims in a JWT header? Well, there are a few special ones:</p>
<ul>
<li><p>“jku”: JWK Set URL, pointing to a resource for a set of JSON Web Keys. While this URL could in theory point to the authority or the issuer of the token, it’s not a requirement! Everyone can create a JWT token, host their public JWK material and add a reference URL to the token header.</p>
</li>
<li><p>“jwk”: using this property, a token include the public JSON Web Key in its header, to allow for full self-validation of the signature. This is <strong>very</strong> dangerous! Because this means that an attacker can craft a self-signed JSON Web Token and simply include the public JWK in the token’s header!</p>
</li>
<li><p>“x5u”: a URL pointing to a X.509 certificate or certificate chain, which can be used to validate the signature by hosting the public certificate (chain) online. Just like the “jku” property, the URL could in theory live on the same server as the authority or issuer, but this doesn’t need to be the case.</p>
</li>
<li><p>“x5c”: an X.509 certificate or certificate chain, which can be used to self-validate the signature, just like the “jwk” property. Again, very dangerous!</p>
</li>
</ul>
<p>Testing these very specific methods to bypass our API’s security is a bit more challenging, since we need to generate valid signature key material and find a way to host it (for the “jku” and “x5u” test scenarios) externally. But in pseudocode, this is how you would write the tests:</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">ExternalSignatureTests</span> : <span class="hljs-title">IntegrationTestBase</span>
{
    [<span class="hljs-meta">Fact</span>]
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">async</span> Task <span class="hljs-title">RejectExternallySignedToken</span>(<span class="hljs-params"></span>)</span>
    {
        <span class="hljs-comment">// Arrange</span>
        <span class="hljs-keyword">var</span> jwt = GetJwt(<span class="hljs-string">"jwk"</span>);
        Client!.DefaultRequestHeaders.Authorization = <span class="hljs-keyword">new</span> AuthenticationHeaderValue(<span class="hljs-string">"Bearer"</span>, jwt);

        <span class="hljs-comment">// Act</span>
        <span class="hljs-keyword">var</span> response = <span class="hljs-keyword">await</span> Client.GetAsync(<span class="hljs-string">"/secure-api-endpoint"</span>);

        <span class="hljs-comment">// Assert</span>
        Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
    }

    <span class="hljs-function"><span class="hljs-keyword">private</span> <span class="hljs-keyword">string</span> <span class="hljs-title">GetJwt</span>(<span class="hljs-params"><span class="hljs-keyword">string</span> testCase</span>)</span>
    {
        <span class="hljs-keyword">var</span> signatureAlgorithm = <span class="hljs-string">"ES256"</span>
        <span class="hljs-keyword">var</span> jwtBuilder = Factory.CreateJwtBuilder()
            .WithSignatureAlgorithm(signatureAlgorithm);

        <span class="hljs-keyword">var</span> header = jwtBuilder.BuildJwtHeader();
        <span class="hljs-keyword">var</span> payload = jwtBuilder.BuildJwtPayload();

        <span class="hljs-keyword">var</span> encodedPayload = payload.Base64UrlEncode();

        <span class="hljs-keyword">var</span> headerAndPayload = <span class="hljs-string">""</span>;
        <span class="hljs-keyword">var</span> signature = <span class="hljs-string">""</span>;

        <span class="hljs-keyword">switch</span> (testCase)
        {
            <span class="hljs-keyword">case</span> <span class="hljs-string">"jwk"</span>:
                signature = InjectJsonWebKey(signatureAlgorithm, header, encodedPayload, <span class="hljs-keyword">out</span> headerAndPayload);
                <span class="hljs-keyword">break</span>;

            <span class="hljs-comment">// other test cases go here...</span>

            <span class="hljs-keyword">default</span>:
                <span class="hljs-keyword">return</span> jwtBuilder.BuildAsync().GetAwaiter().GetResult();
        }

        <span class="hljs-keyword">return</span> headerAndPayload + <span class="hljs-string">"."</span> + signature;
    }

    <span class="hljs-function"><span class="hljs-keyword">private</span> <span class="hljs-keyword">string</span> <span class="hljs-title">InjectJsonWebKey</span>(<span class="hljs-params"><span class="hljs-keyword">string</span> signatureAlgorithm, JwtHeader header, <span class="hljs-keyword">string</span> encodedPayload, <span class="hljs-keyword">out</span> <span class="hljs-keyword">string</span> headerAndPayload</span>)</span>
    {
        <span class="hljs-keyword">var</span> securityKey = SecurityKeyBuilder.CreateSecurityKey(signatureAlgorithm);
        <span class="hljs-keyword">var</span> jsonWebKey = JsonWebKeyConverter.ConvertFromSecurityKey(securityKey);
        jsonWebKey.Alg = signatureAlgorithm;
        jsonWebKey.Use = <span class="hljs-string">"sig"</span>;

        header[<span class="hljs-string">"jwk"</span>] = jsonWebKey.ToDictionary();
        header[<span class="hljs-string">"kid"</span>] = jsonWebKey.KeyId;

        <span class="hljs-keyword">return</span> SignAndReturnJwt(header, encodedPayload, signatureAlgorithm, securityKey, <span class="hljs-keyword">out</span> headerAndPayload);
    }

    <span class="hljs-function"><span class="hljs-keyword">private</span> <span class="hljs-keyword">string</span> <span class="hljs-title">SignAndReturnJwt</span>(<span class="hljs-params">JwtHeader header, <span class="hljs-keyword">string</span> encodedPayload, <span class="hljs-keyword">string</span> signatureAlgorithm, SecurityKey securityKey, <span class="hljs-keyword">out</span> <span class="hljs-keyword">string</span> headerAndPayload</span>)</span>
    {
        headerAndPayload = header.Base64UrlEncode() + <span class="hljs-string">"."</span> + encodedPayload;

        <span class="hljs-keyword">var</span> asciiBytes = Encoding.ASCII.GetBytes(headerAndPayload);
        <span class="hljs-keyword">var</span> signatureProvider = CryptoProviderFactory.Default.CreateForSigning(securityKey, signatureAlgorithm);
        <span class="hljs-keyword">try</span>
        {
            <span class="hljs-keyword">var</span> signatureBytes = signatureProvider.Sign(asciiBytes);
            <span class="hljs-keyword">return</span> Base64UrlEncoder.Encode(signatureBytes);
        }
        <span class="hljs-keyword">finally</span>
        {
            CryptoProviderFactory.Default.ReleaseSignatureProvider(signatureProvider);
        }
    }
}
</code></pre>
<p>Writing these test cases can be very tedious and pose some challenges by themselves. But what if I told you that there’s a solution for that?</p>
<h1 id="heading-enter-jwt-guard">Enter JWT Guard</h1>
<p>After attending an API security workshop, I got the idea to write some of these test cases for my own API’s, but quickly found that I was repeating myself. So I started working on extracting the test cases in a separate project and made them configurable, to easily apply them to the several API projects.</p>
<p>The end result? JWT Guard.</p>
<p>A template for .NET, allowing you to easily add a JWT test project to your existing API project by these two simple commands:</p>
<pre><code class="lang-bash"><span class="hljs-comment"># You only need to do this once per computer</span>
dotnet new install JWTGuard.Template

<span class="hljs-comment"># This command runs the JWT Guard template and creates a new JWT test project:</span>
dotnet new jwt-guard --apiProject &lt;relative-path-to-web-api-project&gt;
</code></pre>
<p>After adding the test project, all that remains is to configure the TestSettings class in the new test project, so that it know the correct audience for your API and can connect to a secured API “GET” endpoint.</p>
<p>Want to know more? Then visit <a target="_blank" href="https://jwtguard.net">https://jwtguard.net</a> for the full documentation.<br />Want to see the code? That’s available over on <a target="_blank" href="https://github.com/wcabus/jwt-guard">GitHub</a>.</p>
<p>Feel free to give it a go and let me know what you think!</p>
]]></content:encoded></item><item><title><![CDATA[Be wary of account enumeration possibilities]]></title><description><![CDATA[Account enumeration is the process where someone attempts to find out which accounts are valid users in a system, by using typically the login, registration or password reset pages of a system in a way that it wasn't designed for. The most basic exam...]]></description><link>https://wesleycabus.be/be-wary-of-account-enumeration-possibilities</link><guid isPermaLink="true">https://wesleycabus.be/be-wary-of-account-enumeration-possibilities</guid><category><![CDATA[Security]]></category><category><![CDATA[software development]]></category><category><![CDATA[Software Engineering]]></category><dc:creator><![CDATA[Wesley Cabus]]></dc:creator><pubDate>Wed, 07 Dec 2022 10:25:53 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/unsplash/90JFNMyBeek/upload/v1669888643462/3LlhQoLnR.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Account enumeration is the process where someone attempts to find out which accounts are valid users in a system, by using typically the login, registration or password reset pages of a system in a way that it wasn't designed for. The most basic example of a potential issue when it comes to account enumeration, is the response delivered when attempting to log in with either a wrong username or password.</p>
<p>Go ahead and try this yourself if you'd like: enter either a wrong username or an invalid password for your own valid username on a website where you have an active account. What response do you get back?
Hopefully, the answer is something in the lines of:</p>
<blockquote>
<p>"Invalid username or password"</p>
</blockquote>
<p>But if the website returns a response like <em>invalid username</em> when entering an unknown username, or <em>invalid password</em> when entering your own username? Then you know that in the second case, the username is valid. Which means that someone with less noble intentions can now attempt to contact you because they know you have an account on this website or service.</p>
<h1 id="heading-but-what-about-registrations">But what about registrations?</h1>
<p>Showing a uniform response to bad login attempts is easy. But in a registration form, you may run into more issues when attempting to thwart account enumeration vulnerabilities.</p>
<p>When we implemented our registration form, we check for the following things in no particular order:</p>
<ul>
<li>the username is entered</li>
<li>the username looks like an email address, because it should be a valid email address</li>
<li>the username is not used by another user</li>
<li>the password is entered</li>
<li>the password has between 8 and 100 characters</li>
<li>the password meets the complexity requirements (a-z, A-Z, 0-9, punctuation characters)</li>
<li>the confirmation password is entered</li>
<li>the confirmation password matches the first password field's value</li>
</ul>
<p>One of these validations is a bit more special: the fact that the username is not used by another user. You can't just validate against this and show an error like:</p>
<blockquote>
<p>We're sorry, but the username "mike.wazowski@pixar.com" has already been taken</p>
</blockquote>
<p>A validation message like this would make it very obvious that this username is known in the system! Instead, when all fields contain valid input, but the username already exists, we:</p>
<ol>
<li>Show a confirmation that the registration succeeded, and that the user should check their inbox to activate their account.</li>
<li>Send an email to the already registered user that someone tried to register an account using their email address, and, in case they did this, remind them they already have an account.</li>
</ol>
<h1 id="heading-always-test-your-forms">Always test your forms</h1>
<p>This all sounds fine, until we started rigorously testing our registration form. Here's the input we used and the resulting validation errors or confirmation:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Username</td><td>Password</td><td>Result</td></tr>
</thead>
<tbody>
<tr>
<td>&lt;new account&gt;</td><td>&lt;too short&gt;</td><td><em>Your password should be between 8 and 100 characters in size.</em></td></tr>
<tr>
<td>&lt;existing account&gt;</td><td>&lt;too short&gt;</td><td><em>Your password should be between 8 and 100 characters in size.</em></td></tr>
<tr>
<td>&lt;new account&gt;</td><td>&lt;right size but only lowercase letters&gt;</td><td><em>Your password should contain a combination of lowercase, uppercase, digits and punctuation characters.</em></td></tr>
<tr>
<td>&lt;existing account&gt;</td><td>&lt;right size but only lowercase letters&gt;</td><td><strong>Your account has been created, please check your inbox to activate your account.</strong></td></tr>
</tbody>
</table>
</div><p>Whoops! Apparently, the password complexity rules were being checked during the creation of the user account, and not before we checked if the username was already taken! This different result means that someone could try to find out who already has an account based on the different validation response!</p>
<p>Luckily, we quickly identified and mitigated this issue before the registration form went live.</p>
]]></content:encoded></item><item><title><![CDATA[When a session stops working because you're being too strict...]]></title><description><![CDATA[Recently, I had to pass around some data between two HTTP requests in an ASP.NET Core project. Because this data could be interesting to retain during the user's session, I stored it in HttpContext.Session which was configured in the Startup class an...]]></description><link>https://wesleycabus.be/when-a-session-stops-working-because-youre-being-too-strict</link><guid isPermaLink="true">https://wesleycabus.be/when-a-session-stops-working-because-youre-being-too-strict</guid><category><![CDATA[asp.net core]]></category><category><![CDATA[cookies]]></category><dc:creator><![CDATA[Wesley Cabus]]></dc:creator><pubDate>Wed, 01 Dec 2021 11:10:49 GMT</pubDate><content:encoded><![CDATA[<p>Recently, I had to pass around some data between two HTTP requests in an ASP.NET Core project. Because this data could be interesting to retain during the user's session, I stored it in <code>HttpContext.Session</code> which was configured in the Startup class anyway.
During normal web app navigation events (going to a form, POSTing the form, ...), that session data worked as expected. Also when a <code>RedirectToAction</code> was triggered in a controller while running on <strong>localhost</strong>, the session was properly updated and preserved.</p>
<p>Time to create a new build and deploy it to the DEV environment, right? Well...</p>
<p>While testing in the DEV environment, everything still worked <em>except</em> when we hit that <code>RedirectToAction</code> flow: the session state was being reset every time! 
I doublechecked all of the settings, but didn't see any obvious issues there. Then I tried to use <code>TempData</code> as a fallback for the <code>RedirectToAction</code> flow, which fixed the issue on the remote environment. </p>
<p>Huh. But TempData, just like Session, also uses cookies... Why does TempData work then when Session doesn't? Is it a difference in implementation, or the positioning of the middleware? </p>
<p>TempData, by default, uses its own cookie. You can also specify this behavior manually or change the cookie settings by calling <code>AddCookieTempDataProvider</code>:</p>
<pre><code><span class="hljs-selector-tag">services</span><span class="hljs-selector-class">.AddControllersWithViews</span>()
    <span class="hljs-selector-class">.AddCookieTempDataProvider</span>();
</code></pre><p>You can also tell ASP.NET Core that you want TempData to use Session if you're already using Session anyway, to reduce the amount of cookies used and to rely on the distributed cache when running your web application on multiple machines. To do this, simply replace the <code>AddCookieTempDataProvider</code> call with <code>AddSessionStateTempDataProvider</code>. You don't (or can't) provide any configuration to this method, because the configuration is being done when adding session support:</p>
<pre><code>services.AddControllersWithViews()
    .AddSessionStateTempDataProvider();

services.AddSession(x =&gt;
{
    x.Cookie.HttpOnly = <span class="hljs-keyword">true</span>;
    x.Cookie.SecurePolicy = CookieSecurePolicy.<span class="hljs-keyword">Always</span>;
    x.Cookie.SameSite = SameSiteMode.<span class="hljs-keyword">Strict</span>;
    x.Cookie.Name = <span class="hljs-keyword">Configuration</span>["CookieNames:Session"];
});
</code></pre><p>This is how we configured the session's cookie: </p>
<ul>
<li>HTTP Only, because we don't want any JavaScript to access the session cookie</li>
<li>SecurePolicy set to Always, because we use HTTPS all the way</li>
<li>SameSite set to Strict, because we don't want this cookie to be sent when a request is initiated by a third-party</li>
<li>And finally, we change the name to be something less obvious.</li>
</ul>
<p>Because TempData worked, and we already had Session enabled, I tried using the SessionStateTempDataProvider. Guess what?
<strong>TempData stopped working between redirects.</strong></p>
<p>Back to the investigation. What's the difference between using session to store TempData and using the original CookieTempDataProvider? Well, here's the source code of  <a target="_blank" href="https://github.com/dotnet/aspnetcore/blob/a450cb69b5e4549f5515cdb057a68771f56cefd7/src/Mvc/Mvc.ViewFeatures/src/CookieTempDataProviderOptions.cs">CookieTempDataProviderOptions</a> :</p>
<pre><code><span class="hljs-comment">// Licensed to the .NET Foundation under one or more agreements.</span>
<span class="hljs-comment">// The .NET Foundation licenses this file to you under the MIT license.</span>

<span class="hljs-keyword">using</span> System;
<span class="hljs-keyword">using</span> Microsoft.AspNetCore.Http;
<span class="hljs-keyword">using</span> Microsoft.AspNetCore.Mvc.ViewFeatures;

<span class="hljs-keyword">namespace</span> <span class="hljs-title">Microsoft.AspNetCore.Mvc</span>;

<span class="hljs-comment"><span class="hljs-doctag">///</span> <span class="hljs-doctag">&lt;summary&gt;</span></span>
<span class="hljs-comment"><span class="hljs-doctag">///</span> Provides programmatic configuration for cookies set by <span class="hljs-doctag">&lt;see cref="CookieTempDataProvider"/&gt;</span></span>
<span class="hljs-comment"><span class="hljs-doctag">///</span> <span class="hljs-doctag">&lt;/summary&gt;</span></span>
<span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">CookieTempDataProviderOptions</span>
{
    <span class="hljs-keyword">private</span> CookieBuilder _cookieBuilder = <span class="hljs-keyword">new</span> CookieBuilder
    {
        Name = CookieTempDataProvider.CookieName,
        HttpOnly = <span class="hljs-literal">true</span>,

        <span class="hljs-comment">// Check the comment on CookieBuilder below for more details</span>
        SameSite = SameSiteMode.Lax,

        <span class="hljs-comment">// This cookie has been marked as non-essential because a user could use the SessionStateTempDataProvider,</span>
        <span class="hljs-comment">// which is more common in production scenarios. Check the comment on CookieBuilder below</span>
        <span class="hljs-comment">// for more information.</span>
        IsEssential = <span class="hljs-literal">false</span>,

        <span class="hljs-comment">// Some browsers do not allow non-secure endpoints to set cookies with a 'secure' flag or overwrite cookies</span>
        <span class="hljs-comment">// whose 'secure' flag is set (http://httpwg.org/http-extensions/draft-ietf-httpbis-cookie-alone.html).</span>
        <span class="hljs-comment">// Since mixing secure and non-secure endpoints is a common scenario in applications, we are relaxing the</span>
        <span class="hljs-comment">// restriction on secure policy on some cookies by setting to 'None'. Cookies related to authentication or</span>
        <span class="hljs-comment">// authorization use a stronger policy than 'None'.</span>
        SecurePolicy = CookieSecurePolicy.None,
    };

    <span class="hljs-comment"><span class="hljs-doctag">///</span> <span class="hljs-doctag">&lt;summary&gt;</span></span>
    <span class="hljs-comment"><span class="hljs-doctag">///</span> <span class="hljs-doctag">&lt;para&gt;</span></span>
    <span class="hljs-comment"><span class="hljs-doctag">///</span> Determines the settings used to create the cookie in <span class="hljs-doctag">&lt;see cref="CookieTempDataProvider"/&gt;</span>.</span>
    <span class="hljs-comment"><span class="hljs-doctag">///</span> <span class="hljs-doctag">&lt;/para&gt;</span></span>
    <span class="hljs-comment"><span class="hljs-doctag">///</span> <span class="hljs-doctag">&lt;para&gt;</span></span>
    <span class="hljs-comment"><span class="hljs-doctag">///</span> <span class="hljs-doctag">&lt;see cref="CookieBuilder.SameSite"/&gt;</span> defaults to <span class="hljs-doctag">&lt;see cref="SameSiteMode.Lax"/&gt;</span>. Setting this to</span>
    <span class="hljs-comment"><span class="hljs-doctag">///</span> <span class="hljs-doctag">&lt;see cref="SameSiteMode.Strict"/&gt;</span> may cause browsers to not send back the cookie to the server in an</span>
    <span class="hljs-comment"><span class="hljs-doctag">///</span> OAuth login flow.</span>
    <span class="hljs-comment"><span class="hljs-doctag">///</span> <span class="hljs-doctag">&lt;see cref="CookieBuilder.SecurePolicy"/&gt;</span> defaults to <span class="hljs-doctag">&lt;see cref="CookieSecurePolicy.SameAsRequest" /&gt;</span>.</span>
    <span class="hljs-comment"><span class="hljs-doctag">///</span> <span class="hljs-doctag">&lt;see cref="CookieBuilder.HttpOnly"/&gt;</span> defaults to <span class="hljs-doctag">&lt;c&gt;</span>true<span class="hljs-doctag">&lt;/c&gt;</span>.</span>
    <span class="hljs-comment"><span class="hljs-doctag">///</span> <span class="hljs-doctag">&lt;see cref="CookieBuilder.IsEssential"/&gt;</span> defaults to <span class="hljs-doctag">&lt;c&gt;</span>false<span class="hljs-doctag">&lt;/c&gt;</span>, This property is only considered when a</span>
    <span class="hljs-comment"><span class="hljs-doctag">///</span> user opts into the CookiePolicyMiddleware. If you are using this middleware and want to use</span>
    <span class="hljs-comment"><span class="hljs-doctag">///</span> <span class="hljs-doctag">&lt;see cref="CookieTempDataProvider"/&gt;</span>, then either set this property to <span class="hljs-doctag">&lt;c&gt;</span>true<span class="hljs-doctag">&lt;/c&gt;</span> or</span>
    <span class="hljs-comment"><span class="hljs-doctag">///</span> request user consent for non-essential cookies.</span>
    <span class="hljs-comment"><span class="hljs-doctag">///</span> <span class="hljs-doctag">&lt;/para&gt;</span></span>
    <span class="hljs-comment"><span class="hljs-doctag">///</span> <span class="hljs-doctag">&lt;/summary&gt;</span></span>
    <span class="hljs-keyword">public</span> CookieBuilder Cookie
    {
        <span class="hljs-keyword">get</span> =&gt; _cookieBuilder;
        <span class="hljs-keyword">set</span> =&gt; _cookieBuilder = <span class="hljs-keyword">value</span> ?? <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> ArgumentNullException(<span class="hljs-keyword">nameof</span>(<span class="hljs-keyword">value</span>));
    }
}
</code></pre><p>Did you spot it? Apparently, there's a bug in browsers (yes, I call this a bug), that causes browsers to not send a cookie back to the server in OAuth login flows when the SameSite is set to Strict. And during OAuth login flows, a lot of redirects occur.</p>
<p>With this new knowledge, I tried relaxing the settings of the session cookie by setting <code>x.Cookie.SameSite = SameSiteMode.Lax;</code> and deployed this attempt to the server.</p>
<p>It worked! TempData survived the redirect, together with the Session! </p>
<p>So, should you find yourself in a situation where something cookie-related works locally but not remotely, and that cookie uses <code>SameSiteMode.Strict</code>? Then first try to relax it a little before trying anything else.</p>
]]></content:encoded></item><item><title><![CDATA[A way to deal with HTTP error responses]]></title><description><![CDATA[When I read Ken's blog post about an issue he had with a certain class in a project he is working on, his solution didn't sit quite right with me. I know that in Ken's case, the code couldn't be improved any further because of dependencies on other b...]]></description><link>https://wesleycabus.be/a-way-to-deal-with-http-error-responses</link><guid isPermaLink="true">https://wesleycabus.be/a-way-to-deal-with-http-error-responses</guid><category><![CDATA[C#]]></category><category><![CDATA[software architecture]]></category><dc:creator><![CDATA[Wesley Cabus]]></dc:creator><pubDate>Fri, 12 Jan 2018 23:00:00 GMT</pubDate><content:encoded><![CDATA[<p>When I read <a target="_blank" href="https://kenbonny.net/2018/01/08/constructor-fun">Ken's blog post</a> about an issue he had with a certain class in a project he is working on, his solution didn't sit quite right with me. I know that in Ken's case, the code couldn't be improved any further because of dependencies on other bits. Nothing can stop us however from having a second look at this design with a fresh codebase, right?</p>
<h1 id="v1">v1</h1>
<p>We want to wrap HTTP responses into something like <code>Response&lt;T&gt;</code>. But, you know, the web is finicky and sometimes stuff breaks somewhere, so we might get a 4xx or 5xx response back. We need to represent these cases as well.</p>
<p>So, without further ado, here is version 1:</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">Response</span>&lt;<span class="hljs-title">T</span>&gt;
{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">Response</span>(<span class="hljs-params">T <span class="hljs-keyword">value</span></span>)</span>
    {
        Value = <span class="hljs-keyword">value</span>;
        IsError = <span class="hljs-literal">false</span>;
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">Response</span>(<span class="hljs-params"><span class="hljs-keyword">string</span> error</span>)</span>
    {
        Error = error;
        IsError = <span class="hljs-literal">true</span>;
    }

    <span class="hljs-keyword">public</span> T Value { <span class="hljs-keyword">get</span>; }
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">string</span> Error { <span class="hljs-keyword">get</span>; }
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">bool</span> IsError { <span class="hljs-keyword">get</span>; }
}
</code></pre>
<p>As Ken already mentioned in his post: what if <code>T</code> is a <code>string</code>? The only way in that case to specify the correct constructor, is by using named parameters:</p>
<p><code>var valueResponse = new Response&lt;string&gt;(value: "text");</code></p>
<p>This is too confusing for any developer in my opinion: the differentiation between a successful response and an erroneous one is completely lost.</p>
<h1 id="v2">v2</h1>
<p>First of all, let's introduce contracts rather than classes to model the success and error responses. These make it easier to introduce tests in the system and allow for extensibility.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">public</span> <span class="hljs-keyword">interface</span> <span class="hljs-title">IResponse</span>&lt;<span class="hljs-keyword">out</span> <span class="hljs-title">T</span>&gt;
{
    <span class="hljs-keyword">int</span> StatusCode { <span class="hljs-keyword">get</span>; }
    T Value { <span class="hljs-keyword">get</span>; }
}

<span class="hljs-keyword">public</span> <span class="hljs-keyword">interface</span> <span class="hljs-title">IErrorResponse</span>&lt;<span class="hljs-keyword">out</span> <span class="hljs-title">T</span>&gt; : <span class="hljs-title">IResponse</span>&lt;<span class="hljs-title">T</span>&gt; 
{
    <span class="hljs-keyword">string</span> Error { <span class="hljs-keyword">get</span>; }
    <span class="hljs-keyword">string</span> OriginalData { <span class="hljs-keyword">get</span>; }
    Exception Exception { <span class="hljs-keyword">get</span>; }
    <span class="hljs-keyword">bool</span> HasException { <span class="hljs-keyword">get</span>; }
}
</code></pre>
<p>In case you're wondering why I opted for an <code>int</code> instead of <code>System.Net.HttpStatusCode</code> for the property <code>StatusCode</code>: not all status code possibilities exist in the enum, like 429 - Too Many Requests. But don't worry, the implementation will allow you to pass in HttpStatusCode's as well.</p>
<p>Let's now implement a class so we can return successful responses from an HTTP service:</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">Response</span>&lt;<span class="hljs-title">T</span>&gt; : <span class="hljs-title">IResponse</span>&lt;<span class="hljs-title">T</span>&gt; 
{
    <span class="hljs-function"><span class="hljs-keyword">internal</span> <span class="hljs-title">Response</span>(<span class="hljs-params">HttpStatusCode statusCode, T <span class="hljs-keyword">value</span></span>)
        : <span class="hljs-title">this</span>(<span class="hljs-params">(<span class="hljs-keyword">int</span></span>)statusCode, <span class="hljs-keyword">value</span>)</span>
    {
    }

    <span class="hljs-function"><span class="hljs-keyword">internal</span> <span class="hljs-title">Response</span>(<span class="hljs-params"><span class="hljs-keyword">int</span> statusCode, T <span class="hljs-keyword">value</span></span>)</span>
    {
        StatusCode = statusCode;
        Value = <span class="hljs-keyword">value</span>;
    }

    <span class="hljs-keyword">public</span> <span class="hljs-keyword">int</span> StatusCode { <span class="hljs-keyword">get</span>; }
    <span class="hljs-keyword">public</span> T Value { <span class="hljs-keyword">get</span>; }
}
</code></pre>
<p>And for an error response:</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">ErrorResponse</span>&lt;<span class="hljs-title">T</span>&gt; : <span class="hljs-title">IErrorResponse</span>&lt;<span class="hljs-title">T</span>&gt;
{
    <span class="hljs-function"><span class="hljs-keyword">internal</span> <span class="hljs-title">ErrorResponse</span>(<span class="hljs-params">HttpStatusCode statusCode, <span class="hljs-keyword">string</span> error</span>)
        : <span class="hljs-title">this</span>(<span class="hljs-params">(<span class="hljs-keyword">int</span></span>)statusCode, error)</span>
    {
    }

    <span class="hljs-function"><span class="hljs-keyword">internal</span> <span class="hljs-title">ErrorResponse</span>(<span class="hljs-params"><span class="hljs-keyword">int</span> statusCode, <span class="hljs-keyword">string</span> error</span>)</span>
    {
        StatusCode = statusCode;
        Error = error;
    }

    <span class="hljs-keyword">public</span> <span class="hljs-keyword">int</span> StatusCode { <span class="hljs-keyword">get</span>; }
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">string</span> Error { <span class="hljs-keyword">get</span>; }

    <span class="hljs-keyword">public</span> <span class="hljs-keyword">string</span> OriginalData { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">internal</span> <span class="hljs-keyword">set</span>; }
    <span class="hljs-keyword">public</span> Exception Exception { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">internal</span> <span class="hljs-keyword">set</span>; }
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">bool</span> HasException =&gt; Exception != <span class="hljs-literal">null</span>;

    T IResponse&lt;T&gt;.Value =&gt; <span class="hljs-keyword">default</span>; <span class="hljs-comment">// Needs C# 7.1</span>
}
</code></pre>
<p>That last line will hide the <code>Value</code> property - which is only interesting when the response was successfull anyway - when you are working with an instance of a class that implements <code>IErrorResponse&lt;T&gt;</code>. It will however still show up when you cast to the interface(s), but will be either <code>null</code> or the default value for a value type. Note that you could still write <code>default(T)</code>, C# 7.1 just provides a slightly shorter way.</p>
<h2 id="bringing-success-and-error-together-the-http-service">Bringing success and error together: the HTTP service</h2>
<p>When retrieving data from an HTTP service, we will either return a <code>Response&lt;T&gt;</code> when everything's OK (2xx response) and the data we get back can actually be converted back to what we expect to find (something <code>T</code>-ish). If anything else happens, we will return an <code>ErrorResponse&lt;T&gt;</code> instead, containing as much data as we can supply to the caller.</p>
<pre><code class="lang-csharp"><span class="hljs-function"><span class="hljs-keyword">protected</span> <span class="hljs-keyword">async</span> <span class="hljs-title">Task</span>&lt;<span class="hljs-title">IResponse</span>&lt;<span class="hljs-title">T</span>&gt;&gt; <span class="hljs-title">Get</span>&lt;<span class="hljs-title">T</span>&gt;(<span class="hljs-params"><span class="hljs-keyword">string</span> uri</span>)</span> 
{
    HttpResponseMessage response = <span class="hljs-literal">null</span>;
    <span class="hljs-keyword">string</span> content = <span class="hljs-literal">null</span>;

    <span class="hljs-keyword">try</span>
    {
        response = <span class="hljs-keyword">await</span> Client.GetAsync(uri)
            .ConfigureAwait(<span class="hljs-literal">false</span>); <span class="hljs-comment">// Client is a static System.Net.HttpClient instance</span>

        content = <span class="hljs-keyword">await</span> response.Content.ReadAsStringAsync()
            .ConfigureAwait(<span class="hljs-literal">false</span>);

        <span class="hljs-keyword">return</span> response.IsSuccessStatusCode ? 
            CreateResponse&lt;T&gt;(response.StatusCode, content) : 
            CreateErrorResponse&lt;T&gt;(response.StatusCode, response.ReasonPhrase, originalData: content);
    }
    <span class="hljs-keyword">catch</span> (Exception e)
    {
        <span class="hljs-keyword">return</span> CreateErrorResponse&lt;T&gt;(
            response?.StatusCode ?? HttpStatusCode.InternalServerError, 
            e.Message, 
            e,
            content);
    }
}

<span class="hljs-function"><span class="hljs-keyword">private</span> <span class="hljs-title">IResponse</span>&lt;<span class="hljs-title">T</span>&gt; <span class="hljs-title">CreateResponse</span>&lt;<span class="hljs-title">T</span>&gt;(<span class="hljs-params">HttpStatusCode statusCode, <span class="hljs-keyword">string</span> json</span>)</span>
{
    <span class="hljs-keyword">try</span>
    {
        <span class="hljs-keyword">var</span> data = JsonConvert.DeserializeObject&lt;T&gt;(json);
        <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> Response&lt;T&gt;(statusCode, data);
    }
    <span class="hljs-keyword">catch</span> (Exception e)
    {
        <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> ErrorResponse&lt;T&gt;(statusCode, <span class="hljs-string">"Couldn't deserialize the received data to the requested type."</span>)
        {
            OriginalData = json,
            Exception = e
        };
    }
}

<span class="hljs-function"><span class="hljs-keyword">private</span> <span class="hljs-title">IResponse</span>&lt;<span class="hljs-title">T</span>&gt; <span class="hljs-title">CreateErrorResponse</span>&lt;<span class="hljs-title">T</span>&gt;(<span class="hljs-params">
    HttpStatusCode statusCode, 
    <span class="hljs-keyword">string</span> error, 
    Exception exception = <span class="hljs-literal">null</span>, 
    <span class="hljs-keyword">string</span> originalData = <span class="hljs-literal">null</span></span>)</span>
{
    <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> ErrorResponse&lt;T&gt;(statusCode, error)
    {
        Exception = exception,
        OriginalData = originalData
    };
}
</code></pre>
<p>The majority of the <code>Get&lt;T&gt;</code> method should be familiar if you've ever called HTTP services using an <code>HttpClient</code> instance: </p>
<ul>
<li>We perform a GET /uri and await the response</li>
<li>We read the returned data as a string. This contains either the actual data (2xx) or information (4xx, 5xx) about what went wrong.</li>
<li>Using <code>response.IsSuccessStatusCode</code>, we check for 2xx responses. If the response was good, we call <code>CreateResponse&lt;T&gt;</code>. If not, we use <code>CreateErrorResponse&lt;T&gt;</code>.</li>
<li>In the exception handler, we call <code>CreateErrorResponse&lt;T&gt;</code> to provide an error response including the exception details.</li>
</ul>
<p>Inside the <code>CreateResponse&lt;T&gt;</code> method, we only need to keep in mind that the returned data might not be what we expect it to be, that is something that can be converted into a <code>T</code>. So when that happens, we catch the deserialization exception, and return an <code>ErrorResponse&lt;T&gt;</code> instead.
I also need to mention that, in the <a target="_blank" href="https://github.com/wcabus/response-errorresponse">full sample source code</a>, I've set a default Accept header to only accept JSON from the HTTP service. It would be rather strange to call <code>JsonConvert.DeserializeObject&lt;T&gt;</code> with XML, right?</p>
<p><strong>Update</strong></p>
<p>I used to call <code>response.EnsureSuccessStatusCode()</code> to prevent having to call <code>CreateErrorResponse&lt;T&gt;</code> twice (and that used to be a <code>new ErrorResponse&lt;T&gt;</code> line instead), but that would raise an unnecessary exception <em>and</em> return false information, because there wasn't really an exception to begin with. We just faked one for our convenience. As <a target="_blank" href="https://twitter.com/nicovermeir">Nico Vermeir</a> pointed out, not causing an exception here is far more elegant. </p>
<h2 id="inspecting-the-result">Inspecting the result</h2>
<p>We now have a way to represent success and error responses, and an HTTP service to get both of these. How can we now call that service and test if we have an error or not?</p>
<p>In the sample, I've provided a dummy CustomerService that uses the HttpService class:</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">CustomerService</span> : <span class="hljs-title">HttpService</span>
{
    <span class="hljs-keyword">public</span> Task&lt;IResponse&lt;Customer&gt;&gt; GetCustomerById(<span class="hljs-keyword">int</span> id)
    {
        <span class="hljs-keyword">return</span> Get&lt;Customer&gt;(<span class="hljs-string">$"https://api.myapp.local/customers/<span class="hljs-subst">{id}</span>"</span>);
    }
}
</code></pre>
<p>When we call that service, we can inspect the response:</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">var</span> client = <span class="hljs-keyword">new</span> CustomerService();
<span class="hljs-keyword">var</span> response = <span class="hljs-keyword">await</span> client.GetCustomerById(<span class="hljs-number">404</span>);
<span class="hljs-keyword">if</span> (response <span class="hljs-keyword">is</span> IErrorResponse&lt;Customer&gt; error)
{
    Console.ForegroundColor = ConsoleColor.DarkRed;
    Console.WriteLine(<span class="hljs-string">$"<span class="hljs-subst">{error.StatusCode}</span> - <span class="hljs-subst">{error.Error}</span>"</span>);
    <span class="hljs-keyword">if</span> (error.HasException)
    {
        Console.WriteLine(error.Exception);
    }

    Console.ResetColor();

    <span class="hljs-keyword">return</span>;
}

Console.WriteLine(response.Value);
</code></pre>
<p>Using a C# 7.0 feature, pattern matching, we can easily check if <code>response</code> is in fact an <code>IErrorResponse&lt;Customer&gt;</code>, rather than a successful response. If it is, the <code>error</code> instance is immediately available inside the if-block.</p>
<p>If the call to <code>GetCustomerById</code> worked just fine, we can access <code>response.Value</code> just like we would expect.</p>
<h2 id="wrapping-it-up">Wrapping it up</h2>
<p>So, instead of dealing with both success and error in one class, I've provided two separate contracts to model them. Because <code>IErrorResponse&lt;T&gt;</code> implements <code>IResponse&lt;T&gt;</code>, we can use the latter as our base return type for all HTTP related methods. 
And thanks to pattern matching, it is now easier than ever to quickly check if the returned response is in fact an error.</p>
<p>Full sample code can be found on <a target="_blank" href="https://github.com/wcabus/response-errorresponse">GitHub</a>. Improvements and further discussions are welcome!</p>
]]></content:encoded></item><item><title><![CDATA[Debugging 101]]></title><description><![CDATA[Welcome back for my second post about debugging! In this post, I'll give you an overview of the basic capabilities of the debugger in Visual Studio 2015, and add a few tips and tricks to take your debugging skills to the next level. We will not delve...]]></description><link>https://wesleycabus.be/debugging-101</link><guid isPermaLink="true">https://wesleycabus.be/debugging-101</guid><category><![CDATA[debugging]]></category><category><![CDATA[Tutorial]]></category><dc:creator><![CDATA[Wesley Cabus]]></dc:creator><pubDate>Wed, 18 Jan 2017 23:00:00 GMT</pubDate><content:encoded><![CDATA[<p>Welcome back for my second post about debugging! In this post, I'll give you an overview of the basic capabilities of the debugger in Visual Studio 2015, and add a few tips and tricks to take your debugging skills to the next level. We will not delve into the more advanced topics yet though, like debugging multi-threaded applications for example: those topics are being reserved for later posts (either by <a href="https://blog.maartenballiauw.be" target="_blank">Maarten</a> or myself) because they are too large to handle all at once.</p>
<p>Now, before you think to skip this post because you've been programming for some years, I do suggest to glance over this post: you might see something you didn't know, or didn't see the benefit of that debugger feature. If you already knew everything I've written in this post, then you are awesome! And should you know a neat trick which I didn't cover, then don't hesitate to leave a comment :)</p>
<p>Let's start with the basics, shall we?</p>
<h1 id="stop-hammer-time">Stop! Hammer Time!</h1>
<p>When you debug code to find out where exactly things are going wrong, you'll probably have an idea where to start searching in the code base:</p>
<ul>
<li>You just wrote some new classes/methods and things started behaving not quite as expected.</li>
<li>A unit test fails suddenly.</li>
<li>An exception has been thrown and you can see where it originates using the stack trace.</li>
</ul>
<p>So, you have an idea where to start digging. The obvious thing to do then, is to tell the debugger to stop running the code at that point in the source.
This is a <em>breakpoint</em>, which you can set using the <strong>Debug &gt; Toggle Breakpoint</strong> menu item or its default shortcut key <strong>F9</strong>. Visual Studio, and many other IDE's, typically indicates a breakpoint with a red circle in front of the line of code, optionally also changing the colorization of the code:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1620566252955/c8sN0aEGE.png" alt="Setting a breakpoint" /></p>
<p>When we run this code, Visual Studio will stop executing the application right before executing the line of code were we added the breakpoint. You will also see a yellow arrow pointing at that line. Think of the yellow arrow as the <a href="https://en.wikipedia.org/wiki/Program_counter" target="_blank">instruction pointer (or program counter)</a> for your code:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1620566396172/cMilO_nMG.png" alt="Breakpoint has been hit" /></p>
<p>At this moment, you can start inspecting your application state using the different windows provided by Visual Studio. These are the first few views which can be useful when debugging, and all of these can be found in the menu <strong>Debug &gt; Windows</strong> while the debugger is active:</p>
<ul>
<li>Watch: you can have four different watch views. These views allow you to inspect variables, fields, properties, collections, methods, and so on. You'll see the value and the data type listed next to the watch entry.</li>
<li>Autos: this is a special watch window, showing the result of the current and previous lines of code if it can.</li>
<li>Locals: this is also a special watch window, displaying all variables and method parameters in the current method or lambda expression. However, it doesn't show properties or fields who are being referenced in that method or lambda expression.</li>
<li>Call Stack: this window shows the execution path up until now per executed method. Because not all of the code is managed code (written using the .NET CLR), or when you are missing <em>debug symbols</em>, you'll see some entries appearing as [External Code]: this can either be a 3rd party library you're using but Visual Studio couldn't find the (correct) <em>debug symbols</em> or <em>PDB</em> files for that library, or it could be unmanaged code - things Windows needs to do to start your .NET application, creating an AppDomain for instance.
We'll cover the Call Stack window later in this post more in depth.</li>
</ul>
<p>In this code example, you've obviously already seen what will go wrong: <a href="https://en.wikipedia.org/wiki/Phrases_from_The_Hitchhiker%27s_Guide_to_the_Galaxy#The_number_42" target="_blank">as awesome a number 42 might be</a>, dividing it by zero just doesn't work in this universe. Before evaluating the next line of code however, you can inspect what would happen by adding <code>value / 0</code> in the Watch 1 window, either by selecting the statement, right-clicking it and select the <strong>Add Watch</strong> menu item, or by pasting/typing the statement in a row in the Watch window:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1620566506918/463Iyv0jj.png" alt="Inspect a value in the Watch 1 window" /></p>
<p>You can now stop the debugger (<strong>Debug &gt; Stop Debugging</strong>, <strong>SHIFT+F5</strong> or the <strong>Stop Debugging</strong> button in the toolbar) to fix the bad code, or you can even change it while the debugger is active:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1620566840243/PHwUK6PEAs.gif" alt="Edit and continue" /></p>
<h1 id="stop-when-its-hammer-time">Stop! When it's hammer time!</h1>
<p>This is, however, the absolute basics of debugging. We can do better than this! One improvement lies in controlling <em>when</em> the debugger actually decides to stop when it arrives at a breakpoint.
You can disable any breakpoint, without removing it, by hovering over it and pressing the disable button. Other options are to right-click and select <strong>Disable Breakpoint</strong> or to press the default shortcut <strong>Ctrl+F9</strong>. This is an easy way of controlling a method where the application passes through several times, but where you don't want to stop continuously. But it's not ideal, and we have better tools in our toolbox.</p>
<p>A second tool, is to enable breakpoint conditions. Breakpoint conditions allows us to only break when certain things are true:</p>
<ul>
<li>When <em>value</em> equals 42, this is a conditional expression.</li>
<li>When we hit this breakpoint for the n-th time, this is a hit count expression.</li>
<li>When we run this code on a certain machine, in a certain process or thread: a filter.</li>
</ul>
<p>To get to these options, you can hover over the breakpoint and click the cog wheel icon (labeled <strong>Settings...</strong>) or right-click and select the <strong>Conditions...</strong> menu item.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1620567032324/Z44BuwcPN.png" alt="Breakpoint conditions" /></p>
<p>Visual Studio will now only stop running our application when the value of <em>divisor</em> equals 0. Neat!</p>
<p>As you can see in the image above, we can also add Actions to a breakpoint: for example, to log information to the Output window every time we pass the breakpoint. Ironically, this is how I used to debug when I started out coding: putting PRINT statements all over the place, displaying the values of variables to know what was going on.</p>
<h1 id="stop-hammernotfoundexception">Stop! HammerNotFoundException!</h1>
<p>Another nifty trick to know, especially when having to fix a hot issue in an unknown code base, is by setting breakpoints on (un)handled exceptions. In the example I've been using, I can declare - inside Visual Studio - that I want the debugger to break whenever the DivideByZeroException is being thrown for example, even if this exceptions has been caught in the code. This enables you to stop executing the application when an exception arises, instead of when it might get rethrown in a main thread.
You can reach these awesome bits in the Exception Settings window, through the <strong>Debug &gt; Windows &gt; Exception Settings</strong> menu item or its default shortcut <strong>CTRL+ALT+E</strong>:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1620567105876/iIIlgcAKa.png" alt="Debugger - Exception Settings" /></p>
<p>By default, you can choose to break on all unlisted exceptions, to break on your own exception types or those used by 3rd party libraries. That possibility is immediately followed by an extensive list of default exception types provided in the CLR, like the well-known System.NullReferenceException. You can also add specific missing exception types, by selecting the line <em>Common Language Runtime Exceptions</em> and hitting the Add button (indicated with the plus sign).
When you right-click on an exception, you can choose an additional option: <em>Continue when unhandled in user code</em>. When you activate this, the debugger will not stop on that exception in your codebase if the exception is handled by the consumer of your code.</p>
<h1 id="the-call-stack">The Call Stack</h1>
<p>I did promise a bit about the Call Stack window, didn't I? Well, here goes!
Whenever the debugger stops running your application, the Call Stack window will show you the list of actions/methods/etc. that led up to the current point of execution:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1620567205247/m7YTniN7p.png" alt="The Call Stack" /></p>
<p>Now, the [External Code] section is where things could get interesting. Basically, this is anything that is not in your code base, like native Windows API's, .NET CLR stuff, 3rd party libraries: you name it. You can however opt in to see what's behind the covers, by right clicking in the Call Stack window and enabling the option called <strong>Show External Code</strong>:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1620567268224/qvGm7gfT2.png" alt="Enabling Show External Code" /></p>
<p>When you double click on an entry shown in black in the Call Stack (or right click and choose <strong>Switch to Frame</strong>), you can jump back and forth through the Call Stack, inspecting the flow of your application up to where it was interrupted by - for example - a breakpoint, including the state of each frame. This means that you can inspect all variables and fields for each step in the Call Stack, which can give you a <em>lot</em> more insight when trying to pinpoint where things might've gone wrong:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1620567297064/dc2R9Dh5D.png" alt="Traversing through the call stack" /></p>
<p>Now, you can also try to do this for code outside your code base, displayed as gray entries. Try clicking on a gray line in the Call Stack, and you'll be presented a window looking somewhat like this, depending on your settings:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1620567353598/aIoTE6BNJ.png" alt="Symbols not found" /></p>
<p>Basically, Visual Studio is telling you that it can't display any source code for the frame you've selected to inspect, but it can try to load <em>debug symbols</em> (or PDB files) which will help in showing some degree of information. As a last resort, you can try to click the <strong>View disassembly</strong> link, which will show you what's going on at the most basic of levels. You can, of course, add your own symbol servers. This can be convenient when you have <a href="http://docs.myget.org/docs/reference/symbols" target="_blank">a custom package feed with its own debug symbol source</a>, or when you want to <a href="https://www.jetbrains.com/help/decompiler/2016.3/Using_product_as_a_Symbol_Server.html" target="_blank">build debug symbols on the fly using DotPeek</a> for example. Check out these two links to learn more about these possibilities, they will definitely help you when dealing with strange behavior in 3rd party libraries!</p>
<p>There are much more features hidden inside the Debug menu, but I'm going to save these for another post, where we will dive into more advanced concepts. Stay tuned!</p>
]]></content:encoded></item><item><title><![CDATA[The History of Debugging: Part 1]]></title><description><![CDATA[Disclaimer: there might never be a Part 2.
Together with Maarten (who already has written some content concerning debugging and monitoring software), we're going to write some posts about the concept of debugging code. And to introduce the topic, why...]]></description><link>https://wesleycabus.be/the-history-of-debugging-part-1</link><guid isPermaLink="true">https://wesleycabus.be/the-history-of-debugging-part-1</guid><category><![CDATA[debugging]]></category><category><![CDATA[history]]></category><dc:creator><![CDATA[Wesley Cabus]]></dc:creator><pubDate>Mon, 07 Nov 2016 23:00:00 GMT</pubDate><content:encoded><![CDATA[<p>Disclaimer: there might never be <a href="http://www.imdb.com/title/tt0082517/" target="_blank">a Part 2</a>.</p>
<p>Together with <a href="https://blog.maartenballiauw.be/" target="_blank">Maarten</a> (who already has <a href="https://blog.maartenballiauw.be/post/2016/10/19/making-net-code-less-allocatey-garbage-collector.html" target="_blank">written some content</a> concerning debugging and monitoring software), we're going to write some posts about the concept of debugging code. And to introduce the topic, why not start with a little bit of (mostly personal) history on the matter?</p>

<h1 id="eniac">ENIAC</h1>
<p>It's hard to imagine nowadays, but writing software wasn't always literally writing: on the <a href="https://en.wikipedia.org/wiki/ENIAC" target="_blank">ENIAC</a> i.e., the programmers had to make physical connections between the different components, replacing burnt out vacuum tubes as they progressed. They did actually write the program on paper first though, and did their very best to run through it <em>step by step</em> before starting to program the actual computer. And even then, they went through the program again: even the ENIAC already supported <em>step-through debugging</em>!</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1620567582796/QFV6Jjvfy.jpeg" alt="ENIAC" /></p>
<h1 id="my-first-program-and-qbasic">My First Program and QBASIC</h1>
<p>When I was in the Sixth grade, at the age of eleven, I got the chance to learn to program in QBASIC on a 386 PC, running MS-DOS 6.0, during breaks. Well, that and the occasional <a href="https://en.wikipedia.org/wiki/Out_Run" target="_blank">Sega OutRun</a> <a href="https://www.youtube.com/watch?v=Y0qFU39Y-M0" target="_blank">game</a>.
But programming really caught my interest and I quickly went through the assignments my teacher had created. Meanwhile, we got a PC at home, so I could continue learning to program. In the end, I'd written several game clones like <a href="https://en.wikipedia.org/wiki/Breakout_(video_game)" target="_blank">Breakout</a>, Tetris, etc.</p><p></p>
<p>My programming skills, however, were quite limited: it took me a while to figure out that I could use subroutines (GOSUB) instead of line numbers and the now dreaded GOTO. And as far as debugging was concerned, I was using the oldest trick in the book: a lot of PRINT statements to know the value of certain variables at specific steps in the code. I'm not kidding when I say that I only recently found out that QBASIC supported <em>step-through debugging</em> and setting <em>breakpoints</em> in code: nobody told me these things when I started programming and I didn't know English well enough to figure this out myself.</p>
<p>Moral of the story so far: you will learn to appreciate any help the debugger tools provide once you had to resort to printing variable values.</p>
<h1>Windows 3.11 and Visual Basic 4.0</h1>
<p>As I got older, I stumbled upon VB4 which allowed me to create software with Forms. My own Windows in Windows! And because I started getting English class at school, I also understood more about the options I had to create software. Finally I discovered things like <em>breakpoints</em>, <em>watches</em>, <em>step-through debugging</em> and Visual Basics way of <em>error handling</em>. Aside from games, I could also start writing more useful software for family and friends.<br />
The summum? Writing a new UI which emulated the Windows 95 look and feel to convince my dad to upgrade the PC (it needed 8 megs of RAM instead of 4) and to buy that shiny Windows 95 upgrade.</p>
<h1>VB6, C/C++, PHP, ...</h1>
<p>I also upgraded to Visual Basic 97, then 6.0, started to dabble in C/C++ and wrote my first web applications in PHP. That was a step back in time really. Sure, you could run a <a href="https://en.wikipedia.org/wiki/LAMP_(software_bundle)#WAMP" target="_blank">WAMP</a> server locally to test your code, but you couldn't <em>attach a debugger</em> to that server to debug the code as you went through the application (I'm talking about PHP3/4 here, way before the Zend era). So instead, I had to rely on echoing stuff back into my web pages or logging it and looking at the log files. Or even worse, stop the code from processing at all using <code>die()</code> statements, which typically happened when you couldn't connect to the MySQL database.</p>
<p>Maybe we are spoiled today, with the capabilities offered by the different debugger tools available. But then again, are we using them efficiently? Find out in my next post in this series!</p>
]]></content:encoded></item><item><title><![CDATA[SLD Injection, it's a thing]]></title><description><![CDATA[I'm in the middle of preparing a session about security, and one topic you regularly bump into when thinking about security and writing code is SQL Injection. Although it is the year 2016, there are still people writing code which is vulnerable again...]]></description><link>https://wesleycabus.be/sld-injection-its-a-thing</link><guid isPermaLink="true">https://wesleycabus.be/sld-injection-its-a-thing</guid><category><![CDATA[C#]]></category><category><![CDATA[Security]]></category><dc:creator><![CDATA[Wesley Cabus]]></dc:creator><pubDate>Tue, 05 Apr 2016 13:45:30 GMT</pubDate><content:encoded><![CDATA[<p>I'm in the middle of preparing a session about security, and one topic you regularly bump into when thinking about security and writing code is SQL Injection. Although it is the year 2016, there are still people writing code which is vulnerable against SQL Injection.</p>
<p>But I'm not going to focus on SQL Injection here, I'm going to take it one step further. If you want to read up on SQL Injection, <a href="http://www.bing.com/search?q=sql+injection" target="_blank">Bing</a>/<a href="https://www.google.be/#q=sql+injection" target="_blank">Google</a> is your friend. Or just take a look at good old <a href="http://bobby-tables.com/" target="_blank">Bobby Tables</a>.</p>
<p>People often think: "It's called SQL Injection, but I'm not using SQL here, so I'm safe."</p>
<p>Wrong.</p>
<p>From the moment you're using any type of query or filtering language construct, you can introduce some form of SQL Injection in your code:</p>
<ul>
<li>Using (n)Hibernate with <a href="https://docs.jboss.org/hibernate/orm/3.3/reference/en/html/queryhql.html" target="_blank">HQL</a>? Are you using parameters in those queries <a href="http://blog.h3xstream.com/2014/02/hql-for-pentesters.html" target="_blank">or not</a>?</li>
<li>You're using Azure Table Storage or another NoSQL DB. <a href="https://securityintelligence.com/does-nosql-equal-no-injection/" target="_blank">But does NoSQL mean No SQL Injection</a>?</li>
</ul>
<p>Another fun example uses the <a href="https://www.nuget.org/packages/System.Linq.Dynamic/" target="_blank">System.Linq.Dynamic</a> NuGet package. This little gem allows you to use string expressions to filter on IEnumerable's. And because it makes our developer life easier, we could use this to filter data in a Web API, for example. Take a look at this piece of code:</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">public</span> <span class="hljs-keyword">async</span> Task&lt;IEnumerable&lt;User&gt;&gt; GetUsersAsync(<span class="hljs-keyword">string</span> filter)
{
    <span class="hljs-comment">// Lets say the current user can only access data with odd ID's</span>
    <span class="hljs-keyword">var</span> fullFilter = <span class="hljs-string">"(id % 2) = 1"</span>;

    <span class="hljs-keyword">if</span> (!<span class="hljs-keyword">string</span>.IsNullOrEmpty(filter))
    {
        fullFilter += <span class="hljs-string">$" &amp;&amp; <span class="hljs-subst">{filter}</span>"</span>;
    }

    <span class="hljs-keyword">return</span> (<span class="hljs-keyword">await</span> DbContext.Users.ToListAsync()).Where(fullFilter);
}
</code></pre>
<p>Yes, I know this is not the best code because you're fetching all users from the database and then you reduce the result set, but bear with me. I'm making a statement here. Besides, this kind of code is still being written in production as well!</p>
<p>As you can see, you're applying a filter to a list of User instances using System.Linq.Dynamic. That filter could be, for example, this:</p>
<p><code>"name.StartsWith(\"n\")"</code></p>
<p>This would reduce the results down to all users with an odd ID and where the surname starts with "n". But someone could circumvent our fixed "odd ID" filter part, which would ignore our little security measure, by changing the filter a bit:</p>
<p><code>1 = 1 || 1 = 1</code></p>
<p>This filter value would make fullFilter look like this:</p>
<p><code>(id % 2) = 1 &amp;&amp; 1 = 1 || 1 = 1</code></p>
<p>Because we're missing parentheses around the user filter part, the ID filter will be ignored. One solution could be to add these parentheses.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">public</span> <span class="hljs-keyword">async</span> Task&lt;IEnumerable&lt;User&gt;&gt; GetUsersAsync(<span class="hljs-keyword">string</span> filter)
{
    <span class="hljs-comment">// Lets say the current user can only access data with odd ID's</span>
    <span class="hljs-keyword">var</span> fullFilter = <span class="hljs-string">"(id % 2) = 1"</span>;

    <span class="hljs-keyword">if</span> (!<span class="hljs-keyword">string</span>.IsNullOrEmpty(filter))
    {
        fullFilter += <span class="hljs-string">$" &amp;&amp; (<span class="hljs-subst">{filter}</span>)"</span>;
    }

    <span class="hljs-keyword">return</span> (<span class="hljs-keyword">await</span> DbContext.Users.ToListAsync()).Where(fullFilter);
}
</code></pre>
<p>Actually, you could solve that problem by moving the fixed filter part. That way, no matter what your user is requesting, he or she can't get by the fixed filter anymore:</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">public</span> <span class="hljs-keyword">async</span> Task&lt;IEnumerable&lt;User&gt;&gt; GetUsersAsync(<span class="hljs-keyword">string</span> filter)
{
   <span class="hljs-comment">// Lets say the current user can only access data with odd ID's</span>
   <span class="hljs-keyword">var</span> query = DbContext.Users.Where(x =&gt; x.Id % <span class="hljs-number">2</span> == <span class="hljs-number">1</span>);

   <span class="hljs-keyword">if</span> (!<span class="hljs-keyword">string</span>.IsNullOrEmpty(filter))
   {
      <span class="hljs-keyword">return</span> (<span class="hljs-keyword">await</span> query.ToListAsync()).Where(filter);
   }

   <span class="hljs-keyword">return</span> <span class="hljs-keyword">await</span> query.ToListAsync();
}
</code></pre>
<p>And to complete the story, you can look at using parameterized queries, <a href="http://dynamiclinq.azurewebsites.net/GettingStarted" target="_blank">which is also supported by System.Linq.Dynamic</a>. Using parameters in your filter would take away some of the filtering power from the consumer of your API, but you could reintroduce that power by defining your own filters. This example shows a <strong>basic attempt</strong> at implementing this:</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">public</span> <span class="hljs-keyword">async</span> Task&lt;IEnumerable&lt;User&gt;&gt; GetUsersAsync(<span class="hljs-keyword">string</span> filter)
{
    <span class="hljs-comment">// Lets say the current user can only access data with odd ID's</span>
    <span class="hljs-keyword">var</span> query = DbContext.Users.Where(x =&gt; x.Id % <span class="hljs-number">2</span> == <span class="hljs-number">1</span>);

    <span class="hljs-keyword">if</span> (!<span class="hljs-keyword">string</span>.IsNullOrEmpty(filter))
    {
        <span class="hljs-keyword">var</span> parsed = ParseFilter(filter);
        <span class="hljs-keyword">return</span> (<span class="hljs-keyword">await</span> query.ToListAsync()).Where(parsed.Filter, parsed.ParamList.ToArray());
    }

    <span class="hljs-keyword">return</span> <span class="hljs-keyword">await</span> query.ToListAsync();
}

<span class="hljs-function"><span class="hljs-keyword">private</span> ParsedFilter <span class="hljs-title">ParseFilter</span>(<span class="hljs-params"><span class="hljs-keyword">string</span> filter</span>)</span>
{
    <span class="hljs-keyword">var</span> newFilter = <span class="hljs-keyword">new</span> StringBuilder(filter.Length);
    <span class="hljs-keyword">var</span> paramList = <span class="hljs-keyword">new</span> List&lt;<span class="hljs-keyword">object</span>&gt;();

    <span class="hljs-keyword">var</span> filterParts = filter.Split(<span class="hljs-keyword">new</span>[] { <span class="hljs-string">' '</span> }, StringSplitOptions.RemoveEmptyEntries);
    <span class="hljs-keyword">var</span> i = <span class="hljs-number">0</span>;
    <span class="hljs-keyword">var</span> paramIndex = <span class="hljs-number">0</span>;

    <span class="hljs-keyword">while</span> (i &lt; filterParts.Length)
    {
        <span class="hljs-keyword">string</span> @operator = <span class="hljs-string">""</span>, property = <span class="hljs-string">""</span>;
        <span class="hljs-keyword">object</span> literal = <span class="hljs-literal">null</span>;
        <span class="hljs-keyword">var</span> parts = <span class="hljs-keyword">new</span>[] {filterParts[i++], filterParts[i++], filterParts[i++]};

        <span class="hljs-keyword">foreach</span> (<span class="hljs-keyword">var</span> part <span class="hljs-keyword">in</span> parts)
        {
            <span class="hljs-keyword">if</span> (IsStringLiteral(part))
            {
                literal = part.Substring(<span class="hljs-number">1</span>, part.Length - <span class="hljs-number">2</span>);
                <span class="hljs-keyword">continue</span>;
            }

            <span class="hljs-keyword">if</span> (IsBoolLiteral(part))
            {
                literal = <span class="hljs-keyword">bool</span>.Parse(part);
                <span class="hljs-keyword">continue</span>;
            }

            <span class="hljs-comment">// No support for float/double/decimal/... yet</span>
            <span class="hljs-keyword">if</span> (IsNumericLiteral(part))
            {
                literal = <span class="hljs-keyword">int</span>.Parse(part);
                <span class="hljs-keyword">continue</span>;
            }

            <span class="hljs-keyword">var</span> propOrOp = part.ToLowerInvariant();
            <span class="hljs-keyword">if</span> (IsOperator(propOrOp))
            {
                @operator = propOrOp;
                <span class="hljs-keyword">continue</span>;
            }

            property = propOrOp;
        }

        newFilter.Append(UseOperator(@operator, property, paramIndex++));
        paramList.Add(literal);

        <span class="hljs-comment">// We only support "and" and "or". No ! or () allowed.</span>
        <span class="hljs-keyword">if</span> (i &lt; filterParts.Length)
        {
            newFilter.Append(<span class="hljs-keyword">string</span>.Equals(filterParts[i++], <span class="hljs-string">"and"</span>, StringComparison.OrdinalIgnoreCase) ? <span class="hljs-string">" &amp;amp;&amp;amp; "</span> : <span class="hljs-string">" || "</span>);
        }
    }

    <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> ParsedFilter(newFilter.ToString(), paramList);
}

<span class="hljs-function"><span class="hljs-keyword">private</span> <span class="hljs-keyword">bool</span> <span class="hljs-title">IsNumericLiteral</span>(<span class="hljs-params"><span class="hljs-keyword">string</span> literal</span>)</span>
{
    <span class="hljs-keyword">var</span> rxNumeric = <span class="hljs-keyword">new</span> Regex(<span class="hljs-string">@"^-?\d+(,\d+)*(\.\d+(e\d+)?)?$"</span>);
    <span class="hljs-keyword">return</span> rxNumeric.IsMatch(literal);
}

<span class="hljs-function"><span class="hljs-keyword">private</span> <span class="hljs-keyword">bool</span> <span class="hljs-title">IsBoolLiteral</span>(<span class="hljs-params"><span class="hljs-keyword">string</span> literal</span>)</span>
{
    <span class="hljs-keyword">return</span> <span class="hljs-keyword">string</span>.Equals(literal, <span class="hljs-string">"true"</span>, StringComparison.OrdinalIgnoreCase) ||
           <span class="hljs-keyword">string</span>.Equals(literal, <span class="hljs-string">"false"</span>, StringComparison.OrdinalIgnoreCase);
}

<span class="hljs-function"><span class="hljs-keyword">private</span> <span class="hljs-keyword">bool</span> <span class="hljs-title">IsStringLiteral</span>(<span class="hljs-params"><span class="hljs-keyword">string</span> literal</span>)</span>
{
    <span class="hljs-keyword">return</span> literal.StartsWith(<span class="hljs-string">"\""</span>, StringComparison.Ordinal) &amp;&amp;
           literal.EndsWith(<span class="hljs-string">"\""</span>, StringComparison.Ordinal);
}

<span class="hljs-function"><span class="hljs-keyword">private</span> <span class="hljs-keyword">bool</span> <span class="hljs-title">IsOperator</span>(<span class="hljs-params"><span class="hljs-keyword">string</span> @<span class="hljs-keyword">operator</span></span>)</span>
{
    <span class="hljs-keyword">switch</span> (@operator)
    {
        <span class="hljs-keyword">case</span> <span class="hljs-string">"eq"</span>:
        <span class="hljs-keyword">case</span> <span class="hljs-string">"ne"</span>:
        <span class="hljs-keyword">case</span> <span class="hljs-string">"lt"</span>:
        <span class="hljs-keyword">case</span> <span class="hljs-string">"le"</span>:
        <span class="hljs-keyword">case</span> <span class="hljs-string">"gt"</span>:
        <span class="hljs-keyword">case</span> <span class="hljs-string">"ge"</span>:
        <span class="hljs-keyword">case</span> <span class="hljs-string">"sw"</span>:
        <span class="hljs-keyword">case</span> <span class="hljs-string">"ew"</span>:
        <span class="hljs-keyword">case</span> <span class="hljs-string">"co"</span>:
            <span class="hljs-keyword">return</span> <span class="hljs-literal">true</span>;
    }

    <span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>;
}

<span class="hljs-function"><span class="hljs-keyword">private</span> <span class="hljs-keyword">string</span> <span class="hljs-title">UseOperator</span>(<span class="hljs-params"><span class="hljs-keyword">string</span> @<span class="hljs-keyword">operator</span>, <span class="hljs-keyword">string</span> property, <span class="hljs-keyword">int</span> paramIndex</span>)</span>
{
    <span class="hljs-keyword">switch</span> (@operator)
    {
        <span class="hljs-keyword">case</span> <span class="hljs-string">"eq"</span>:
            <span class="hljs-keyword">return</span> <span class="hljs-string">$"<span class="hljs-subst">{property}</span> = @<span class="hljs-subst">{paramIndex}</span>"</span>;
        <span class="hljs-keyword">case</span> <span class="hljs-string">"ne"</span>:
            <span class="hljs-keyword">return</span> <span class="hljs-string">$"<span class="hljs-subst">{property}</span> != @<span class="hljs-subst">{paramIndex}</span>"</span>;
        <span class="hljs-keyword">case</span> <span class="hljs-string">"lt"</span>:
            <span class="hljs-keyword">return</span> <span class="hljs-string">$"<span class="hljs-subst">{property}</span> &lt; @<span class="hljs-subst">{paramIndex}</span>"</span>;
        <span class="hljs-keyword">case</span> <span class="hljs-string">"le"</span>:
            <span class="hljs-keyword">return</span> <span class="hljs-string">$"<span class="hljs-subst">{property}</span> &lt;= @<span class="hljs-subst">{paramIndex}</span>"</span>;
        <span class="hljs-keyword">case</span> <span class="hljs-string">"gt"</span>:
            <span class="hljs-keyword">return</span> <span class="hljs-string">$"<span class="hljs-subst">{property}</span> &gt; @<span class="hljs-subst">{paramIndex}</span>"</span>;
        <span class="hljs-keyword">case</span> <span class="hljs-string">"ge"</span>:
            <span class="hljs-keyword">return</span> <span class="hljs-string">$"<span class="hljs-subst">{property}</span> &gt;= @<span class="hljs-subst">{paramIndex}</span>"</span>;
        <span class="hljs-keyword">case</span> <span class="hljs-string">"sw"</span>:
            <span class="hljs-keyword">return</span> <span class="hljs-string">$"<span class="hljs-subst">{property}</span>.StartsWith(@<span class="hljs-subst">{paramIndex}</span>)"</span>;
        <span class="hljs-keyword">case</span> <span class="hljs-string">"ew"</span>:
            <span class="hljs-keyword">return</span> <span class="hljs-string">$"<span class="hljs-subst">{property}</span>.EndsWith(@<span class="hljs-subst">{paramIndex}</span>)"</span>;
        <span class="hljs-keyword">case</span> <span class="hljs-string">"co"</span>:
            <span class="hljs-keyword">return</span> <span class="hljs-string">$"<span class="hljs-subst">{property}</span>.Contains(@<span class="hljs-subst">{paramIndex}</span>)"</span>;
    }

    <span class="hljs-keyword">return</span> <span class="hljs-string">""</span>;
}

<span class="hljs-keyword">private</span> <span class="hljs-keyword">struct</span> ParsedFilter
{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">ParsedFilter</span>(<span class="hljs-params"><span class="hljs-keyword">string</span> filter, IEnumerable&lt;<span class="hljs-keyword">object</span>&gt; paramList</span>)</span>
    {
        Filter = filter;
        ParamList = paramList;
    }

    <span class="hljs-keyword">public</span> <span class="hljs-keyword">string</span> Filter { <span class="hljs-keyword">get</span>; }
    <span class="hljs-keyword">public</span> IEnumerable&lt;<span class="hljs-keyword">object</span>&gt; ParamList { <span class="hljs-keyword">get</span>; }
}
</code></pre>
]]></content:encoded></item><item><title><![CDATA[CSP: we're not there, yet.]]></title><description><![CDATA[CSP, or Content Security Policy, is an added layer of security that helps to detect and mitigate certain types of attacks, including Cross-Site Scripting (XSS) and data injection attacks. In short, you can add this policy using either a <meta> tag or...]]></description><link>https://wesleycabus.be/csp-were-not-there-yet</link><guid isPermaLink="true">https://wesleycabus.be/csp-were-not-there-yet</guid><category><![CDATA[ASP.NET]]></category><category><![CDATA[Security]]></category><dc:creator><![CDATA[Wesley Cabus]]></dc:creator><pubDate>Mon, 26 Oct 2015 23:00:00 GMT</pubDate><content:encoded><![CDATA[<p>CSP, or Content Security Policy, is an added layer of security that helps to detect and mitigate certain types of attacks, including Cross-Site Scripting (XSS) and data injection attacks. In short, you can add this policy using either a <code>&lt;meta&gt;</code> tag or by setting additional headers in your HTTP response, and using the policy you'll limit the origins for resources for that HTTP request. For example:</p>
<ul>
<li><code>script-src 'self'</code> allows loading scripts from the current domain</li>
<li><code>child-src https://youtube.com</code> allows the use of <code>&lt;iframe&gt;</code> tags pointing towards YouTube</li>
<li><code>style-src 'self' https://maxcdn.bootstrapcdn.com</code> allows loading CSS files from the current source and from a CDN.</li>
</ul>
<p>If you want to read up on CSP, I suggest heading over to <a target="_blank" href="http://www.html5rocks.com/en/tutorials/security/content-security-policy/">http://www.html5rocks.com/en/tutorials/security/content-security-policy/</a>.</p>
<p>Now, I was trying out some things concerning CSP and inline scripts. You could add 'unsafe-inline' to the script-src source list to allow all inline scripting (except eval and other bad stuff, you need 'unsafe-eval' in that case), but that is exactly what you would want to avoid. Instead, you can opt to do one of these things:</p>
<ol>
<li>Move all inline JavaScript into .js files and load them using <code>&lt;script src=""&gt;&lt;/script&gt;</code> tags, while adding 'self' to script-src if that wasn't already the case. The easiest solution, but not always possible.</li>
<li>Generate a nonce for each inline script. A nonce means: a unique and hard to predict stream of bytes, different for each script, each page <strong>and</strong> each request!
A nonce could be base64 encoded and look like <em>RJ6bGjm5EO/X8pImZjvjeAexFVei9IvzNFCGw5lQUa0=</em>
You would need to add that nonce to the script using the nonce attribute, and also to the script-src source list using 'nonce-RJ6bGjm5EO/X8pImZjvjeAexFVei9IvzNFCGw5lQUa0='</li>
<li>Calculate the SHA256, SHA384 or SHA512 digest of each inline script (including all whitespace, but excluding the opening and closing script tags). Like the nonce, you'd need to add these digests to the script-src source list using 'sha256-0ZMofb7eMqkB9IFHnGVZ6Z4chjplAavgi09shinNehs=' for example.</li>
</ol>
<p>Options 2 and 3 however are only defined in CSP v2, which is currently only implemented by Chrome, Opera and Firefox.
The safest method would be to use the hash digest method, option 3. Alas, when you choose option 3, you'll quickly run into the following issues:</p>
<ul>
<li><p>Chrome. I'm running version 46.0.2490.80 m on a Windows PC and Chrome keeps telling me this:</p>
<pre><code>Refused <span class="hljs-keyword">to</span> <span class="hljs-keyword">execute</span> <span class="hljs-keyword">inline</span> script because it violates the <span class="hljs-keyword">following</span> Content <span class="hljs-keyword">Security</span> <span class="hljs-keyword">Policy</span> directive: "script-src 'self' 'sha256-0ZMofb7eMqkB9IFHnGVZ6Z4chjplAavgi09shinNehs='". Either the <span class="hljs-string">'unsafe-inline'</span> keyword, a hash (<span class="hljs-string">'sha256-G3FpTn2EFU91Umz2fz6NyjnqeGDTr8SUdmWbsvxzfbY='</span>), <span class="hljs-keyword">or</span> a nonce (<span class="hljs-string">'nonce-...'</span>) <span class="hljs-keyword">is</span> required <span class="hljs-keyword">to</span> <span class="hljs-keyword">enable</span> <span class="hljs-keyword">inline</span> execution.
</code></pre><p>The issue? My script block contains carriage returns for readability. You know, those '\r\n' thingies which tend to differ sometimes, depending on the OS you're running. But I'm running on Windows and hosting my website locally. Yet Chrome has stripped the '\r' characters from the script before calculating the SHA256 hash to verify my script block... Ugh.</p>
</li>
<li><p>Firefox. Version 41.0.2, catching up to Chrome apparently. Loading my test site and...</p>
<pre><code>Content <span class="hljs-keyword">Security</span> <span class="hljs-keyword">Policy</span>: The pag<span class="hljs-string">e's settings blocked the loading of a resource at self ("script-src http://localhost:21275 '</span>sha256<span class="hljs-number">-0</span>ZMofb7eMqkB9IFHnGVZ6Z4chjplAavgi09shinNehs=<span class="hljs-string">'")</span>
</code></pre></li>
<li><p>Edge. The newest browser from Microsoft, which I really want to start to use. But then I bump, as expected, into:</p>
<pre><code><span class="hljs-attribute">CSP14304</span>: Unknown source ''sha<span class="hljs-number">256</span>-<span class="hljs-number">0</span>ZMofb<span class="hljs-number">7</span>eMqkB<span class="hljs-number">9</span>IFHnGVZ<span class="hljs-number">6</span>Z<span class="hljs-number">4</span>chjplAavgi<span class="hljs-number">09</span>shinNehs='' for directive 'script-src' in Content-Security-Policy - source will be ignored.
</code></pre></li>
<li><p>Let's try Internet Explorer, version 11.0.10240.16431. I'll dump the entire console output to share this with you:</p>
<pre><code><span class="hljs-selector-tag">Navigation</span> <span class="hljs-selector-tag">occurred</span>.
<span class="hljs-selector-tag">localhost</span><span class="hljs-selector-pseudo">:21275</span>
<span class="hljs-selector-tag">test</span>
</code></pre><p>Amazing, no? Wait, let's try something else here. Let's remove the hash from the header, that should stop the script from running. I'll dump the console output again:</p>
<pre><code><span class="hljs-selector-tag">Navigation</span> <span class="hljs-selector-tag">occurred</span>.
<span class="hljs-selector-tag">localhost</span><span class="hljs-selector-pseudo">:21275</span>
<span class="hljs-selector-tag">test</span>
</code></pre><p>So don't be fooled here. Internet Explorer doesn't support CSP v2, and even v1 is only partially supported.</p>
</li>
</ul>
<p>Let's try option 2 instead: making use of a nonce for every script block. This time, the results are looking a <em>little bit</em> better:</p>
<ul>
<li>Chrome is happily executing the script now.</li>
<li>So is Firefox, but Firefox keeps complaining about another script. I have no clue which one. I could try to find out, using the CSP reporting options, but I'm not going to bother.</li>
</ul>
<p>So there you have it: Content Security Policy is still not fully there yet. You can use it though, to restrict the use of other content, like webfonts, style sheets, media, ..., but for scripts our options are currently limited to either opening up 'unsafe-inline' or moving all JavaScript into files. And if you're doing ASP.NET projects, have a look at <a target="_blank" href="https://www.nuget.org/packages/NWebsec">https://www.nuget.org/packages/NWebsec</a>. This NuGet package will make implementing CSP - and other security headers - a <strong>lot</strong> easier for you :)</p>
]]></content:encoded></item><item><title><![CDATA[Writing a custom TagHelper in ASP.NET 5]]></title><description><![CDATA[ASP.NET 5 brings some new features to MVC. One of these features is TagHelpers, which allow us to add new attributes to HTML tags (or create custom tags altogether) to add behavior to these tags. At this moment - beta8 - we receive the following TagH...]]></description><link>https://wesleycabus.be/writing-a-custom-taghelper-in-aspnet-5</link><guid isPermaLink="true">https://wesleycabus.be/writing-a-custom-taghelper-in-aspnet-5</guid><category><![CDATA[ASP.NET]]></category><dc:creator><![CDATA[Wesley Cabus]]></dc:creator><pubDate>Fri, 23 Oct 2015 22:00:00 GMT</pubDate><content:encoded><![CDATA[<p>ASP.NET 5 brings some new features to MVC. One of these features is <em>TagHelpers</em>, which allow us to add new attributes to HTML tags (or create custom tags altogether) to add behavior to these tags. At this moment - beta8 - we receive the following TagHelpers out of the box:</p>
<ul>
<li>AnchorTagHelper: allows you to write <code>&lt;a asp-controller="Home" asp-action="Index"&gt;Back to home&lt;/a&gt;</code> instead of <code>@Html.ActionLink("Back to home", "Index", "Home")</code></li>
<li>LabelTagHelper, InputTagHelper, TextAreaTagHelper, SelectTagHelper, etc.: instead of writing Razor like <code>@Html.LabelFor(m =&gt; m.Property1, new { @class = "control-label col-md-2"})</code>, you can use a syntax which is much cleaner: <code>&lt;label asp-for="Property1" class="control-label col-md-2"&gt;&lt;/label&gt;</code></li>
<li>EnvironmentTagHelper: adds a new tag, <code>&lt;environment&gt;</code>, giving you the possibility to include <code>&lt;link&gt;</code> or <code>&lt;script&gt;</code> tags specific for Development or Production environments.</li>
<li>LinkTagHelper, ScriptTagHelper: adds attributes to <code>&lt;link&gt;</code> and <code>&lt;script&gt;</code> to allow the use of CDN's and fallback urls.
This list is incomplete, but you can <a target="_blank" href="https://github.com/aspnet/Mvc/tree/dev/src/Microsoft.AspNetCore.Mvc.TagHelpers">head over to GitHub</a> to see every available TagHelper class currently available.</li>
</ul>
<p>You can also create your own TagHelper classes. I'll show you an example which enables you to do this:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">img</span> <span class="hljs-attr">asp-controller</span>=<span class="hljs-string">"Users"</span> <span class="hljs-attr">asp-action</span>=<span class="hljs-string">"ProfileImage"</span> <span class="hljs-attr">asp-route-id</span>=<span class="hljs-string">"@currentUserId"</span> /&gt;</span>
</code></pre>
<p>That <code>&lt;img&gt;</code> tag would load a users profile image using the ProfileImage action method in a UsersController class: useful for retrieving a profile image from a blob container on Azure, for example.</p>
<p>To create a custom TagHelper class, start by adding a dependency to the Microsoft.AspNet.Razor.Runtime NuGet package in project.json. You can add this dependency to the top list of global dependencies:</p>
<pre><code class="lang-js">{
  <span class="hljs-string">"webroot"</span>: <span class="hljs-string">"wwwroot"</span>,
  <span class="hljs-string">"version"</span>: <span class="hljs-string">"1.0.0-*"</span>,

  <span class="hljs-string">"dependencies"</span>: {
    <span class="hljs-string">"Microsoft.AspNet.Diagnostics"</span>: <span class="hljs-string">"1.0.0-beta8"</span>,
    <span class="hljs-string">"Microsoft.AspNet.IISPlatformHandler"</span>: <span class="hljs-string">"1.0.0-beta8"</span>,
    <span class="hljs-string">"Microsoft.AspNet.Mvc"</span>: <span class="hljs-string">"6.0.0-beta8"</span>,
    <span class="hljs-string">"Microsoft.AspNet.Mvc.TagHelpers"</span>: <span class="hljs-string">"6.0.0-beta8"</span>,
    <span class="hljs-string">"Microsoft.AspNet.Server.Kestrel"</span>: <span class="hljs-string">"1.0.0-beta8"</span>,
    <span class="hljs-string">"Microsoft.AspNet.StaticFiles"</span>: <span class="hljs-string">"1.0.0-beta8"</span>,
    <span class="hljs-string">"Microsoft.AspNet.Tooling.Razor"</span>: <span class="hljs-string">"1.0.0-beta8"</span>,
    <span class="hljs-string">"Microsoft.Framework.Configuration.Json"</span>: <span class="hljs-string">"1.0.0-beta8"</span>,
    <span class="hljs-string">"Microsoft.Framework.Logging"</span>: <span class="hljs-string">"1.0.0-beta8"</span>,
    <span class="hljs-string">"Microsoft.Framework.Logging.Console"</span>: <span class="hljs-string">"1.0.0-beta8"</span>,
    <span class="hljs-string">"Microsoft.Framework.Logging.Debug"</span>: <span class="hljs-string">"1.0.0-beta8"</span>,
    <span class="hljs-string">"Microsoft.VisualStudio.Web.BrowserLink.Loader"</span>: <span class="hljs-string">"14.0.0-beta8"</span>,
    <span class="hljs-string">"Microsoft.AspNet.Razor.Runtime"</span>:  <span class="hljs-string">"4.0.0-beta8"</span>
  },

...
</code></pre>
<p>Next, add a new Class to your MVC project. Let's call this class <strong>ImageTagHelper</strong>, and let the class derive from the <strong>TagHelper</strong> class which lives in the <em>Microsoft.AspNet.Razor.Runtime.TagHelpers</em> namespace.
We're going to add three new attributes to the <code>&lt;img&gt;</code> tag:</p>
<ul>
<li><code>asp-controller</code>: the MVC Controller</li>
<li><code>asp-action</code>: the action method within the controller</li>
<li><code>asp-route-*</code>: route values for the action method</li>
</ul>
<p>For each of these attributes, add a class level HtmlTargetElementAttribute:</p>
<pre><code class="lang-csharp">[<span class="hljs-meta">HtmlTargetElement(<span class="hljs-meta-string">"img"</span>, Attributes = ActionAttributeName)</span>]
[<span class="hljs-meta">HtmlTargetElement(<span class="hljs-meta-string">"img"</span>, Attributes = ControllerAttributeName)</span>]
[<span class="hljs-meta">HtmlTargetElement(<span class="hljs-meta-string">"img"</span>, Attributes = RouteValuesPrefix + <span class="hljs-meta-string">"*"</span>)</span>]
<span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">ProfileImageTagHelper</span> : <span class="hljs-title">TagHelper</span>
{
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">const</span> <span class="hljs-keyword">string</span> ActionAttributeName = <span class="hljs-string">"asp-action"</span>;
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">const</span> <span class="hljs-keyword">string</span> ControllerAttributeName = <span class="hljs-string">"asp-controller"</span>;
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">const</span> <span class="hljs-keyword">string</span> RouteValuesPrefix = <span class="hljs-string">"asp-route-"</span>;
}
</code></pre>
<p>I'm using constants here to define the attribute names: I can reuse these later when adding the properties which will receive the values of the HTML attributes. Let's add these properties now:</p>
<pre><code class="lang-csharp">[<span class="hljs-meta">HtmlTargetElement(<span class="hljs-meta-string">"img"</span>, Attributes = ActionAttributeName)</span>]
[<span class="hljs-meta">HtmlTargetElement(<span class="hljs-meta-string">"img"</span>, Attributes = ControllerAttributeName)</span>]
[<span class="hljs-meta">HtmlTargetElement(<span class="hljs-meta-string">"img"</span>, Attributes = RouteValuesPrefix + <span class="hljs-meta-string">"*"</span>)</span>]
<span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">ProfileImageTagHelper</span> : <span class="hljs-title">TagHelper</span>
{
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">const</span> <span class="hljs-keyword">string</span> ActionAttributeName = <span class="hljs-string">"asp-action"</span>;
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">const</span> <span class="hljs-keyword">string</span> ControllerAttributeName = <span class="hljs-string">"asp-controller"</span>;
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">const</span> <span class="hljs-keyword">string</span> RouteValuesPrefix = <span class="hljs-string">"asp-route-"</span>;

    <span class="hljs-comment"><span class="hljs-doctag">///</span> <span class="hljs-doctag">&lt;summary&gt;</span></span>
    <span class="hljs-comment"><span class="hljs-doctag">///</span> The name of the action method.</span>
    <span class="hljs-comment"><span class="hljs-doctag">///</span> <span class="hljs-doctag">&lt;/summary&gt;</span></span>
    [<span class="hljs-meta">HtmlAttributeName(ActionAttributeName)</span>]
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">string</span> Action { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; }

    <span class="hljs-comment"><span class="hljs-doctag">///</span> <span class="hljs-doctag">&lt;summary&gt;</span></span>
    <span class="hljs-comment"><span class="hljs-doctag">///</span> The name of the controller.</span>
    <span class="hljs-comment"><span class="hljs-doctag">///</span> <span class="hljs-doctag">&lt;/summary&gt;</span></span>
    [<span class="hljs-meta">HtmlAttributeName(ControllerAttributeName)</span>]
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">string</span> Controller { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; }

    <span class="hljs-comment"><span class="hljs-doctag">///</span> <span class="hljs-doctag">&lt;summary&gt;</span></span>
    <span class="hljs-comment"><span class="hljs-doctag">///</span> Additional parameters for the route.</span>
    <span class="hljs-comment"><span class="hljs-doctag">///</span> <span class="hljs-doctag">&lt;/summary&gt;</span></span>
    [<span class="hljs-meta">HtmlAttributeName(DictionaryAttributePrefix = RouteValuesPrefix)</span>]
    <span class="hljs-keyword">public</span> IDictionary&lt;<span class="hljs-keyword">string</span>, <span class="hljs-keyword">string</span>&gt; RouteValues { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; } =
        <span class="hljs-keyword">new</span> Dictionary&lt;<span class="hljs-keyword">string</span>, <span class="hljs-keyword">string</span>&gt;(StringComparer.OrdinalIgnoreCase);
}
</code></pre>
<p>By using a <code>*</code> at the end of the HtmlTargetElementAttribute, we can map multiple values into an <code>IDictionary&lt;string, string&gt;</code>. Think of this as a way to specify only one property to hold all <code>data-*</code> attributes.
It is now time to add the logic which will make this TagHelper work. Let's override the Process method:</p>
<pre><code class="lang-csharp"><span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">override</span> <span class="hljs-keyword">void</span> <span class="hljs-title">Process</span>(<span class="hljs-params">TagHelperContext context, TagHelperOutput output</span>)</span>
{
    <span class="hljs-keyword">if</span> (context == <span class="hljs-literal">null</span>)
    {
        <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> ArgumentNullException(<span class="hljs-keyword">nameof</span>(context));
    }

    <span class="hljs-keyword">if</span> (output == <span class="hljs-literal">null</span>)
    {
        <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> ArgumentNullException(<span class="hljs-keyword">nameof</span>(output));
    }

    <span class="hljs-comment">// If "src" is already set, it means the user is attempting to use a normal img tag.</span>
    <span class="hljs-keyword">if</span> (output.Attributes.ContainsName(<span class="hljs-string">"src"</span>))
    {
        <span class="hljs-keyword">if</span> (Action != <span class="hljs-literal">null</span> ||
            Controller != <span class="hljs-literal">null</span> ||
            RouteValues.Count != <span class="hljs-number">0</span>)
        {
            <span class="hljs-comment">// User specified an src and one of the bound attributes; can't determine the src attribute.</span>
            <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> InvalidOperationException(
                <span class="hljs-string">"Cannot override the src attribute of an &lt;img&gt; tag if the src attribute has a value."</span>);
        }
    }
    <span class="hljs-keyword">else</span>
    {
        <span class="hljs-comment">// Convert from Dictionary&lt;string, string&gt; to Dictionary&lt;string, object&gt;.</span>
        <span class="hljs-keyword">var</span> routeValues = RouteValues.ToDictionary(
            kvp =&gt; kvp.Key,
            kvp =&gt; (<span class="hljs-keyword">object</span>) kvp.Value,
            StringComparer.OrdinalIgnoreCase);

        <span class="hljs-keyword">var</span> tagBuilder = <span class="hljs-keyword">new</span> TagBuilder(<span class="hljs-string">"img"</span>);
        tagBuilder.MergeAttribute(<span class="hljs-string">"src"</span>, _urlHelper.Action(Action, Controller, routeValues));

        output.MergeAttributes(tagBuilder);
    }
}
</code></pre>
<p>First of all, we check if the consumer of this custom TagHelper hasn't set a value for the <em>src</em> attribute, because then the <code>&lt;img&gt;</code> tag would just need to look at the original URI to retrieve the image. We will however show an error when the <em>src</em> attribute and one of our custom attributes has been set together.
If the developer is using our TagHelper without a <em>src</em> attribute, then we'll fill in the attribute ourselves using <code>_urlHelper.Action()</code>: that's the <code>@Url.Action</code> method you've been using in Razor all along. Of course, we still need to add that <code>_urlHelper</code> instance to our class and inject it. Here is the final version of our TagHelper class code:</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">using</span> System;
<span class="hljs-keyword">using</span> System.Collections.Generic;
<span class="hljs-keyword">using</span> System.Linq;
<span class="hljs-keyword">using</span> Microsoft.AspNet.Mvc;
<span class="hljs-keyword">using</span> Microsoft.AspNet.Mvc.Rendering;
<span class="hljs-keyword">using</span> Microsoft.AspNet.Mvc.TagHelpers;
<span class="hljs-keyword">using</span> Microsoft.AspNet.Razor.Runtime.TagHelpers;

<span class="hljs-keyword">namespace</span> <span class="hljs-title">CustomTagHelperDemo.TagHelpers</span>
{
    [<span class="hljs-meta">HtmlTargetElement(<span class="hljs-meta-string">"img"</span>, Attributes = ActionAttributeName)</span>]
    [<span class="hljs-meta">HtmlTargetElement(<span class="hljs-meta-string">"img"</span>, Attributes = ControllerAttributeName)</span>]
    [<span class="hljs-meta">HtmlTargetElement(<span class="hljs-meta-string">"img"</span>, Attributes = RouteValuesPrefix + <span class="hljs-meta-string">"*"</span>)</span>]
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">ProfileImageTagHelper</span> : <span class="hljs-title">TagHelper</span>
    {
        <span class="hljs-keyword">private</span> <span class="hljs-keyword">readonly</span> IUrlHelper _urlHelper;

        <span class="hljs-keyword">private</span> <span class="hljs-keyword">const</span> <span class="hljs-keyword">string</span> ActionAttributeName = <span class="hljs-string">"asp-action"</span>;
        <span class="hljs-keyword">private</span> <span class="hljs-keyword">const</span> <span class="hljs-keyword">string</span> ControllerAttributeName = <span class="hljs-string">"asp-controller"</span>;
        <span class="hljs-keyword">private</span> <span class="hljs-keyword">const</span> <span class="hljs-keyword">string</span> RouteValuesPrefix = <span class="hljs-string">"asp-route-"</span>;

        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">ProfileImageTagHelper</span>(<span class="hljs-params">IUrlHelper urlHelper</span>)</span>
        {
            _urlHelper = urlHelper;
        }

        <span class="hljs-comment"><span class="hljs-doctag">///</span> <span class="hljs-doctag">&lt;summary&gt;</span></span>
        <span class="hljs-comment"><span class="hljs-doctag">///</span> The name of the action method.</span>
        <span class="hljs-comment"><span class="hljs-doctag">///</span> <span class="hljs-doctag">&lt;/summary&gt;</span></span>
        <span class="hljs-comment"><span class="hljs-doctag">///</span> <span class="hljs-doctag">&lt;remarks&gt;</span>Must be <span class="hljs-doctag">&lt;c&gt;</span>null<span class="hljs-doctag">&lt;/c&gt;</span> if <span class="hljs-doctag">&lt;see cref="Route"/&gt;</span> is non-<span class="hljs-doctag">&lt;c&gt;</span>null<span class="hljs-doctag">&lt;/c&gt;</span>.<span class="hljs-doctag">&lt;/remarks&gt;</span></span>
        [<span class="hljs-meta">HtmlAttributeName(ActionAttributeName)</span>]
        <span class="hljs-keyword">public</span> <span class="hljs-keyword">string</span> Action { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; }

        <span class="hljs-comment"><span class="hljs-doctag">///</span> <span class="hljs-doctag">&lt;summary&gt;</span></span>
        <span class="hljs-comment"><span class="hljs-doctag">///</span> The name of the controller.</span>
        <span class="hljs-comment"><span class="hljs-doctag">///</span> <span class="hljs-doctag">&lt;/summary&gt;</span></span>
        <span class="hljs-comment"><span class="hljs-doctag">///</span> <span class="hljs-doctag">&lt;remarks&gt;</span>Must be <span class="hljs-doctag">&lt;c&gt;</span>null<span class="hljs-doctag">&lt;/c&gt;</span> if <span class="hljs-doctag">&lt;see cref="Route"/&gt;</span> is non-<span class="hljs-doctag">&lt;c&gt;</span>null<span class="hljs-doctag">&lt;/c&gt;</span>.<span class="hljs-doctag">&lt;/remarks&gt;</span></span>
        [<span class="hljs-meta">HtmlAttributeName(ControllerAttributeName)</span>]
        <span class="hljs-keyword">public</span> <span class="hljs-keyword">string</span> Controller { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; }

        <span class="hljs-comment"><span class="hljs-doctag">///</span> <span class="hljs-doctag">&lt;summary&gt;</span></span>
        <span class="hljs-comment"><span class="hljs-doctag">///</span> Additional parameters for the route.</span>
        <span class="hljs-comment"><span class="hljs-doctag">///</span> <span class="hljs-doctag">&lt;/summary&gt;</span></span>
        [<span class="hljs-meta">HtmlAttributeName(DictionaryAttributePrefix = RouteValuesPrefix)</span>]
        <span class="hljs-keyword">public</span> IDictionary&lt;<span class="hljs-keyword">string</span>, <span class="hljs-keyword">string</span>&gt; RouteValues { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; } =
            <span class="hljs-keyword">new</span> Dictionary&lt;<span class="hljs-keyword">string</span>, <span class="hljs-keyword">string</span>&gt;(StringComparer.OrdinalIgnoreCase);

        <span class="hljs-comment"><span class="hljs-doctag">///</span> <span class="hljs-doctag">&lt;summary&gt;</span></span>
        <span class="hljs-comment"><span class="hljs-doctag">///</span> Synchronously executes the <span class="hljs-doctag">&lt;see cref="T:Microsoft.AspNet.Razor.Runtime.TagHelpers.TagHelper"/&gt;</span> with the given <span class="hljs-doctag">&lt;paramref name="context"/&gt;</span> and</span>
        <span class="hljs-comment"><span class="hljs-doctag">///</span>             <span class="hljs-doctag">&lt;paramref name="output"/&gt;</span>.</span>
        <span class="hljs-comment"><span class="hljs-doctag">///</span> <span class="hljs-doctag">&lt;/summary&gt;</span></span>
        <span class="hljs-comment"><span class="hljs-doctag">///</span> <span class="hljs-doctag">&lt;param name="context"&gt;</span>Contains information associated with the current HTML tag.<span class="hljs-doctag">&lt;/param&gt;</span><span class="hljs-doctag">&lt;param name="output"&gt;</span>A stateful HTML element used to generate an HTML tag.<span class="hljs-doctag">&lt;/param&gt;</span></span>
        <span class="hljs-comment"><span class="hljs-doctag">///</span> <span class="hljs-doctag">&lt;remarks&gt;</span>Does nothing if user provides an <span class="hljs-doctag">&lt;c&gt;</span>src<span class="hljs-doctag">&lt;/c&gt;</span> attribute.<span class="hljs-doctag">&lt;/remarks&gt;</span></span>
        <span class="hljs-comment"><span class="hljs-doctag">///</span> <span class="hljs-doctag">&lt;exception cref="InvalidOperationException"&gt;</span></span>
        <span class="hljs-comment"><span class="hljs-doctag">///</span> Thrown if <span class="hljs-doctag">&lt;c&gt;</span>src<span class="hljs-doctag">&lt;/c&gt;</span> attribute is provided and <span class="hljs-doctag">&lt;see cref="Action"/&gt;</span> or <span class="hljs-doctag">&lt;see cref="Controller"/&gt;</span> are</span>
        <span class="hljs-comment"><span class="hljs-doctag">///</span> non-<span class="hljs-doctag">&lt;c&gt;</span>null<span class="hljs-doctag">&lt;/c&gt;</span> or if the user provided <span class="hljs-doctag">&lt;c&gt;</span>asp-route-*<span class="hljs-doctag">&lt;/c&gt;</span> attributes.</span>
        <span class="hljs-comment"><span class="hljs-doctag">///</span> <span class="hljs-doctag">&lt;/exception&gt;</span></span>
        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">override</span> <span class="hljs-keyword">void</span> <span class="hljs-title">Process</span>(<span class="hljs-params">TagHelperContext context, TagHelperOutput output</span>)</span>
        {
            <span class="hljs-keyword">if</span> (context == <span class="hljs-literal">null</span>)
            {
                <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> ArgumentNullException(<span class="hljs-keyword">nameof</span>(context));
            }

            <span class="hljs-keyword">if</span> (output == <span class="hljs-literal">null</span>)
            {
                <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> ArgumentNullException(<span class="hljs-keyword">nameof</span>(output));
            }

            <span class="hljs-comment">// If "src" is already set, it means the user is attempting to use a normal anchor.</span>
            <span class="hljs-keyword">if</span> (output.Attributes.ContainsName(<span class="hljs-string">"src"</span>))
            {
                <span class="hljs-keyword">if</span> (Action != <span class="hljs-literal">null</span> ||
                    Controller != <span class="hljs-literal">null</span> ||
                    RouteValues.Count != <span class="hljs-number">0</span>)
                {
                    <span class="hljs-comment">// User specified an href and one of the bound attributes; can't determine the href attribute.</span>
                    <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> InvalidOperationException(
                        <span class="hljs-string">"Cannot override the src attribute of an &lt;img&gt; tag if the src attribute has a value."</span>);
                }
            }
            <span class="hljs-keyword">else</span>
            {
                <span class="hljs-comment">// Convert from Dictionary&lt;string, string&gt; to Dictionary&lt;string, object&gt;.</span>
                <span class="hljs-keyword">var</span> routeValues = RouteValues.ToDictionary(
                    kvp =&gt; kvp.Key,
                    kvp =&gt; (<span class="hljs-keyword">object</span>) kvp.Value,
                    StringComparer.OrdinalIgnoreCase);

                <span class="hljs-keyword">var</span> tagBuilder = <span class="hljs-keyword">new</span> TagBuilder(<span class="hljs-string">"img"</span>);
                tagBuilder.MergeAttribute(<span class="hljs-string">"src"</span>, _urlHelper.Action(Action, Controller, routeValues));

                output.MergeAttributes(tagBuilder);
            }
        }
    }
}
</code></pre>
<p>But we're not done, yet. To be able to use custom TagHelper classes, you'll need to let Razor know about them.  Open the _ViewImports.cshtml file in the Views/Shared folder and add the following line:</p>
<pre><code class="lang-csharp">@addTagHelper <span class="hljs-string">"*, CustomTagHelperDemo"</span>
</code></pre>
<p>This line will tell Razor to load all TagHelper derived classes from the assembly CustomTagHelperDemo. You can also use the name of a specific TagHelper class instead of an asterisk. Also, don't forget to replace <em>CustomTagHelperDemo</em> with the name of your project or class library.
And now, you can open up a Razor file and tryout the new features you've added to the <img /> tag:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">ul</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"nav navbar-nav navbar-right"</span>&gt;</span>
    @if (User.Identity?.IsAuthenticated == true)
    {
        <span class="hljs-tag">&lt;<span class="hljs-name">li</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">img</span> <span class="hljs-attr">asp-controller</span>=<span class="hljs-string">"Users"</span> <span class="hljs-attr">asp-action</span>=<span class="hljs-string">"ProfileImage"</span> <span class="hljs-attr">asp-route-id</span>=<span class="hljs-string">"@User.FindFirst("</span><span class="hljs-attr">sub</span>")<span class="hljs-attr">.Value</span>" /&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">a</span> <span class="hljs-attr">asp-controller</span>=<span class="hljs-string">"Account"</span> <span class="hljs-attr">asp-action</span>=<span class="hljs-string">"Logoff"</span>&gt;</span>Sign out<span class="hljs-tag">&lt;/<span class="hljs-name">a</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span>
    }
    else
    {
        <span class="hljs-tag">&lt;<span class="hljs-name">li</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">a</span> <span class="hljs-attr">asp-controller</span>=<span class="hljs-string">"Account"</span> <span class="hljs-attr">asp-action</span>=<span class="hljs-string">"Logon"</span>&gt;</span>Sign in<span class="hljs-tag">&lt;/<span class="hljs-name">a</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span>
    }
<span class="hljs-tag">&lt;/<span class="hljs-name">ul</span>&gt;</span>
</code></pre>
]]></content:encoded></item></channel></rss>