This tutorial will guide you through building a simple TODO app with authentication using ASP.NET Core. By the end of this post, you will have a functional API with secure user authentication, allowing you to manage your TODO tasks effectively.
1. Setting Up Your ASP.NET Core Project
Let’s start by creating a new ASP.NET Core Web API project.
- Create a New Project:
- Using Visual Studio: Open Visual Studio, select “Create a new project,” and choose “ASP.NET Core Web API.”
- Using .NET CLI: Run the following command in your terminal:
dotnet new webapi -n TodoApp
Add Required Packages:
- For database and authentication, install the necessary NuGet packages
dotnet add package Microsoft.EntityFrameworkCore
dotnet add package Microsoft.EntityFrameworkCore.SqlServer
dotnet add package Microsoft.EntityFrameworkCore.Tools
dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer
2. Setting Up the Database
- Define Your Model: Create a model to represent the TODO items.
- Models/TodoItem.cs
public class TodoItem
{
public int Id { get; set; }
public string Title { get; set; }
public bool IsComplete { get; set; }
}
Create the Database Context: Set up the Entity Framework Core context to manage database operations.
- Data/ApplicationDbContext.cs
using Microsoft.EntityFrameworkCore;
public class ApplicationDbContext : DbContext
{
public ApplicationDbContext(DbContextOptions options) : base(options) { }
public DbSet<TodoItem> TodoItems { get; set; }
}
Configure the Database Connection: Set up the database connection in Program.cs
.
- Program.cs:
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));
builder.Services.AddControllers();
// Configure JWT authentication
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = builder.Configuration["Jwt:Issuer"],
ValidAudience = builder.Configuration["Jwt:Issuer"],
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration["Jwt:Key"]))
};
});
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();
appsettings.json:
public class LoginModel
{
public string Username { get; set; }
public string Password { get; set; }
}
. Create TODO Endpoints
- Implement TODO API:
- Controllers/TodoController.cs
[ApiController]
[Route("api/[controller]")]
[Authorize]
public class TodoController : ControllerBase
{
private readonly ApplicationDbContext _context;
public TodoController(ApplicationDbContext context)
{
_context = context;
}
[HttpGet]
public async Task<IActionResult> GetTodos()
{
var todos = await _context.TodoItems.ToListAsync();
return Ok(todos);
}
[HttpPost]
public async Task<IActionResult> CreateTodo([FromBody] TodoItem todoItem)
{
_context.TodoItems.Add(todoItem);
await _context.SaveChangesAsync();
return CreatedAtAction(nameof(GetTodos), new { id = todoItem.Id }, todoItem);
}
}
. Testing Your API
Use tools like Postman or cURL to test your API.
- Obtain a JWT Token: Send a POST request to
/api/auth/login
with valid credentials to receive a JWT token. - Access Protected Endpoints: Use the token to access protected endpoints like
/api/todo
. Add the token in the Authorization header as a Bearer token.
6. Additional Considerations
- Error Handling: Implement global error handling middleware to catch and respond to exceptions.
- Validation: Add model validation and handle validation errors gracefully.
- Security: Ensure sensitive information, such as JWT keys, is securely stored and managed. Always use HTTPS for secure communication.
With this updated guide, you should now have a fully functional and secure TODO application using ASP.NET Core 6. This new hosting model simplifies the setup and configuration, making it easier to build and maintain modern web applications. Happy coding!