How to Generate and Use JWT Bearer Tokens in .NET Core API

Updated on: June 9, 2025

Securing your API with JWT (JSON Web Tokens) is a powerful and modern way to authenticate and authorize users. In this blog post, we’ll explore how to generate a JWT Bearer token in .NET Core, set it in headers, and validate it.

🔧 Prerequisites

  • Visual Studio or VS Code
  • .NET Core SDK installed
  • NuGet Package: System.IdentityModel.Tokens.Jwt

🧱 Step 1: Install JWT Package

Install-Package System.IdentityModel.Tokens.Jwt

🛡️ Step 2: Create Token Generator

Create a helper class to generate the token:

public class JwtHelper
{
    private readonly string _key = "YourSecretKey@123";

    public string GenerateToken(string username)
    {
        var tokenHandler = new JwtSecurityTokenHandler();
        var key = Encoding.ASCII.GetBytes(_key);

        var tokenDescriptor = new SecurityTokenDescriptor
        {
            Subject = new ClaimsIdentity(new[] {
                new Claim(ClaimTypes.Name, username)
            }),
            Expires = DateTime.UtcNow.AddHours(1),
            SigningCredentials = new SigningCredentials(
                new SymmetricSecurityKey(key), 
                SecurityAlgorithms.HmacSha256Signature)
        };

        var token = tokenHandler.CreateToken(tokenDescriptor);
        return tokenHandler.WriteToken(token);
    }
}

🔐 Step 3: Create Login API

[HttpPost("login")]
public IActionResult Login([FromBody] LoginModel model)
{
    if (model.Username == "admin" && model.Password == "password")
    {
        var jwt = new JwtHelper();
        var token = jwt.GenerateToken(model.Username);

        Response.Headers.Add("Authorization", "Bearer " + token);
        return Ok(new { token });
    }
    return Unauthorized();
}

🔍 Step 4: Get Token from Header

[HttpGet("protected")]
public IActionResult Protected()
{
    var token = Request.Headers["Authorization"].ToString().Replace("Bearer ", "");

    if (string.IsNullOrWhiteSpace(token))
        return Unauthorized("No token provided.");

    var handler = new JwtSecurityTokenHandler();
    var jwtToken = handler.ReadJwtToken(token);

    var username = jwtToken.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Name)?.Value;

    return Ok($"Hello {username}, your token is valid.");
}

⚙️ Step 5: Configure Authentication

In Startup.cs or Program.cs:

services.AddAuthentication("Bearer")
    .AddJwtBearer("Bearer", options =>
    {
        options.TokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuer = false,
            ValidateAudience = false,
            ValidateIssuerSigningKey = true,
            IssuerSigningKey = new SymmetricSecurityKey(
                Encoding.ASCII.GetBytes("YourSecretKey@123"))
        };
    });

app.UseAuthentication();
app.UseAuthorization();

📌 Testing the API

  1. Call POST /login with credentials
  2. Copy the token returned in the header/response
  3. Call GET /protected with: Authorization: Bearer eyJhbGciOi...

🚀 SEO Tips to Index This Blog

  • Use clean meta tags and schema markup
  • Add this blog in sitemap.xml of your Blogger or website
  • Share on social and submit URL to Google Search Console
  • Use canonical link for preferred indexing

📚 Conclusion

Using JWT for securing .NET Core APIs is a modern, scalable approach. With this guide, you can generate tokens, set them in headers, and authorize protected endpoints securely.

Happy coding!

Leave a Reply

Your email address will not be published. Required fields are marked *