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
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • HAIP 1.0 for Verifiable Presentations: Securing the VP Flow
  • Secrets in Code: Understanding Secret Detection and Its Blind Spots
  • Building a Production-Ready MCP Server in Python
  • JWT Policy Enforcement, Rate Limiting, IP White Listing: Using Mulesoft, API Security, Cloudhub 2.0

Trending

  • Throughput vs Goodput: The Performance Metric You Are Probably Ignoring in LLM Testing
  • How AI Is Rewriting Full-Stack Java Systems: Practical Patterns with Spring Boot, Kafka and WebSockets
  • The Cost of Knowing: When Observability Becomes the Outage
  • The 7 Pillars of Meeting Design: Transforming Expensive Conversations into Decision Assets
  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 user avatar
Thomas Hansen
DZone Core CORE ·
Jul. 12, 20 · Tutorial
Likes (5)
Comment
Save
Tweet
Share
31.2K Views

Join the DZone community and get the full member experience.

Join For Free

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

  • HAIP 1.0 for Verifiable Presentations: Securing the VP Flow
  • Secrets in Code: Understanding Secret Detection and Its Blind Spots
  • Building a Production-Ready MCP Server in Python
  • JWT Policy Enforcement, Rate Limiting, IP White Listing: Using Mulesoft, API Security, Cloudhub 2.0

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • 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