An example Go (golang) REST service that uses JWT (JSON Web Tokens) and Negroni

Post to Twitter

I’ve been messing with the idea of re-writing a project of mine in Go (for fun and learning). While I’ve been looking over my options I decided to evaluate JWT (JSON Web Tokens) rather than rolling my own concoction (which is never really a good idea). I looked around at what others were doing and stumbled upon this video which linked to this example code. The code uses the jwt-go library as well as Negroni. The issue I ran into was it didn’t work with the latest version (v3.0) of jwt-go. Today, I’ll go over the modifications and resulting code to get JWT with Go working in simple Negroni REST service.

Note: I don’t claim this simple example to be security compliant – use at your own risk.

One of the first things I did to get the code working was to read over the jwt-go version 2 to 3 migration guide. This provided most of the knowledge to make the changes. The rest of what I needed I got from reading issues with the jwt-go project and looking over the source code.

Here is the working code (again, modified from the sources I specified earlier):

Testing this out is fairly simple. I’m using Postman to make the calls. First off let’s try to hit the resource endpoint which is restricted.

As you can see we cannot hit the resource endpoint without a valid token.

Let’s utilize the login resource and fetch a token, however, we will use an invalid user to simulate another failure.

Now you’ll see we get a token back in the form of XXXXX.YYYYY.ZZZZZ You need to take that token and put it into the header with a header key value of Authorization and then in the value add “Bearer TOKEN-HERE“. Make sure there is a space after the word Bearer. See the JWT website for an introduction if this is confusing.

And we should be rewarded now with access:

That’s it!

Post to Twitter

This entry was posted in Go, Open Source. Bookmark the permalink.

3 Responses to An example Go (golang) REST service that uses JWT (JSON Web Tokens) and Negroni

  1. Peter Yates says:

    Thanks for this, it really helped!

  2. DiegoMachado says:

    Hi, Chad.

    I’ve noticed that the code as it is test both “username” and “password” but only do anything if the password is wrong (in LoginHandler).
    You should do something in case the username is wrong as well.
    So, the line 121 should be:
    if strings.ToLower(user.Username) != “someone” || user.Password != “password”

  3. sumit says:

    Thanks!

Leave a Reply

Your email address will not be published. Required fields are marked *