Learn JWT Authentication in ASP.NET Core Web API using HMAC-SHA256 with complete beginner-to-advanced examples. Compare OAuth 2.0, JWT, API Keys and HMAC-SHA256, implement secure authentication, understand payment gateway webhook verification, and build production-ready .NET APIs.
Imagine you have built an amazing ASP.NET Core Web API for an online banking system.
The API provides endpoints like:
POST /login
GET /accounts
GET /transactions
POST /money-transfer
POST /change-passwordEverything works perfectly.
Then one day…
Someone discovers your API URL.
Instead of opening your website, they directly call:
POST
/api/money-transferwith
Amount = ₹5,00,000and
Account = 123456789Your API happily processes the request.
Money is transferred.
No login.
No verification.
No identity.
No authorization.
Would you trust such an application?
Absolutely not.
This is exactly why API Security exists.
Today, almost every mobile application, website, banking application, OTT platform, healthcare system, and government portal communicates through APIs.
If your API is insecure, your entire application becomes insecure.
This is why companies like Microsoft, Google, Amazon, Razorpay, PhonePe, Paytm, Netflix, and Uber invest millions of dollars every year in API security.
Before learning JWT Authentication, we first need to understand why authentication exists and what problem it solves.
What is an API?
API stands for Application Programming Interface.
Think of an API as a waiter in a restaurant.
Imagine you visit a restaurant.
You don’t walk directly into the kitchen.
Instead,
You tell the waiter:
“Please bring me one Paneer Butter Masala.”
The waiter takes your request.
The kitchen prepares the food.
The waiter delivers the food back.
You never directly interact with the kitchen.
Exactly the same thing happens in software.
Client
↓
API
↓
DatabaseThe API acts as a secure bridge between users and the application’s internal resources.
Without APIs,
- Mobile apps cannot communicate with servers.
- Websites cannot retrieve data.
- Payment gateways cannot process transactions.
- AI applications cannot generate responses.
- Cloud applications cannot exchange information.
APIs are the heart of modern software systems.
Why APIs Are Becoming Prime Targets for Attackers
Imagine an e-commerce website.
It has APIs such as:
/login
/products
/cart
/orders
/payment
/adminEvery request from the frontend eventually reaches one of these APIs.
If an attacker gains access to these endpoints, they may attempt to:
- View another customer’s orders.
- Modify product prices.
- Delete records.
- Transfer money.
- Download sensitive customer data.
- Create fake administrator accounts.
This is why APIs are among the most attractive targets for cybercriminals.
Unlike websites, APIs often expose direct access to business logic and sensitive data.
Real-World Example: Online Banking
Suppose a banking application exposes the following endpoint:
GET
/api/account/balanceWhen a legitimate customer logs in, the API returns:
Balance
₹2,35,000Now imagine anyone could simply type:
https://bank.com/api/account/balanceand receive another customer’s account balance.
This would be a catastrophic security failure.
Instead, the bank requires proof of identity before responding.
That proof is called authentication.
The Three Fundamental Questions Every Secure API Must Answer
Every incoming request should answer three questions.
1. Who are you?
This is Authentication.
Example:
Username
Passwordor
JWT TokenThe server verifies the identity.
2. What are you allowed to do?
This is Authorization.
A customer can:
- View their profile
- Transfer money
- Download statements
But they should not:
- Delete all customers
- View another user’s account
- Access administrator functions
Authorization determines permissions after authentication.
3. Has the request been altered?
This is Integrity.
Suppose a payment request is sent:
Amount
₹100During transmission, an attacker modifies it to:
₹10,000The server must detect that the request has been tampered with.
Technologies like HMAC-SHA256 are specifically designed to verify message integrity.
Understanding Authentication
Authentication answers one simple question:
“Who are you?”
Every secure application performs authentication before granting access.
Examples include:
- ATM PIN verification
- Mobile OTP verification
- Google login
- Aadhaar authentication
- Biometric fingerprint scanning
- Face recognition
In software applications, authentication proves the user’s identity before any protected resource is accessed.
Everyday Analogy: Airport Security
Imagine you arrive at an international airport.
Before boarding the aircraft, the airline checks your passport and boarding pass.
They verify:
- Your identity
- Your ticket
- Your destination
Only after successful verification are you allowed to proceed.
This process is authentication.
Similarly, when you call a secure API, the server first checks your identity before processing your request.
Understanding Authorization
Authorization begins after authentication.
Suppose three users log into the same system.
Customer
Allowed to:
- View profile
- Place orders
- Make payments
Employee
Allowed to:
- View customer information
- Process orders
Cannot:
- Delete products
Administrator
Allowed to:
- Create users
- Delete users
- Manage products
- Access reports
- Configure the application
All three users are authenticated.
However, each has different permissions.
That difference is authorization.
Authentication vs Authorization
Many beginners confuse these concepts.
Think of a corporate office.
Step 1
A security guard checks your employee ID.
This verifies your identity.
Authentication is complete.
Step 2
Your access card determines which floors you can enter.
- HR Floor
- Finance Floor
- Server Room
- CEO Office
This is authorization.
Identity comes first.
Permissions come second.
Visual Representation
User
↓
Enter Username & Password
↓
Server Verifies Identity
↓
Authenticated
↓
Server Checks User Role
↓
Authorized
↓
Access GrantedAuthentication and authorization always work together but serve different purposes.
Why Username and Password Alone Are Not Enough
Years ago, applications relied solely on usernames and passwords.
The workflow looked like this:
Login
↓
Database Verification
↓
Session Created
↓
User Logged InThis approach worked well for traditional web applications.
However, modern applications have evolved significantly.
Today, a single user may access the same system through:
- Android app
- iPhone app
- Smartwatch
- Web browser
- Smart TV
- Desktop application
- Third-party integrations
- AI assistants
Managing sessions across all these platforms becomes increasingly complex.
This challenge led to the adoption of token-based authentication, where users receive a digitally signed token after successful login.
The most widely used token standard today is JWT (JSON Web Token).
Why Modern Companies Prefer Token-Based Authentication
Companies like Microsoft, Amazon, Netflix, Google, Spotify, and many fintech organizations use token-based authentication because it offers:
- Scalability
- Stateless architecture
- Better performance
- Easier integration with mobile apps
- Improved cloud compatibility
- Support for microservices
- Enhanced security when implemented correctly
JWT has become the industry standard for securing RESTful APIs.
Where You Use JWT Every Day
You may not realize it, but JWT is likely used every day when you:
- Log into an online banking app
- Access a food delivery service
- Use an e-commerce website
- Stream movies on an OTT platform
- Sign in with Google or Microsoft
- Access cloud dashboards
- Use enterprise business applications
Behind the scenes, these applications often issue a signed token that proves your identity without requiring you to enter your password on every request.
API Security Fundamentals and Authentication Methods
Example: Food Delivery Application
Suppose you develop a food delivery application.
Available APIs:
GET /restaurants
GET /menu
POST /order
POST /payment
GET /orderHistory
DELETE /restaurantQuestion:
Should everyone be allowed to call every API?
Absolutely not.
Anyone can view restaurants.
Only logged-in users should place orders.
Only restaurant owners should update menus.
Only administrators should delete restaurants.
This is where API security begins.
The CIA Triad of Security
Every secure application is built around three principles.
Confidentiality
Integrity
AvailabilityThese three concepts are known as the CIA Triad.
They form the foundation of information security.
1. Confidentiality
Confidentiality means:
Only authorized people can access the information.
Example:
Your bank statement.
Only you should be able to read it.
Not another customer.
Not another employee.
Not an attacker.
Techniques used:
- Authentication
- Authorization
- Encryption
- Access Control
2. Integrity
Integrity means:
Data should never change without authorization.
Example:
Original request
Transfer ₹1,000If someone changes it during transmission:
Transfer ₹1,00,000The server must detect the modification.
This is exactly why HMAC-SHA256 exists.
Later in this blog we’ll see how payment gateways use it.
3. Availability
Availability means:
The application should remain accessible.
Imagine UPI stopping for one day.
Millions of transactions would fail.
Therefore applications must protect themselves against:
- DDoS attacks
- Server failures
- Database crashes
- Infrastructure outages
Why APIs Are Easier to Attack Than Websites
A website hides many implementation details.
APIs expose endpoints directly.
Example
POST
/api/loginAn attacker can automate thousands of requests.
Password123
Password1234
Admin123
Welcome123This is called a Brute Force Attack.
Without protection, the API may eventually reveal valid credentials.
Common API Attacks
Let’s understand how attackers think.
1. Broken Authentication
Suppose an API accepts:
Username
PasswordBut never expires the session.
An attacker who steals the session gains permanent access.
This is one of the most common vulnerabilities.
2. Broken Authorization
Imagine:
GET
/api/user/1001returns
Ashutosh JhaNow an attacker changes the URL.
GET
/api/user/1002The server returns another customer’s information.
This is called Broken Object Level Authorization (BOLA).
It is the #1 API vulnerability according to OWASP.
3. SQL Injection
Suppose the application creates SQL like this:
SELECT *
FROM Users
WHERE
Username='Admin'
AND
Password='123'An attacker enters
'
OR
1=1The database now returns all users.
Modern applications prevent this using:
- Entity Framework
- Parameterized Queries
- ORM Frameworks
4. Token Theft
Suppose JWT is stored insecurely.
An attacker steals it.
Now the attacker becomes the user.
This is why token storage matters.
We’ll discuss this in later chapters.
5. Replay Attack
Suppose a payment request is intercepted.
Pay ₹500The attacker sends the same request again.
The payment executes twice.
How do payment gateways stop this?
Using
- Timestamp
- Nonce
- HMAC Signature
We’ll build this ourselves later.
The OWASP API Security Top 10
Every .NET developer should know these risks.
| Risk | Description |
|---|---|
| Broken Object Level Authorization | Accessing another user’s data |
| Broken Authentication | Weak login mechanisms |
| Broken Object Property Level Authorization | Unauthorized field access |
| Unrestricted Resource Consumption | No rate limiting |
| Broken Function Level Authorization | Normal users calling admin APIs |
| Unrestricted Access to Sensitive Business Flows | Abuse of business logic |
| SSRF | Server Side Request Forgery |
| Security Misconfiguration | Poor server settings |
| Improper Inventory Management | Forgotten APIs |
| Unsafe Consumption of APIs | Trusting external APIs blindly |
Learning JWT alone is not enough.
A secure developer understands these risks.
Different Ways to Secure an API
There isn’t a single authentication method.
Different applications use different techniques.
Let’s compare them.
1. Basic Authentication
One of the oldest authentication mechanisms.
Client sends
Username
Passwordwith every request.
Example
Authorization
Basic
QWRtaW46UGFzc3dvcmQ=Advantages
- Easy
Disadvantages
- Password travels every request
- Weak security
- Not suitable for production
Mostly used in:
- Internal tools
- Legacy systems
2. Session Authentication
Traditional ASP.NET applications use sessions.
Login
↓
Server creates Session
↓
Browser receives Cookie
↓
Cookie sent every request
↓
Server checks SessionAdvantages
- Easy
- Secure
Disadvantages
- Server stores session
- Difficult for microservices
- Poor scalability
3. API Key Authentication
Very common.
Client sends
X-API-Key
ABCD123456Examples
- Google Maps API
- Weather APIs
- OpenAI API
- Azure APIs
Advantages
- Very simple
- Fast
Disadvantages
- No user identity
- Difficult to revoke individually
- Can be leaked
Best for
Machine-to-machine communication.
4. JWT Authentication
The server creates a signed token.
Login
↓
JWT Created
↓
Client Stores Token
↓
Client Sends Token
↓
Server Validates Signature
↓
Access GrantedAdvantages
- Stateless
- Fast
- Scalable
- Cloud friendly
- Mobile friendly
Disadvantages
- Cannot easily revoke without additional mechanisms
- Secret key protection is critical
Best for
Modern REST APIs.
5. OAuth 2.0
OAuth is not just authentication.
It is an authorization framework.
Example
Login using Google.
Application
↓
Google Login
↓
User Grants Permission
↓
Google Issues Access Token
↓
Application Uses TokenOAuth is used when:
- Google Login
- Microsoft Login
- Facebook Login
- GitHub Login
OAuth is common in enterprise applications where third-party identity providers are involved.
6. HMAC Authentication
This is completely different.
Many beginners think HMAC authenticates users.
It doesn’t.
It authenticates requests.
Suppose the client sends:
Amount
₹5,000The client also generates:
HMAC Signatureusing a secret key.
The server generates the same signature.
If both signatures match:
Request AcceptedOtherwise:
Request RejectedHMAC guarantees:
- Message Integrity
- Authenticity
- Tamper Detection
Comparing API Security Methods
| Feature | Basic Auth | Session | API Key | JWT | OAuth 2.0 | HMAC-SHA256 |
|---|---|---|---|---|---|---|
| User Authentication | Yes | Yes | Limited | Yes | Yes | No |
| Authorization | No | Yes | No | Yes | Yes | No |
| Stateless | No | No | Yes | Yes | Yes | Yes |
| Mobile Friendly | Poor | Poor | Good | Excellent | Excellent | Excellent |
| Microservices | Poor | Poor | Good | Excellent | Excellent | Excellent |
| Prevents Request Tampering | No | No | No | No | No | Yes |
| Used by Payment Gateways | No | No | No | No | No | Yes |
| Used for Login | Yes | Yes | Rare | Yes | Yes | No |
| Recommended for Modern APIs | No | Limited | Sometimes | Yes | Yes | Alongside JWT |
Which Authentication Method Should You Choose?
The answer depends on your application.
Internal Company Tools
- Session Authentication or JWT
Mobile Applications
- JWT Authentication
Enterprise Applications
- OAuth 2.0 + JWT
Banking APIs
- JWT + HMAC-SHA256 + Mutual TLS
Payment Gateway Webhooks
- HMAC-SHA256
Public APIs
- API Keys + JWT
Microservices
- JWT + OAuth 2.0
There is no single solution for every scenario. Production systems often combine multiple mechanisms to achieve layered security.
What is JWT?
JWT stands for
JSON Web Token
It is a compact, URL-safe token used to securely transfer information between two parties.
A JWT contains information about the authenticated user and is digitally signed so that the server can verify its authenticity.
Unlike session-based authentication, JWT is stateless.
This means the server does not store login information for every user.
Instead, all necessary information travels inside the token itself.
Why Was JWT Created?
Imagine an e-commerce application with 10 million users.
If every logged-in user’s session is stored in server memory:
User A
↓
Session
↓
Server MemoryUser B
↓
Session
↓
Server MemoryUser C
↓
Session
↓
Server MemoryEventually,
10 Million Users
↓
10 Million SessionsProblems begin to appear:
- Huge memory consumption
- Difficult to scale
- Multiple servers cannot easily share session data
- Load balancing becomes complex
Modern cloud applications require a different approach.
Instead of storing sessions on the server, the server gives the client a signed token.
The client carries the token with every request.
This is the philosophy behind JWT.
JWT Authentication Flow
Let’s see the complete lifecycle.
User
↓
Login Request
↓
ASP.NET Core API
↓
Validate Username & Password
↓
Generate JWT
↓
Sign using HMAC-SHA256
↓
Return Token
↓
Client Stores Token
↓
Client Sends Token
↓
Authorization Header
↓
Server Verifies Signature
↓
API ExecutesNotice something important.
After login,
the server never needs to remember the user.
Everything required is inside the JWT.
What Does a JWT Look Like?
A real JWT looks like this:
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9
.
eyJzdWIiOiIxMjM0NTYiLCJuYW1lIjoiQXNodXRvc2ggSmhhIiwiUm9sZSI6IkFkbWluIiwiZXhwIjoxNzY0MjU2MDAwfQ
.
P0kgDd9VvA0x3Qv7xv2jM2xF5lQf5b4iFhA5LkLh8FgAt first glance,
it looks like random text.
It is actually composed of three parts.
Header
.
Payload
.
SignatureEvery JWT always has these three sections.
JWT Structure
Header
↓
Payload
↓
SignatureEach section has a specific responsibility.
Part 1 – Header
The Header tells the receiver
how the token was created.
Example:
{
"alg": "HS256",
"typ": "JWT"
}Let’s understand each property.
alg
Algorithm used for signing.
Example
HS256means
HMAC using SHA-256.
Other algorithms include
- HS384
- HS512
- RS256
- ES256
We’ll compare these later.
typ
Indicates the token type.
JWTSimple.
Nothing complicated.
Why Is the Header Important?
Imagine receiving a token.
How does the server know
whether it should verify using
- HS256
or
- RS256
The Header provides that information.
Without the Header,
the server wouldn’t know how to validate the signature.
Part 2 – Payload
The Payload contains user information.
Example
{
"sub":"101",
"name":"Ashutosh Jha",
"email":"ashutosh@example.com",
"role":"Admin",
"exp":1764256000
}This section is called Claims.
Claims describe the authenticated user.
Common JWT Claims
Subject (sub)
Unique user identifier.
Example
101Usually the database UserId.
Name
Ashutosh JhaDisplayed inside the application.
ashutosh@example.comUseful for identity.
Role
AdminRole-based authorization depends on this claim.
Example
Admin
Manager
Employee
StudentExpiration (exp)
Specifies when the token expires.
Example
Tomorrow
10:30 PMAfter expiration,
the token becomes invalid.
Important Note About Payload
Many beginners believe
JWT Payload is encrypted.
It is NOT.
It is merely Base64URL encoded.
Anyone possessing the token can decode the Payload.
Therefore,
never store
- Passwords
- Credit Card Numbers
- Aadhaar Numbers
- PAN Numbers
- Secret Keys
inside a JWT.
Store only information you are comfortable exposing.
Base64 Encoding Is NOT Encryption
Many developers confuse encoding with encryption.
Let’s understand.
Suppose your name is
AshutoshBase64 Encoding converts it into
QXNodXRvc2g=Can someone decode it?
Yes.
Immediately.
No secret key required.
Therefore,
Base64 is
NOT
encryption.
JWT Payload is simply encoded for compact transmission.
Part 3 – Signature
This is the most important part of JWT.
The Signature protects the token from modification.
It is generated like this:
HMACSHA256(
Base64(Header)
+
Base64(Payload),
SecretKey
)The output becomes the Signature.
Example
Header
+
Payload
↓
HMAC-SHA256
↓
Secret Key
↓
Digital SignatureWithout the Secret Key,
nobody can generate a valid signature.
Why Signature Matters
Imagine the Payload says
{
"Role":"Student"
}An attacker modifies it to
{
"Role":"Admin"
}Looks dangerous.
But the Signature was generated using
Role = StudentAfter modification,
the server generates a new signature.
The new signature becomes different.
Original Signature
≠
New SignatureImmediately,
the server rejects the token.
This is exactly why JWT is secure.
Understanding HMAC-SHA256
Let’s simplify it.
Suppose two friends share a secret password.
Secret Key
↓
TuxAcademy2026Friend A sends
Helloalong with a signature.
Friend B generates the same signature using the same secret.
If both signatures match,
the message is genuine.
Otherwise,
someone modified it.
JWT uses the exact same principle.
Why HMAC Uses a Secret Key
SHA256 alone creates a hash.
Anyone can hash the same data.
That means anyone could create a fake token.
HMAC solves this by introducing a secret key.
Message
+
Secret Key
↓
HMAC-SHA256
↓
SignatureWithout the Secret Key,
signature generation is impossible.
JWT Validation Process
When an API receives a JWT,
it performs these steps.
Receive Token
↓
Split Header
↓
Split Payload
↓
Split Signature
↓
Read Header
↓
Find Algorithm
↓
Generate New Signature
↓
Compare Both Signatures
↓
If Match
↓
Token Valid
↓
Otherwise RejectNotice something important.
The server never asks
“Is this token in my database?”
It simply verifies the signature.
That is why JWT authentication is called Stateless Authentication.
Why JWT Is So Fast
Traditional Session Authentication
Request
↓
Database
↓
Session Lookup
↓
ResponseJWT
Request
↓
Verify Signature
↓
ResponseNo database lookup.
No session retrieval.
No memory search.
This makes JWT extremely fast.
Why Microservices Love JWT
Imagine an e-commerce platform.
Authentication Service
↓
Product Service
↓
Payment Service
↓
Inventory Service
↓
Shipping ServiceEvery service receives the same JWT.
Every service independently verifies the signature.
No central session server is required.
This makes JWT ideal for:
- Microservices
- Cloud-native applications
- Kubernetes deployments
- Distributed systems
HS256 vs RS256
Two popular JWT signing algorithms are:
| Feature | HS256 | RS256 |
|---|---|---|
| Key Type | Shared Secret | Public/Private Key Pair |
| Speed | Very Fast | Slower |
| Complexity | Simple | More Complex |
| Best For | Internal APIs | Enterprise & Third-Party APIs |
| Used in ASP.NET Core | Yes | Yes |
Most beginner and enterprise internal applications start with HS256 because it is simpler and performs well.
For systems where multiple parties need to verify tokens without sharing the signing secret, RS256 is often preferred.
Common JWT Misconceptions
Myth 1: JWT encrypts data
False.
JWT signs data.
It does not encrypt it.
Myth 2: JWT cannot expire
False.
JWT should always include an expiration (exp) claim.
Myth 3: JWT is impossible to hack
False.
JWT is secure only when:
- Strong secret keys are used
- HTTPS is enforced
- Expiration times are reasonable
- Secrets are protected
- Validation is correctly implemented
Poor implementation can still lead to vulnerabilities.
Call to Action
Take the next step toward a successful career in data science.
If you are serious about building real data science skills that go beyond theory, TuxAcademy offers structured data science courses built around real project work with industry experienced trainers who have worked with actual data at scale.
Website: https://www.tuxacademy.org/
Course: https://www.tuxacademy.org/data-science-course-in-noida-complete-guide/
Email: info@tuxacademy.org
Phone: +91-7982029314
Visit the nearest center or book a free counseling session today.
Watch Video
- Data Science Project Explanation for Beginners
- Machine Learning Course Overview with Real Projects
- Data Science Career Advice | Short Video
- Machine Learning Basics Explained Quickly
- Machine Learning Quick Explanation
- Data Science Learning Path
- Programming Career Guidance
- Top IT Career Options Explained
- AI vs Data Science Career Comparison
Location:
Students searching for a data science course in Greater Noida West or SQL and data science training near Knowledge Park who want to build practical, job ready analytical skills will find TuxAcademy directly accessible from across the NCR region. Positioned near Knowledge Park, one of the most prominent education hubs in North India, the institute benefits from its proximity to key student zones such as Alpha 1 Greater Noida, Alpha 2 Greater Noida, Beta 1 Greater Noida, Gamma 1 Greater Noida, and Delta 1 Greater Noida, making it highly convenient for daily commuting students. The institute enjoys excellent connectivity through major transit points including Pari Chowk, Knowledge Park Metro Station, and the Noida Greater Noida Expressway, along with close proximity to popular commercial and student hubs such as Jagat Farm Market, Ansal Plaza Greater Noida, and Omaxe Connaught Place Greater Noida.
TuxAcademy is also easily accessible from major residential and student centric localities including Gaur City, Bisrakh, Techzone 4 Greater Noida West, Crossings Republik, Ek Murti Chowk, Sector 1 Greater Noida West, Sector 16B Greater Noida West, Greater Noida Sector 2, Ecotech 12 Greater Noida, Amrapali Dream Valley, Patwari Village, Milak Lachhi, Cherry County Greater Noida West, Roza Yakubpur, Eco Village 3 Greater Noida West, Iteda Greater Noida, Eco Village 1 Greater Noida West, Greater Noida Sector 8, Roza Jalalpur, Mahagun Mywoods Phase 2, Eco Village 2 Greater Noida West, Amrapali Leisure Valley, Greater Noida Sector 1, Greater Noida Sector 16B, Vedpura, and Charmurti Chowk, reinforcing its reach across densely populated student regions.

