C
C#16mo ago
uselessxp

❔ Implement JWT to my WebAPI .NET 7.0 project - First time

guys I'd like to implement JWT into my WebAPI project, theory seems to be simple but I'm unable to implement it in my .NET 7.0 project, someone could help me or link me a reliable guide? I'm reading different but each of theme have differences in some points
5 Replies
lvasconcellos
lvasconcellos16mo ago
Hi Do you have something coded already?
uselessxp
uselessxp16mo ago
yeah, I added some code to my Program.cs Below the code I added for now:
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Tokens;
using System.Security.Cryptography.X509Certificates;

// Configure JWT authentication
builder.Services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = false, // I put false cause I don't have a domain, am I wrong?
ValidateAudience = false, // I put false cause I don't have a domain, am I wrong?
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = configuration["Jwt:Issuer"],
ValidAudience = configuration["Jwt:Audience"],
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(configuration["Jwt:Key"]))
};
});

// Enable authentication middleware
app.UseAuthentication();
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Tokens;
using System.Security.Cryptography.X509Certificates;

// Configure JWT authentication
builder.Services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = false, // I put false cause I don't have a domain, am I wrong?
ValidateAudience = false, // I put false cause I don't have a domain, am I wrong?
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = configuration["Jwt:Issuer"],
ValidAudience = configuration["Jwt:Audience"],
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(configuration["Jwt:Key"]))
};
});

// Enable authentication middleware
app.UseAuthentication();
I'm really confused about next steps as every guide show different things to do now I added this in my appsettings.json
"Jwt": {
"Key": "mySecretKey123",
"Issuer": "myIssuer",
"Audience": "myAudience"
},
"Jwt": {
"Key": "mySecretKey123",
"Issuer": "myIssuer",
"Audience": "myAudience"
},
lvasconcellos
lvasconcellos16mo ago
The settings looks okay Now you need the code to generate the token
uselessxp
uselessxp16mo ago
Well, now I created a Post method for login in one of my controllers, I don't know if I have to create a custom class for this, or what, maybe yes, I guess something like Auth controller with this Post method, I wait confirmation. For the moment I pasted this code in one of my existing controllers for try it:
[HttpPost("login")]
public IActionResult Login([FromBody] LoginRequest login)
{
if (login == null)
{
return BadRequest("Invalid client request");
}

// temporary fake login
if (login.Username == "TestUser" && login.Password == "TestPwd")
{
var tokenHandler = new JwtSecurityTokenHandler();
var key = Encoding.ASCII.GetBytes(_config["Jwt:Key"]);
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(new Claim[]
{
new Claim(ClaimTypes.Name, login.Username)
}),
Expires = DateTime.UtcNow.AddMinutes(30),
SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
};
var token = tokenHandler.CreateToken(tokenDescriptor);
var tokenString = tokenHandler.WriteToken(token);

return Ok(new { Token = tokenString });
}
else
{
return Unauthorized();
}
}

private string GenerateJwtToken(string username)
{
return "sample_token";
}

public class LoginRequest
{
public string Username { get; set; }
public string Password { get; set; }
}
[HttpPost("login")]
public IActionResult Login([FromBody] LoginRequest login)
{
if (login == null)
{
return BadRequest("Invalid client request");
}

// temporary fake login
if (login.Username == "TestUser" && login.Password == "TestPwd")
{
var tokenHandler = new JwtSecurityTokenHandler();
var key = Encoding.ASCII.GetBytes(_config["Jwt:Key"]);
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(new Claim[]
{
new Claim(ClaimTypes.Name, login.Username)
}),
Expires = DateTime.UtcNow.AddMinutes(30),
SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
};
var token = tokenHandler.CreateToken(tokenDescriptor);
var tokenString = tokenHandler.WriteToken(token);

return Ok(new { Token = tokenString });
}
else
{
return Unauthorized();
}
}

private string GenerateJwtToken(string username)
{
return "sample_token";
}

public class LoginRequest
{
public string Username { get; set; }
public string Password { get; set; }
}
I found this code on web, and I adapted it by changing the login system, and creating a fake login for now. It seems all clear, only I don't understand the GenerateJwtToken method, if I'm not wrong it's never called. Forgot to say that's before the GenerateJwpToken method snippet, is written that I have to implement JWT token logic without further explainations.
Accord
Accord16mo ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.