This code demonstrates how to use
the JwtHelpers class to generate a JWT token based on a sample user object
UserTokens and JWT settings Jwtsettings. The generated token is then printed
along with other user details such as ID, username, expiration time, and user
type. Make sure to replace the sample data with your actual user data and JWT
settings
using
System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using Microsoft.AspNetCore.Mvc;
using
Microsoft.Extensions.Options;
using
Microsoft.IdentityModel.Tokens;
namespace WebApplication.Controllers
{
[ApiController]
[Route("[controller]")]
public class AuthController :
ControllerBase
{
private readonly JwtSettings _jwtSettings;
public AuthController(IOptions<JwtSettings>
jwtSettings)
{
_jwtSettings =
jwtSettings.Value;
}
[HttpPost("login")]
public IActionResult
Login([FromBody] LoginRequest model)
{
// Check user credentials (This is just a sample, replace with
your actual logic)
if (model.Username != "admin" ||
model.Password != "admin")
{
return Unauthorized();
}
// Generate JWT token
var token = GenerateJwtToken(new UserTokens { Id = 123,
Username = model.Username, UserType = "admin" });
return Ok(new { Token = token });
}
private string GenerateJwtToken(UserTokens
user)
{
var tokenHandler = new JwtSecurityTokenHandler();
var key =
Encoding.ASCII.GetBytes(_jwtSettings.Secret);
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(new Claim[]
{
new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()),
new Claim(ClaimTypes.Name,
user.Username),
new Claim(ClaimTypes.Role,
user.UserType)
}),
Expires =
DateTime.UtcNow.AddMinutes(_jwtSettings.ExpirationMinutes),
SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key),
SecurityAlgorithms.HmacSha256Signature)
};
var token =
tokenHandler.CreateToken(tokenDescriptor);
return
tokenHandler.WriteToken(token);
}
}
public class JwtSettings
{
public string Secret { get; set; }
public int ExpirationMinutes { get; set; }
}
public class UserTokens
{
public int Id { get; set; }
public string Username { get; set; }
public string UserType { get; set; }
}
public class LoginRequest
{
public string Username { get; set; }
public string Password { get; set; }
}
}
using
Microsoft.AspNetCore.Authentication.JwtBearer;
using
Microsoft.Extensions.Configuration;
using
Microsoft.Extensions.DependencyInjection;
using
Microsoft.IdentityModel.Tokens;
using System;
namespace YourNamespace
{
// Class representing JWT settings
public class JwtSettings
{
public string IssuerSigningKey { get; set; }
public string ValidIssuer { get; set; }
public string ValidAudience { get; set; }
// Add more properties as needed
}
// Extension method for IServiceCollection to add JWT token
services
public static class AddJWTTokenServicesExtensions
{
public static void AddJWTTokenServices(this IServiceCollection services,
IConfiguration configuration)
{
// Add Jwt Settings
var jwtSettings = new JwtSettings();
configuration.Bind("JsonWebTokenKeys", jwtSettings);
services.AddSingleton(jwtSettings);
services.AddAuthentication(options => {
options.DefaultAuthenticateScheme
= JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(options => {
options.SaveToken = true;
options.TokenValidationParameters
= new
TokenValidationParameters()
{
ValidateIssuerSigningKey = jwtSettings.ValidateIssuerSigningKey,
IssuerSigningKey = new SymmetricSecurityKey(System.Text.Encoding.UTF8.GetBytes(jwtSettings.IssuerSigningKey)),
ValidateIssuer = jwtSettings.ValidateIssuer,
ValidIssuer = jwtSettings.ValidIssuer,
ValidateAudience = jwtSettings.ValidateAudience,
ValidAudience = jwtSettings.ValidAudience,
RequireExpirationTime = jwtSettings.RequireExpirationTime,
ValidateLifetime = jwtSettings.RequireExpirationTime,
ClockSkew = TimeSpan.FromDays(30),
};
});
}
}
// Main program class
public class Program
{
public static void Main(string[] args)
{
// Configuration setup
var configuration = new ConfigurationBuilder()
.AddJsonFile("appsettings.json") // Add your appsettings.json
file here
.Build();
// Service collection setup
var services = new ServiceCollection();
services.AddJWTTokenServices(configuration);
// Build service provider
var serviceProvider =
services.BuildServiceProvider();
// Example usage: Retrieve JwtSettings
var jwtSettings = serviceProvider.GetRequiredService<JwtSettings>();
Console.WriteLine($"IssuerSigningKey: {jwtSettings.IssuerSigningKey}");
Console.WriteLine($"ValidIssuer: {jwtSettings.ValidIssuer}");
Console.WriteLine($"ValidAudience: {jwtSettings.ValidAudience}");
// You can add more service registrations and configurations here
}
}
}
using Microsoft.AspNetCore.Mvc;
using System.Security.Claims;
using
WebApplication.Repository.Interface;
public class AuthController : ControllerBase
{
private readonly IUserService _userService;
private readonly IHttpContextAccessor
_httpContextAccessor;
public AuthController(IUserService
userService, IHttpContextAccessor httpContextAccessor)
{
_httpContextAccessor
= httpContextAccessor;
}
public IActionResult Index()
{
// Retrieve the NameIdentifier claim from the current user's
claims
var userId =
_httpContextAccessor.HttpContext.User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
if (userId != null)
{
// Fetch user data using the userId
if (userId.Success &&
userId.Data != null && userId.Data.Count > 0)
{
// User data exists, perform further actions
// For example, return Ok with the user data
return Ok(userId.Data);
}
}
// Handle the case when user data is not found or userId is null
// For example, return NotFound or another appropriate status code
return NotFound();
}
}
-------
using System;
namespace UserTokensDemo
{
class Program
{
static void Main(string[] args)
{
// Sample user data
var user = new UserTokens
{
Id = Guid.NewGuid(),
UserName = "exampleUser",
UserType = "Admin"
};
// Sample JWT settings
var jwtSettings = new JwtSettings
{
ValidIssuer
= "exampleIssuer",
ValidAudience = "exampleAudience",
IssuerSigningKey = "exampleKey"
};
// Generate JWT token
var jwtToken =
JwtHelpers.GenTokenkey(user, jwtSettings);
// Output token details
Console.WriteLine("Generated JWT
Token:");
Console.WriteLine(jwtToken.Token);
Console.WriteLine("User ID: " + jwtToken.Id);
Console.WriteLine("User Name: " + jwtToken.UserName);
Console.WriteLine("Expiration Time: "
+ jwtToken.ExpiredTime);
Console.WriteLine("User Type: " + jwtToken.UserType);
}
}
}
using JwtHelpers;
using
Microsoft.IdentityModel.Tokens;
using
System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
namespace Auth
{
public static class JwtHelpers
{
public static IEnumerable<Claim>
GetClaims(this UserTokens userTokens, Guid Id)
{
IEnumerable<Claim> claims = new Claim[]
{
new Claim("Id",
userTokens.Id.ToString()),
new Claim(ClaimTypes.Name,
userTokens.UserName),
new Claim(ClaimTypes.NameIdentifier,
Id.ToString()),
new Claim(ClaimTypes.Expiration,
DateTime.UtcNow.AddDays(30).ToString("MMM
ddd dd yyyy HH:mm:ss tt"))
};
return claims;
}
public static IEnumerable<Claim>
GetClaims(this UserTokens userTokens, out Guid Id)
{
Id =
userTokens.Id;
return GetClaims(userTokens, Id);
}
public static UserTokens
GenTokenkey(UserTokens model, JwtSettings jwtSettings)
{
try
{
var userToken = new UserTokens();
if (model == null) throw new
ArgumentException(nameof(model));
var key =
System.Text.Encoding.ASCII.GetBytes(jwtSettings.IssuerSigningKey);
Guid Id =
model.Id;
DateTime
expireTime = DateTime.UtcNow.AddDays(30);
userToken.Validaty = expireTime.TimeOfDay;
var JWToken = new JwtSecurityToken(
issuer:
jwtSettings.ValidIssuer,
audience: jwtSettings.ValidAudience,
claims:
GetClaims(model, out Id),
notBefore: new DateTimeOffset(DateTime.Now).DateTime,
expires:
new
DateTimeOffset(expireTime).DateTime,
signingCredentials: new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256)
);
userToken.Token = new JwtSecurityTokenHandler().WriteToken(JWToken);
userToken.UserName
= model.UserName;
userToken.Id
= model.Id;
userToken.ExpiredTime = expireTime;
userToken.UserType = model.UserType;
return userToken;
}
catch (Exception)
{
throw;
}
}
}
}
-----
using
Microsoft.IdentityModel.Tokens;
namespace WebApplication.Controllers
{
// Class representing JWT settings
public class JwtSettings
{
public string IssuerSigningKey { get; set; }
public string ValidIssuer { get; set; }
public string ValidAudience { get; set; }
// Add more properties as needed
}
// Extension method for IServiceCollection to add JWT token
services
public static class AddJWTTokenServicesExtensions
{
public static void AddJWTTokenServices(this IServiceCollection services,
IConfiguration configuration)
{
// Add Jwt Settings
var jwtSettings = new JwtSettings();
configuration.Bind("JsonWebTokenKeys", jwtSettings);
services.AddSingleton(jwtSettings);
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(options =>
{
options.SaveToken = true;
options.TokenValidationParameters = new TokenValidationParameters()
{
ValidateIssuerSigningKey = jwtSettings.ValidateIssuerSigningKey,
IssuerSigningKey = new
SymmetricSecurityKey(System.Text.Encoding.UTF8.GetBytes(jwtSettings.IssuerSigningKey)),
ValidateIssuer = jwtSettings.ValidateIssuer,
ValidIssuer = jwtSettings.ValidIssuer,
ValidateAudience = jwtSettings.ValidateAudience,
ValidAudience = jwtSettings.ValidAudience,
RequireExpirationTime = jwtSettings.RequireExpirationTime,
ValidateLifetime = jwtSettings.RequireExpirationTime,
ClockSkew = TimeSpan.FromDays(30),
};
});
}
}
// Main program class
public class Program
{
public static void Main(string[] args)
{
// Configuration setup
var configuration = new ConfigurationBuilder()
.AddJsonFile("appsettings.json") // Add your appsettings.json
file here
.Build();
// Service collection setup
var services = new ServiceCollection();
services.AddJWTTokenServices(configuration);
// Build service provider
var serviceProvider =
services.BuildServiceProvider();
// Example usage: Retrieve JwtSettings
var jwtSettings =
serviceProvider.GetRequiredService<JwtSettings>();
Console.WriteLine($"IssuerSigningKey: {jwtSettings.IssuerSigningKey}");
Console.WriteLine($"ValidIssuer: {jwtSettings.ValidIssuer}");
Console.WriteLine($"ValidAudience: {jwtSettings.ValidAudience}");
// You can add more service registrations and configurations here
}
}
}