i have a webApi project that the client side in angular
i need to do token in my server side and i need a help how to do that
thanks
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
Cynthia SathuragiriPosted Dec 11, 2025, 12:02 PM
Install-Package Microsoft.AspNetCore.Authentication.JwtBearer
Add JWT Settings in appsettings.json
"Jwt": {
"Key": "ThisIsMySecretKey12345",
"Issuer": "yourapp",
"Audience": "yourapp-users",
"ExpiresInMinutes": 60
}
Configure JWT in Program.cs
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddAuthentication("Bearer")
.AddJwtBearer("Bearer", options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = builder.Configuration["Jwt:Issuer"],
ValidAudience = builder.Configuration["Jwt:Audience"],
IssuerSigningKey = new SymmetricSecurityKey(
Encoding.UTF8.GetBytes(builder.Configuration["Jwt:Key"]))
};
});
builder.Services.AddAuthorization();
var app = builder.Build();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();
Create a Method to Generate JWT Token
private string GenerateJwtToken(string username)
{
var securityKey = new SymmetricSecurityKey(
Encoding.UTF8.GetBytes(_config["Jwt:Key"]));
var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);
var claims = new[]
{
new Claim(ClaimTypes.Name, username)
};
var token = new JwtSecurityToken(
issuer: _config["Jwt:Issuer"],
audience: _config["Jwt:Audience"],
claims: claims,
expires: DateTime.Now.AddMinutes(Convert.ToDouble(_config["Jwt:ExpiresInMinutes"])),
signingCredentials: credentials
);
return new JwtSecurityTokenHandler().WriteToken(token);
}
Create Login API That Returns Token
[HttpPost("login")]
public IActionResult Login([FromBody] LoginModel model)
{
if (model.Username == "admin" && model.Password == "123")
{
var token = GenerateJwtToken(model.Username);
return Ok(new { token });
}
return Unauthorized();
}
Secure Your API Endpoints
[Authorize]
[HttpGet("get-data")]
public IActionResult GetData()
{
return Ok("This is protected data");
}
Angular Side – Store & Send Token
Save token after login:
localStorage.setItem('token', response.token);
Add token to every API request using interceptor:
const token = localStorage.getItem('token');
req = req.clone({
setHeaders: {
Authorization:
Bearer ${token}}
});
Sanwar RanwaPosted Jan 16, 2020, 10:36 AM
Rajeesh MenothPosted Jan 16, 2020, 10:30 AM