DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Future-Proofing JWT Security: Crypto-Agility, Post-Quantum Signatures, and IAM Migration
  • Designing Secure REST APIs With Spring Boot
  • Refresh Token Rotation in Node.js: Stopping Token Theft Without Logging Users Out
  • Implementing Secure API Gateways for Microservices Architecture

Trending

  • AI-Era Cybersecurity, Part 1: Mapping Glasswing, Daybreak, Lightwell and the Tools Racing to Find and Fix Bugs
  • How Kestra Unifies Enterprise Workflow Orchestration and Agentic AI
  • Building a Real Pipeline With senro: Monorepos, Caching, and Triggers
  • Introducing senro: A Pipeline Engine You Program in Go

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  1. DZone
  2. Software Design and Architecture
  3. Security
  4. Creating a JWT auth server in 1 second

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

By 
Thomas Hansen
DZone Core CORE ·
Jul. 12, 20 · Tutorial
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
31.4K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

Security 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.

TypeScript
 




x


 
1
this.httpService.authenticate('username', 'password').subscribe(res => {
2
  const jwtToken = res.ticket;
3

          
4
  /*
5
   * Store your above jwtToken in e.g. localStorage for later use.
6
   * Then later when you want to invoke an endpoint requiring a
7
   * token, you can add it to your Authorization HTTP header
8
   * of your invocations.
9
   */
10
});
11

          


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.

C#
 




xxxxxxxxxx
1
11


 
1
[Route("foo")]
2
[Authorize(Roles = "admin")]
3
public class FooController : Controller
4
{
5
  [HttpGet]
6
  [Route("bar")]
7
  public IActionResult Bar()
8
  {
9
    return new ObjectResult("Yup! You're authenticated");
10
  }
11
}


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.

C#
 




x
4
33


 
1
public void ConfigureServices(IServiceCollection services)
2
{
3
  // Other init stuff here ...
4

          
5
  var secret = ""; /* ... get secret from config here ... */
6
  services.AddAuthentication(x =>
7
  {
8
    x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
9
    x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
10
  })
11
  .AddJwtBearer(x =>
12
  {
13
    x.RequireHttpsMetadata = true;
14
    x.SaveToken = true;
15
    x.TokenValidationParameters = new TokenValidationParameters
16
    {
17
      ValidateIssuer = false,
18
      ValidateAudience = false,
19
      ValidateLifetime = true,
20
      ValidateIssuerSigningKey = true,
21
      IssuerSigningKeyResolver = (token, secToken, kid, valParams) =>
22
      {
23
        var key = Encoding.ASCII.GetBytes(secret);
24
        return new List<SecurityKey>() { new SymmetricSecurityKey(key) };
25
      }
26
    };
27
  });
28
}
29

          


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.

JWT (JSON Web Token)

Opinions expressed by DZone contributors are their own.

Related

  • Future-Proofing JWT Security: Crypto-Agility, Post-Quantum Signatures, and IAM Migration
  • Designing Secure REST APIs With Spring Boot
  • Refresh Token Rotation in Node.js: Stopping Token Theft Without Logging Users Out
  • Implementing Secure API Gateways for Microservices Architecture

Partner Resources

×

Comments

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook