Using JWT Authentication with Swagger and Node.js

TL;DR: check the code on Github

I recently decided to use Swagger as the underlying technology for a Node.js REST API. Swagger (or it’s new “enterprise-friendly” OpenAPI branding) allows you to easily define a RESTful API using a JSON or YAML schema. Not only does it enforce you to follow all of REST’s best practices, it also provides a few very interesting tools that simplify the development process. A couple of examples are the Swagger Editor, that allows you to edit the API spec and see changes in real time, Swagger UI that automatically builds beautiful documentation, and Swagger Codegen, that generates the first version of the API endpoints’ code. Furthermore, there are many tools and integrations built for Swagger by its community.

While Swagger looked like a great fit for what I was looking for and everything started out nicely, some limitations soon became apparent. The first that I encountered is related to the use of JSON Web Tokens (JWT) for authentication purposes. Swagger’s specification allows for two types of mechanisms: OAuth, and what they call “apiKey”. Since JWT is definitely not OAuth, we have to use use “apiKey” to define that the JWT token will be sent in the HTTP Authorization header as “Bearer token_string“:

Furthermore, if we want to have different roles and manage the access to each API endpoint based on the user’s role, we will have to extend the Swagger spec, as it does not allow this for “apiKey” authentication. We can allow for role-based access as follows:

After the Swagger configuration is defined, we need to write the code to actually make this work. Here I will use Express and swagger-tools to care care of all the heavy lifting:

As you can see in line 13, the security checks are handed off to the verifyToken function in the auth module. Here is the code:

We just verify that the request presents a valid token (lines 21 through 27) and that the role of the user (which is saved in the token) matches one of the roles of the endpoint (line 13 and 29). The final piece of the puzzle is issuing a JWT with the user’s role as part of its payload:

Just return the token when the user correctly logs in, and you’re set:

And that’s basically it! All the code is available on Github, so feel free to check it out and test it for yourself.

Codebits VII (2014)

Codebits VII

After a year and a half of waiting, Codebits VII finally took place again from the 10th to the 12th of April. Codebits, for those that don’t know, is a 3-day technological event where the 900 (!!!) participants can attend dozens of talks, enter in the 48h programming contest, participate in workshops, and basically have tons of fun. I’ve been attending since the 4th edition in 2010 (you can check my previous posts here, here and here), and each edition has been even more awesome than the previous one. This year it was no exception.


16818137_qBK6Q 16818110_qahK9

For the second year in a row, Codebits had a Hardware Den where you could attend workshops on robotics, electronics and Arduino, and ride on the immersive Tron motorcycles (they even made it to Gizmodo and CNET!) with an Oculus Rift, see BeeVeryCreative’s 3d printer in action, or control the RAPOSA robot, also with an Oculus Rift. There was also another edition of the Presentation Karaoke, where stand-up comedy meets random powerpoint presentations that the participants have never seen in their life. Once again I participated in yet another edition of the Amazing Codebits Quiz Show (think of it as the “Who Wants to be a Millionare?” for geeks), but it ended like all the previous ones: elimination in the first round. I hope I’ll make it to the finals someday 🙂

16818130_G22q6 16818161_3rOvB

This year there were a total of 49 talks, in 5 different simultaneous tracks. I submitted a talk proposal about cryptocurrencies, which was accepted. At first I thought I was going to give the talk in one of the smaller stages, but lots of people wanted to attend the talk which got me bumped to the main stage just a couple of hours before. It was friggin’ terrifying! I think it went well, but I still have to check to video to see what kind of nonsense I was babbling about 🙂 At least it generated a very interesting discussion in the end, which was what I was aiming for.

16818154_urYfD

I participated with David Jardim, Tiago Rodrigues, and Valéria Pacheco in the 48h programming contest, with the Babel Talk project. It consisted of a mobile application that allows users to communicate using their voice with anyone in the world, regardless of their language. The application translates voice from one language to another transparently using several Google and Microsoft APIs. We ended up in 5th place in the jury’s choice category, which was the icing on top of the cake! It’s always an honor to receive an award in Codebits, since it attracts some of Portugal’s best talents in the area of Computer Science. The quality of the projects just keeps getting higher and higher every year, with notable examples such as this year’s winning project, NeLo.

16834382_5BioK

There are so many other awesome things that happen at Codebits… From the badge hunt, to the lightning talks, nuclear chiliquadrocopters, crowd pong, nerf guns, that INCREDIBLE video mapped intro, free food (and Red Bull!), the GoT throne, world-class speakers (John Graham-Cumming and Christian Heilmann, just to name a couple), people zip sliding over your head, bean bag madness, retro computing area, the amazing organizers, and the friendly people all around that will gladly talk to you about their crazy-ass projects. Codebits is the Mecca of geeks, and it simply has to be experienced. If you have never applied, please do yourself a favour and go to Codebits VIII next year!

NodecopterLX 2013

In October, the first Portuguese Nodecopter event was held in Lisbon. Nodecopter is a hackathon that enables the participants to control real quadrocopters using a programming language. These events started in October 2012, and have since then spread to many different countries. Since there was a big Javascript conference coming up, LXJS, we decided to bootstrap NodecopterLX by inviting their participants.

We had around 35 participants in a total of 11 teams. Luckily, no quadrocopter was harmed and everyone had a blast! There were many demos by the end of the day, and, more importantly, our participants had the chance to learn how to program some cool robots. I’ll leave you with some photos (but you can check all of them over at our Google+ page):

IMG_0987

IMG_1002

IMG_0953

IMG_1008

PS: I’d like to thank our awesome sponsor Flipside, our partners Inspiring, IST, ISCTE-IUL and Instituto de Telecomunicações, Andrew Nesbitt and Gilles Ruppert for being awesome and bringing some extra AR.Drones, and the rest of the team: Daniel Gomes, David Dias, João Jerónimo, Joaquim Serafim, Pedro Dias, Samuel Gordalina and Tiago Carlos. Make sure you follow our Twitter account @nodecopterlx to know when we are preparing the next event 🙂

Robô Bombeiro 2013

Recently some colleagues and I participated in the Robô Bombeiro 2013 (Firefighter Robot) competition, which has been organized by the Guarda Polytechnic Institute for 11 consecutive years. The objective of the competition is to build a robot that is able to navigate in a maze-like environment, find a fire (which is represented by a candle), and extinguish it. Participants are free to choose whatever design they want for their robot, and how they want to extinguish the flame. The environment has 4 rooms which are connected by corridors. In the entrance of a room there is always a white line that the robot can detect. The configuration of the environment can change, for instance, certain doors might be placed in a different location and an obstacle (represented by a sheep) can block a corridor in one of three places.

Robô Bombeiro 2013 Guarda

There are several different modes that a team can choose to participate in for extra points. In one of the modes, for instance, the robot must start its mission after it detects a sound with a certain frequency, instead of waiting for the push of a button. In a different mode, the robot must start and end in a random room, instead of the the regular white circle. The competition had 22 teams in the high school league and 24 in the university league. Our robot, IEEE Firefighter, competed in the university league, and our team was composed of seven BSc, MSc and PhD students. It was our first robotics competition and we had only one month to prepare. Due to the lack of time, we took the easiest route: we built our robot using the Lego Mindstorms NXT. Our robot was equipped with a rotating turret that enabled it to quickly scan a room for a candle with two infrared/flame sensors, three sonars for obstacle avoidance, a color sensor to detect the lines at the entrance of the rooms, and a fan to put out the fire. Due to the NXT’s limited sensor and actuator ports, we added an Arduino with a Bluetooth module, which controlled the two flame sensors, a microphone, a couple of buttons and the fan.

IEEE Firefighter

Things started going badly as soon as we got to the venue. The conditions we tested our robot in proved to be quite different from the real thing. The environment’s floor gave us some headaches because of our robot’s tracks, and the 35º Celsius in the gym were messing with the infrared sensors. We also had to tweak our algorithm because of the “sheep” obstacle, since we kept knocking it down. After spending the whole morning changing things, we had to hand in our robot to the judges.

There were a total of three rounds, and every robot had to be tested. This translated to roughly 90 minutes per round. I wasn’t expecting it to be such an intense experience! Waiting for your team’s name to be called out, and then hoping that both your algorithm and hardware work perfectly is totally nerve-wracking. Usually in other types of competition, such as sports, you are in direct control of your actions and you can affect the outcome of a match. In this case, we simply had to observe as our little robot did what we programmed it to do.

In the first round we were able to quickly put out the fire and ended up in a surprising first place. In the second round, we were successful at putting out the fire but unable to return to the starting position. This placed us in the 2nd overall position. The third and final round was a disaster for us. Our robot crashed on its way to the candle and it kicked us all the way back to 7th place. We were a bit sad at first, but we quickly bounced back – it was a great result for our first try. Next year we’ll try to enter the competition again, but with a few kinks ironed out. A huge thanks to the team! Here’s a group photo – Adriano, Paulo, moi, Mário, Tiago, Carlos and Vasco. See you next year, Guarda!

IMG_0360

Bluetooth communication between Arduino and Lego NXT using leJOS

The Lego NXT is a robotics platform that makes it easy to start creating robots with standard Lego pieces, an “intelligent brick” and a wide variety of sensors and actuators. One of the problems of the NXT is that it only has 3 motor ports and 4 sensor ports. If you want to extend the amount of sensors and actuators that the NXT can have access to, a solution is to use an Arduino with a Bluetooth module. In our case, we used the leJOS firmware for the NXT, which allows us to write the code for the robot in Java.

The first step is to pair both devices, which you can do by going to the Bluetooth menu  on the NXT. Afterwards, you can access the Arduino through its Bluetooth ID via the Java code:

It is VERY important that you use the RAW mode (NXTConnection.RAW) when connecting to a Bluetooth device other than another NXT brick. By default leJOS sends some extra bytes with every communication, which can mess up your data transmission. After the connection is established, you can open the input and/or output streams and start sending data:

Make sure that you read data from the stream on a different thread if you don’t want your robot to block while waiting for data. In our case, the NXT brick was communicating with an Arduino. Here’s an example of how that looks like:

Something that gave us some headaches was the difference between Serial.print() and Serial.write(). The value that you pass to Serial.print(), even if it’s an int, gets converted to its corresponding character. For instance, Serial.print(5) will send the character ‘5’, which corresponds to the ASCII value of 53. If you want to send the integer 5, use Serial.write(5).