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
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workkloads.

Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Issue and Present Verifiable Credentials With Spring Boot and Android
  • Secure Your Frontend: Practical Tips for Developers
  • A Practical Guide to Securing NodeJS APIs With JWT
  • How to Set up OAuth JWT Flow and mTLS in the Salesforce Connector for a MuleSoft App

Trending

  • It’s Not About Control — It’s About Collaboration Between Architecture and Security
  • How to Configure and Customize the Go SDK for Azure Cosmos DB
  • Recurrent Workflows With Cloud Native Dapr Jobs
  • Beyond Linguistics: Real-Time Domain Event Mapping with WebSocket and Spring Boot
  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
30.9K 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

  • Issue and Present Verifiable Credentials With Spring Boot and Android
  • Secure Your Frontend: Practical Tips for Developers
  • A Practical Guide to Securing NodeJS APIs With JWT
  • How to Set up OAuth JWT Flow and mTLS in the Salesforce Connector for a MuleSoft App

Partner Resources

×

Comments
Oops! Something Went Wrong

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

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

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 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!