complete jwt authentication in csharp

To complete JWT authentication in C#, you can follow the steps below:

  1. Install the Microsoft.AspNetCore.Authentication.JwtBearer package:
main.cs
Install-Package Microsoft.AspNetCore.Authentication.JwtBearer -Version <version number>
88 chars
2 lines
  1. Configure JWT authentication services in Startup.cs:
main.cs
services.AddAuthentication(options =>
{
    options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
    options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
    options.Authority = "https://your-auth0-domain.auth0.com/";
    options.Audience = "https://your-auth0-api.com/";
});
349 chars
11 lines
  1. Add the [Authorize] attribute to the appropriate controllers or actions:
main.cs
[Authorize]
[ApiController]
[Route("[controller]")]
public class ApiController : ControllerBase
{
    // Controller methods
}
126 chars
8 lines
  1. Generate JWT tokens:
main.cs
var tokenHandler = new JwtSecurityTokenHandler();
var key = Encoding.ASCII.GetBytes("your_secret_key_here");

var tokenDescriptor = new SecurityTokenDescriptor
{
    Subject = new ClaimsIdentity(new Claim[]
    {
        new Claim(ClaimTypes.Name, "John Doe"),
        new Claim(ClaimTypes.Email, "johndoe@example.com")
    }),
    Expires = DateTime.UtcNow.AddHours(1),
    SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
};

var token = tokenHandler.CreateToken(tokenDescriptor);
var tokenString = tokenHandler.WriteToken(token);
599 chars
17 lines
  1. Send the generated token in the Authorization header of the HTTP request:
main.cs
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", /* Your JWT token here */);
117 chars
2 lines

Note that you should replace your-auth0-domain and your-auth0-api with your Auth0 domain and API Identifier respectively. Also, make sure to replace your_secret_key_here with a secret key that is only known by your server.

gistlibby LogSnag