Creating a JWT auth server in 1 second
Creating and setting up a JWT server requires some tedious and repetetive steps. In this article we look at how you can use Magic to create it in 1 second
Join the DZone community and get the full member experience.
Join For FreeSecurity is one of those things you shouldn't play around with yourself, unless you know what you're doing. This is the reason products such as Identity Server has gained such momentum and popularity. However, Identity Server is extremely difficult to configure correctly, and OIDC is also arguably a "hack" on top of OAuth2. JWT on the other hand, is dead simple to understand, and was created explicitly to authenticate and authorise users, contrary to OAuth that was originally created for an entirely different purpose. Hence, JWT is just as secure as OpenID Connect, only a gazillion times easier to understand and implement.
In the following video I demonstrate how to create your own JWT server using Magic in 1 second. Notice, Magic is a commercial product, and you need to pay a small fee to use it in a production environment - But compared to the number of hours you'd have to spend rolling your own Enterprise Single Sign On solution using JWT, I'm confident in that the license costs are small in comparison.
When you are done following the recipe in the above video, you can check out the scaffolded Angular code in the HttpService called "AuthService", to see the URLs you need to use to invoke operations towards your auth database - And to authenticate a user to retrieve a secure JSON Web Token, you can check out the "HttpService" in the same folder. If you're using Angular, the way to authenticate your user becomes as follows, assuming you add a dependency injected HttpService to your component's constructor.
x
this.httpService.authenticate('username', 'password').subscribe(res => {
const jwtToken = res.ticket;
/*
* Store your above jwtToken in e.g. localStorage for later use.
* Then later when you want to invoke an endpoint requiring a
* token, you can add it to your Authorization HTTP header
* of your invocations.
*/
});
The above code assumes you've got an HttpService similar to the one found in the scaffolded Magic Angular frontend. Feel free to copy and paste the Magic one into your own Angular project if you wish.
At this point, the only thing you'll need to do yourself, is to use any favourite method of yours to secure your HTTP rest endpoints, requiring a valid JWT token to invoke them. In addition, if you want to use tokens generated by your Magic backend, you'll need to share your JWT Secret Key between Magic and your other app. If you do this in a .Net Web API backend for instance, this would allow you to use the Authorize attribute on your Controller endpoints, such as the following illustrates.
xxxxxxxxxx
[Route("foo")]
[Authorize(Roles = "admin")]
public class FooController : Controller
{
[HttpGet]
[Route("bar")]
public IActionResult Bar()
{
return new ObjectResult("Yup! You're authenticated");
}
}
Then to add up the middleware, validating your JWT token, you can use something like the following if you're in .Net Core land. The following code would normally be found in your Startup class.
x
public void ConfigureServices(IServiceCollection services)
{
// Other init stuff here ...
var secret = ""; /* ... get secret from config here ... */
services.AddAuthentication(x =>
{
x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(x =>
{
x.RequireHttpsMetadata = true;
x.SaveToken = true;
x.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = false,
ValidateAudience = false,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
IssuerSigningKeyResolver = (token, secToken, kid, valParams) =>
{
var key = Encoding.ASCII.GetBytes(secret);
return new List<SecurityKey>() { new SymmetricSecurityKey(key) };
}
};
});
}
And VOILA! You've secured your entire .Net Core Web app, in addition to that you have an authentication and authorisation backend, and a frontend to administrate your users database. More importantly probably, you've created a Single Sign On solution, that you can now reuse in all of your enterprise development efforts.
Opinions expressed by DZone contributors are their own.
Comments