Winner's Excogitations

A chronicle of the thoughts, learning experiences, ideas and actions of a tech junkie, .NET, JS and Mobile dev, aspiring entrepreneur, devout Christian and travel enthusiast.

[HOW TO] Deploy your ASP.NET Core 1.x app to Heroku
7 years ago · 3 minutes read

For this tutorial, I’ll be using Elementary OS 0.4 Loki so the commands would be geared towards my system, but since elementary OS is based off Ubuntu, the same commands would work on Ubuntu. For those using Windows or Mac, I’m sure there are comparable commands for your platform.

Installing Ruby

To make use of the Heroku command line interface, you need to have Ruby installed on your system. So to install Ruby, some prerequisites must be installed and they can be using the following commands:

sudo apt-get update
    
sudo apt-get install git-core curl zlib1g-dev build-essential libssl-dev libreadline-dev libyaml-dev libsqlite3-dev sqlite3 libxml2-dev libxslt1-dev libcurl4-openssl-dev python-software-properties libffi-dev

After installing the prerequisites, we’ll install rvm which is the Ruby Version Manager. For that, we’ll install a few more prerequisites that are specific to rvm using the following command:

sudo apt-get install libgdbm-dev libncurses5-dev automake libtool bison libffi-dev

Next, we add the GNU projects’ GPG key to the keyring of your system to allow your system trust content gotten from their allied servers using the command:

gpg --keyserver hkp://keys.gnupg.net --recv-keys 409B6B1796C275462A1703113804BB82D39DC0E3

Next, we finally download and install the rvm using the commands below:

curl -sSL https://get.rvm.io | bash -s stable
    
source ~/.rvm/scripts/rvm
    
rvm install 2.3.1

Set the installed version as the default

rvm use 2.3.1 --default

Check the version of Ruby installed:

ruby -v

Installing Heroku

Both Windows and Mac OS have installers which can be gotten at https://devcenter.heroku.com/articles/heroku-command-line. But for Ubuntu or Elementary OS, run the following command which would get the debian package and install it:

wget -O- https://toolbelt.heroku.com/install-ubuntu.sh | sh

After it installs, you can verify your Heroku version with the command:

heroku --version

Heroku might prompt you to install the CLI which I did.

Next Steps

Next, you need to login to your Heroku account. And to do that you must have created an account on the Heroku website.After that is done, log in using the command:

heroku login

You’ll be prompted for your email address and password. Enter the appropriate values and wait for the success message telling you that you’re logged in.

Next, you create the build pack. There are some languages which Heroku supports by default and ASP.NET Core is not one of them. But trust the open source community to have created a solution which can be found at http://github.com/bolorundurowb/dotnetcore-buildpack.git. Create your build pack using the command:

heroku create --buildpack https://github.com/bolorundurowb/dotnetcore-buildpack#v1.1.5

Once that is done commit any changes you have made in your repo using the following commands:

git add *
    
git commit -m “”

Next, push your repo to Heroku using the command:

git push heroku master

If you get an error fatal: ‘heroku’ does not appear to be a git repository, run the following command:

heroku git:remote -a

If you get the error Failed to detect set buildpack https://github.com/bolorundurowb/dotnet-buildpack then make sure your local repo has a project.json file defined.

If everything goes well, you should see the following screen

screenshot-from-2016-10-04-124718

Finally, run your new Heroku app using the command:

heroku open
Json Web Token (JWT) Authentication with ASP.NET Core 2.0
7 years ago · 4 minutes read

I recently was building a small web application and needed to add some authentication. For the .NET developer, the first thing that comes to mind is Identity but was that too heavy for my purposes. Having worked with Json Web Tokens (JWT) with NodeJS, they seemed to be the perfect fit for the job. They are simple, easy to implement, and for the most part, do a good job of securing your endpoint(s).

The wrong way

That said, I initially approached implementing token-based authentication the same way i had done it on Node which was a pretty terrible idea. I created middleware that sat on the HTTP request pipeline and for every request, I checked the route to see if it was to be protected and then proceeded to look for the token header, retrieve it, decode it and respond depending on the state of the token. That led to this abomination

    public class AuthenticationMiddleware
    {
        private readonly RequestDelegate _next;
    
        public AuthenticationMiddleware(RequestDelegate next)
        {
            _next = next;
        }
    
        public async Task Invoke(HttpContext context)
        {
            if (context.Request.Path.Value.Contains("notes"))
            {
                string token = context.Request.Headers["x-access-token"];
                if (token == null)
                {
                    context.Response.StatusCode = 401;
                    await context.Response.WriteAsync("Sorry, a token is required to access this route.");
                    return;
                }
    
                try
                {
                    var json = Helpers.DecodeToken(token);
                    context.Items["id"] = json["id"];
                    await _next.Invoke(context);
                    return;
                }
                catch (TokenExpiredException)
                {
                    context.Response.StatusCode = 401;
                    await context.Response.WriteAsync("Sorry, your token is expired. Please login.");
                    return;
                }
                catch (SignatureVerificationException)
                {
                    context.Response.StatusCode = 401;
                    await context.Response.WriteAsync("Sorry, this token has an invalid signature.");
                    return;
                }
                catch (ArgumentException)
                {
                    context.Response.StatusCode = 401;
                    await context.Response.WriteAsync("Sorry, this token is corrupted.");
                    return;
                }
            }
    
            await _next.Invoke(context);
        }
    }
    
    public static class AuthenticationMiddlewareExtensions
    {
        public static IApplicationBuilder UseAuthenticationMiddleware(this IApplicationBuilder app)
        {
            return app.UseMiddlewarelt;AuthenticationMiddlewaregt;();
        }
    }

Somewhere at the back of my mind, I knew this couldn’t be the right way. So off I went to do some research and it turns out I was right, there is a better way.

The right way

This tutorial makes a whole lot of assumptions. First, you know what Json Web Tokens are. If you don’t, then this scotch.io article would do you a whole world of good. Second, you are familiar with the C# language, .NET Core and the ASP.NET Core framework. if you are not familiar with them, this, this and this would help you get up to speed. Third, you have an ASP.NET Core application. Finally, you have a system of verifying if a user is valid or not.

That said, we need to create a static method called GenerateAuthToken that would help us generate the authentication token (static so as to enable it be called from any class without instantiation). You can place the method in any existing class or create a class for that purpose. The method should look something like this. This sample takes a userId as the token payload.

    internal static string GenerateAuthToken(string userId)
    {
        var claims = new[]
        {
            new Claim(JwtRegisteredClaimNames.Sub, userId),
            new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
        };
    
        var token = new JwtSecurityToken
        (
            "the issuer (change please)",
            "your audience (change please)",
            claims,
            expires: DateTime.UtcNow.AddDays(30),
            notBefore: DateTime.UtcNow,
            signingCredentials: new SigningCredentials(
                new SymmetricSecurityKey(Encoding.UTF8.GetBytes("The security key (change please)")),
                SecurityAlgorithms.HmacSha256)
        );
        return new JwtSecurityTokenHandler().WriteToken(token);
    }

Once you are done verifying a user’s validity with a check against a database or by any other means, proceed to call the GenerateAuthToken method with the userId as a parameter. Something like this:

var token = GenerateAuthToken("sampleId");

A token would be retruned that looks something like this:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJ0b3B0YWwuY29tIiwiZXhwIjoxNDI2NDIwODAwLCJodHRwOi8vdG9wdGFsLmNvbS9qd3RfY2xhaW1zL2lzX2FkbWluIjp0cnVlLCJjb21wYW55IjoiVG9wdGFsIiwiYXdlc29tZSI6dHJ1ZX0.yRQYnWzskCZUxPwaQupWkiUzKELZ49eM7oWxAQK_ZXw

Next, to verify the user token when a request is made to the API, we need to configure the request pipeline. Add this to the <span class="pl-en">ConfigureServices</span> method in the ​Startup.cs file of your project to handle verifying the token:

     // add authentication
    services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
     .AddJwtBearer(jwtBearerOptions =&amp;gt;
     {
       jwtBearerOptions.TokenValidationParameters = new TokenValidationParameters
       {
         ValidateActor = true,
         ValidateAudience = true,
         ValidateLifetime = true,
         ValidateIssuerSigningKey = true,
         ValidIssuer = "the issuer (please change)",
         ValidAudience = "your audience (please change)",
         IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("a secret (please change)"))
       };
     });

Add the code below to the Configure method of your Startup.cs file. It adds the authentication middleware to the request pipeline.

app.UseAuthentication();

Finally, to protect any controller or controller method, just add the Authorize attribute to the controller or controller method. That protects it from unauthorized access. if no token is present on the request or the token is invalid, a 401 response is returned.

PS: The JWT Bearer system expects the header to be in the format,

Authorization: Bearer .

Hopefully, this helps someone on their way to building the next big thing.

Till the next one.

Cheers.

 

My Open Source story (thus far)
7 years ago · 3 minutes read

open source

About 2 years ago, I took a hiatus from writing .NET code to focus on NodeJS as I needed it for work. I worked with Express, and MongoDB and over the course of working and learning I developed a fondness for some tools and libraries as they just made my life easy and saved me time. Fast forward a few months and I am back to writing dot net code again (though it is dot net core now) I realise that quite a number of those libraries have no dot net equivalent and that is what set me down this trip.

The first library from the JavaScript world that I missed was shortid. It is a simple package that generates unique strings from seven to fourteen characters long and those can be used for just about anything. I used them as my _id fields in my mongo collections instead of the mongoid format that MongoDB assigns by default. It helped make them human-readable at least for me. I got back to writing web apps with ASP.NET Core and was itching for a way to generate short ids that I could use to uniquely identify objects in my database and use in a URL as well. When I discussed this with other dot net devs their response was to use Guid's and while that would have met my requirement for uniqueness, I just didn't like seeing a Guid in my URI. My grand solution was to write a dot net analogue called (you won't believe the amount of creativity this took) shortid. Writing it and posting the source code online allowed for me to gain valuable feedback and insights about handling thread safety and memory management when dealing with a lot of strings.

The second library I realized I missed was dotenv which is a library that helps load environment variables from .env files. When I started working with ASP.NET Core, I tried handling configuration data using the baked in appsettings.json files but those had the glaring limitation of having you place potentially sensitive information in plain text. .env files allow for the files to just reside locally and not be checked into source control. I looked around and did not see any library that allowed for that to be done on ASP.NET Core and so ... (you guessed it) I wrote one. I called it dotenv.net. I made a few changes to the way the dot net port works to make sure it familiar to the target audience. Building this and having it open source helped me learn how to handle ideas from other developers in the form of issues or pull requests, know when a change recommended is in line with the goals and spirit of the project.

Recently, I really wanted to see a summary if the details of the calls my ASP.NET Core Web API was receiving and I realised the dot net ecosystem doesn't have something like morgan which exists for NodeJS. I set out to write a port called Logly which is out and on nuget. Writing a piece on that as well, that should be out in a few days.

The purpose for writing all of this and telling these stories is to encourage someone somewhere to do something. Do not feel like you cannot. If you identify an issue or a need in your environment, step up and take responsibility and this goes for more than just programming,

Cheers people,

Till the next one.

My Perfect Devices 2014
7 years ago · 3 minutes read

As promised in my previous post about my perfect devices 2016, here is what would have constituted the perfect devices for me in 2014. As I go through them again, they’ll still be pretty competitive in the year 2016. So much for the 2-year cycle of IT equipment.

The phone 📱


A 5-inch Super-AMOLED screen
1920 * 1080
A 2.5GHz Cortex A17 quad core processor
An ARM Mali T764 GPU @750MHz
An 8MP Ultra Pixel ISOCELL camera
Dual tone flash
A 2MP front camera
Stereo front facing speakers
3500mAh battery
LTE support
Wireless charging support
Dolby enhanced sound
Aircraft grade Aluminum body
Dragontrail glass with oleophobic coating
Dual-band 802.11a/b/g/n/ac wifi
Bluetooth 4.0 with a2dp, ant+, and edr
16GB internal memory
SD card supports up to 128GB.

The tablet 💊


An 8.9-inch Super-AMOLED screen
2560 *1536 resolution
A 3.0GHz Cortex A17 quad core processor
3GB ram
Power VR G6400 MP6
4MP ultra Pixel ISOCELL camera
Dual tone LED flash
2MP front camera
Stereo speakers with subwoofer
10000mAh battery
LTE support
Wireless charging support
Dolby enhanced sound
Aircraft grade Aluminum body
Dragontrail glass with oleophobic coating
Dual-band 802.11a/b/g/n/ac wifi
Bluetooth 4.0 with a2dp, ANT+, and EDR
64GB internal memory
SD card supports up to 128GB.

The laptop


Intel Core i7 4702MQ processor
8GB of ddr3 RAM
32GB mSATA SSD
1024GB 7200rpm HDD
Dual band 802.11a/b/g/n/ac wifi
bluetooth 4.0 with a2dp and edr
4 USB 3.1 ports
4 speakers with a sub woofer
5MP camera
Full sized back-lit keyboard
Nvidia 745m graphics card
2GB video ram
Aluminum body
17.3 inch screen
1920 x 1080 resolution
100Wh battery
Lightweight
<2cm thick

The desktop 💻 setup


An Intel I7 5960X 8 core processor @4GHz
32GB of DDR4 2133MHz quad channel ram
Amd Radeon R9 295×2 GPU (8GB DDR5 VRAM, 5362 shaders 1018MHz)
256GB PCIe SSD
512GB Sata III 6.0Gbps ssd
2x 2TB 7200rpm hdd
Dual band 802.11a/b/g/n/ac wifi
Bluetooth 4.0 with A2DP and EDR
2x 30″ 2560 x 1440 AMOLED displays

Getting Started With ASP.NET Core (Part 1)
7 years ago · 3 minutes read

ASP.NET Core is the new direction that Microsoft is taking their web technologies. It is still in its early stages but is showing a lot of promise. Between versions 1.0 and 1.1, the Kestrel server has shown significant speed improvements. ASP.NET Core is a significant departure from the previous generation of ASP.NET in that it was (and currently is) a community-driven and developed project whose source code can be found on GitHub. ASP.NET Core also has the advantage of being very modular, this means that it can be run on IIS Servers, or the newer, lighter Kestrel Server. Another advantage ASP.NET Core has is that it shares a single set of libraries for creating Web API and Web applications. The most important advantage is that unlike traditional ASP.NET, ASP.NET Core is fully cross-platform.

At the end of this tutorial, we’ll create a full-fledged Notes application and deploy it to Heroku, but for this part, we’ll start with a basic application which would show “Hello World” in the browser.

We would be using the ASP .NET Core yeoman generator to spin up our web application. If you don’t have the ASP .NET Core generator, you can install it via npm. The following dependencies are required:

  1. .NET Core SDK which can be gotten from here 

  2. Node JS which can be gotten from here

  3. Yeoman which can be installed by running

    npm install -g yo
    
  4. Bower which can be installed by running

    $ npm install -g bower
    
  5. ASP .NET yeoman generator by running

    $ npm install -g generator-aspnet
    

Once you’re all set, run the following command;

$ yo aspnet

You should see the following screen;

bolorundurowb_com/production/article/zaanse3yobxhak08gjdl

Select the “Empty Web Application” option using the up and down arrow keys and accept with the Enter key.

Set your app name, for this tutorial, we’ll use cookieauth.

bolorundurowb_com/production/article/tgarpyfntheu2qwzvbaj

After that, a set of files would be created in the folder cookieauth

Next change directory to the cookieauth folder using:

$ cd cookieauth

Run the commands

$ dotnet restore

To get all required libraries from Nuget

$ dotnet build

To compile the existing code to an executable

bolorundurowb_com/production/article/bkx7sr7nzry6m18vxgph

$ dotnet run

This would run the empty app on the default port (5000) and can be accessed via the URL http://localhost:5000

bolorundurowb_com/production/article/awedmxwbxk7xx19awajl

If you visit HTTP://localhost:5000 in your browser, you should see

bolorundurowb_com/production/article/bfvplsa3ykdcp9sjaspa

That would be it, for this. Check out the next tutorial in this series.

Cheers