Loading
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
Ishika TiwariRank #298 · 8.4K reputationPosted Sep 10, 2024, 9:05 AM EDT
https://jasonwatmore.com/post/2021/07/29/net-5-role-based-authorization-tutorial-with-example-api
https://jasonwatmore.com/post/2022/02/18/net-6-role-based-authorization-tutorial-with-example-api
Aman GuptaRank #193 · 12.4K reputationPosted Sep 11, 2024, 4:09 AM EDT
Hi Firoz,
To implement JWT authentication in an ASP.NET Core Web API with CRUD operations, you need to:
- Set up JWT in your ASP.NET Core Web API project.
- Secure your API endpoints with JWT authentication.
- Create CRUD operations with authentication and authorization.
Steps:1. Install Required Packages
In your ASP.NET Core project, install the following NuGet packages:
2. Configure JWT Authentication in
Startup.cs(orProgram.csin .NET 6/7)In
.NET 6/7, configure JWT authentication inProgram.csas follows:public class Startup { public void ConfigureServices(IServiceCollection services) { // Add JWT Authentication services.AddAuthentication(options => { options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }) .AddJwtBearer(options => { options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = true, ValidateAudience = true, ValidateLifetime = true, ValidateIssuerSigningKey = true, ValidIssuer = "yourIssuer", ValidAudience = "yourAudience", IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("your_secret_key")) // Replace with your key }; }); services.AddControllers(); services.AddAuthorization(); } public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { app.UseRouting(); // Enable authentication app.UseAuthentication(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); } }3. Generate JWT Token:
In your controller, create a method to generate the JWT token after a successful login:
[HttpPost("login")] public IActionResult Login([FromBody] UserLoginDto login) { if (login.Username == "testuser" && login.Password == "password") // Example credentials { var token = GenerateJwtToken(); return Ok(new { token }); } return Unauthorized(); } private string GenerateJwtToken() { var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("your_secret_key")); var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256); var tokenDescriptor = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(new[] { new Claim(ClaimTypes.Name, "testuser"), new Claim(ClaimTypes.Role, "User") }), Expires = DateTime.Now.AddMinutes(30), Issuer = "yourIssuer", Audience = "yourAudience", SigningCredentials = credentials }; var tokenHandler = new JwtSecurityTokenHandler(); var token = tokenHandler.CreateToken(tokenDescriptor); return tokenHandler.WriteToken(token); }4. Secure CRUD Endpoints with JWT Authentication
You can now protect your CRUD API endpoints with
[Authorize]to ensure they can only be accessed with a valid JWT token.[Authorize] [ApiController] [Route("api/[controller]")] public class ItemsController : ControllerBase { private static List _items = new List(); // GET: api/items [HttpGet] public IActionResult Get() { return Ok(_items); } // GET: api/items/5 [HttpGet("{id}")] public IActionResult Get(int id) { var item = _items.FirstOrDefault(i => i.Id == id); if (item == null) return NotFound(); return Ok(item); } // POST: api/items [HttpPost] public IActionResult Post([FromBody] Item item) { _items.Add(item); return CreatedAtAction(nameof(Get), new { id = item.Id }, item); } // PUT: api/items/5 [HttpPut("{id}")] public IActionResult Put(int id, [FromBody] Item updatedItem) { var item = _items.FirstOrDefault(i => i.Id == id); if (item == null) return NotFound(); item.Name = updatedItem.Name; item.Description = updatedItem.Description; return NoContent(); } // DELETE: api/items/5 [HttpDelete("{id}")] public IActionResult Delete(int id) { var item = _items.FirstOrDefault(i => i.Id == id); if (item == null) return NotFound(); _items.Remove(item); return NoContent(); } }5. Test the JWT Authentication with CRUD
POSTrequest to/loginto get the JWT token.Authorizationheader of your API requests:This setup ensures that all CRUD operations are protected by JWT authentication. Only users with a valid token can access these endpoints.
Jignesh KumarRank #91 · 22.9K reputationPosted Sep 13, 2024, 12:01 AM EDT
Hello Firoz,
Please refer this article which will help you to undestand step by step,
https://www.c-sharpcorner.com/article/how-to-implement-jwt-authentication-in-web-api-using-net-6-0-asp-net-core/