Storing JWT access token in a Cookie

I am using JWT access tokens for my latest ASP.NET Core project. Authentication is added in ConfigureServices:

services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options =>
{
 options.TokenValidationParameters = new TokenValidationParameters()
 {
 ValidateIssuer = true,
 ValidateAudience = true,
 ValidateLifetime = true,
 ValidateIssuerSigningKey = true,
 ValidIssuer = Configuration["Jwt:Issuer"],
 ValidAudience = Configuration["Jwt:Issuer"],
 IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:Key"]))
 };
});

This works well for my SPA application, where I store the access token in localStorage (which is bad).  Moving the JWT access token to a cookie is a better approach, however I want the ability to use JWT Bearer for my APIs. Configuration of Dual authentication where:

  1. JWT token can be passed as part of Authorization header
  2. And JWT token can be passed as a token.

has proven cumbersome to implement.

A simple approach is to 1. add an access token cookie when forming the token and to 2. fake the Authorization header on the server if an access token is received as a cookie.

In the TokenController, the Cookie is either set or deleted depending on the success of the authorization:

[HttpPost]
public IActionResult Post([FromBody]UserBody user)
{
 IActionResult response = Unauthorized();
 if (this.Authenticate(user))
 {
  var token = this.BuildToken(user);
  response = Ok(new { token = token });
  Response.Cookies.Append("access_token", token);
 }
 else
 {
  Response.Cookies.Delete("access_token");
 }

 return response;
}

When a client sends his credentials, the credentials are checked and if successful a token is returned as part of the response. In addition, the token is added to an access_token cookie (which should be httpOnly for security reasons).

To make use of the cookie, we simply forge the Authorization header based upon the value of the cookie. This is done by writing a simple middleware before the app.UseAuthentication() in Startup.Configure.

app.Use(async (context, next)=>
{
 var token = context.Request.Cookies["access_token"];
 if (token != null)
 context.Request.Headers["Authorization"] = "Bearer " + token.ToString();
 await next();
});

app.UseAuthentication();

If the cookie exists, it is added to the Authorization header, thus invoking the JWT Bearer authorization mechanism in the pipeline. If the authorization fails in the pipeline, the Cookie is cleared.

Simple as that!

 

Advertisements

Parcel-Bundler

Parcel-bundler is a zero configuration web application bundler similar to webpack. It sports multicore compilation and filesystem cache for faster build times, with out of the box support for the most common file types.

Setting up a project using Parcel-Bundler for TypeScript + React is a piece of cake.

Simply create an index.html file which references the index.tsx file directly and invoking the following command from cmd:

parcel index.html

and we are off!

Build wise, parcel will automatically use index.html as entry-point, invoke the TSC compiler for the TypeScript source and include referenced CSS files in the build.

In addition, it will automatically host the bundle on port 1234 and do hot replacement upon changes to the underlying source.

Build wise, it is about twice as fast compared to webpack on my Quad core while sporting even faster build times during incremental builds.

Parcel-Bundler will definitely replace my use of Webpack on most of my projects.

VSync and Browsers (lack-of)

While developing my HTML5 game, LaserDefence, I stumbled upon vsync issues in Chrome – specifically that my game stuttered several times throughout the gameplay.

I tracked the issue down to the specific Chrome version installed as standard webview on Android 6.0 and I was able to fix the issue by compiling my HTML5 game using Crosswalk.

However, investigation of the issue showed that all browsers (more or less) have vsync issues. This has also been reported by vsynctester.com, a site where one can test a browsers vsync capabilities.

For Chrome on Windows, vsync more or less works – i.e. no dropped frames, however on my Android phone a Galaxy S5 running 6.0 vsynctester.com frequently showed dropped frames using Chrome. Other browsers exhibited similar issues.

According to vsynctester.com, both Firefox and Chrome implement vsync “wrongly” meaning that dropped frames will happen resulting in stuttering in the gameplay and or animations.

One is met with the following messages when visiting vsynctester.com from Firefox and Chrome:

“Firefox is hopelessly broken (timers/vsync/etc) — DO NOT USE!”
“Google Chrome has VSYNC issues — You can help get Chrome fixed!”

Funny enough, Edge seem to be the browser which implements vsync properly, but even so, Edge does not support high refresh-rate displays which clearly puts the browser at a disadvantage compared to Chrome and Firefox.

As of 2018, no browser seem to implement proper vsync with high-refresh rate support. VERY disappointing considering that more applications are moved to the web, which includes graphical demanding applications.

Lets hope 2018 is the year where atleast Chrome and Firefox mets the quality test of vsynctester.com…

 

Laser Defence

I implemented my first ever (finished) HTML5 game called Laser Defence.

It can be played here: http://laserdefence.hrup.dk

I used PIXI.JS v4 and TypeScript for the implementation. Visual Studio Code was used as the IDE.

For fun, I wrapped the project into Cordova and published it to the Google Play Store:

https://play.google.com/store/apps/details?id=dk.hrup.laserdefence

I had some issues with consistent frame-rates using Cordova on my Galaxy S5 phone. The fix was to use the Crosswalk Cordova plugin. This plugin comes with its own Chromium instance, which is far superior to the default webview provided by Android 6.0.

The con is a fatter APK, about 20MB – but the pro is a much more consistent experience.

laserdefence
Screenshot of laser defence!

 

Nativefier

I stumbled upon a cool tool named Nativefier which converts a website into a desktop application, i.e. wrapping it in an executable. Can be installed from NPM and invoked like so:

npm install nativefier -g
nativefier somewebsite.com

This downloads all resources from the URL and wraps these in an Electron application which can be distributed.

The resulting application is however a bit fat, easily consuming 90MB of storage. This is primarily due to Chromium and NodeJS being a part of Electron.

 

Over- and under-clocking Refresh Rate

Recently I have been working on a HTML5 game using Pixi.js. One issue I have come across when doing web game programming is that it is not possible to disable vsync to test my game with higher and lower FPS.

The window.requestAnimationFrame() fires before the next repaint and is therefore tied to the refresh-rate of the monitor in use. For a 60hz monitor, the function fires every 16.66ms.

One could create a custom interval timer to simulate different refresh rates. This works fairly well, although the update will for obvious reasons be out of sync with the monitor.

Another method is to change the refresh-rate of the monitor using INI patching on Windows or using GPU tools such as NVIDIA Control Panel. A monitor is designed for a specific refresh-rate, where 60hz is the most widely PC monitor refresh rate.

Depending on the monitor, it is sometimes possible to over-clock the monitor yielding higher refresh rate. Similarly, under-clocking can be use to reduce the refresh-rate. For my 60hz DELL 2515h monitor I can increase the refresh-rate to 80hz before the monitor goes blank.

This allows me to test different frame rates, while preserving vsync, when developing HTML5 games. Similarly, I can reduce the frame-rate by under-clocking the monitor to e.g. 50hz or 30hz.

For NVIDIA GPUs, changing refresh-rates can easily be done through the NVIDIA Control Panel:

refreshrate.png

The Test button will test the refresh rate before adding it to the list. When added, you can select the custom refresh rates from the drop-down menu to the right.

This can be done even when the game is loaded in the browser. A site such as https://www.vsynctester.com/ can be used to verify that the refresh rate of monitor is in effect in the browser.

 

 

 

 

 

8bit Painter – a pixel art editor

Making pixel art has never been a hobby of mine until I stumbled upon 8bit Painter for Android. This app is a bitmap editor with very few features and a lot of constraints – however, this also makes it easy to use on a handheld device such as my Galaxy S5 phone.

Features more or less are:

  • Gallery list with all images made in the app.
  • Grid with each cell representing a single pixel.
  • Pan and Zoom
  • Fixed canvas sizes from 16 x 16 to 128 x 128, nothing customization here.
  • Ereaser, Pen, Fill and Picker tools.
  • Colorpicker with presets, brightness and saturation support.
  • Export to e.g. Google drive

Its an awesome app to use when idling with ones phone, e.g. in a meeting without an interesting agenda 🙂

Some stuff I made using the app:

pixelart