Using identity in the application

The to-do list items themselves are still shared between all users, because the to-do entities aren’t tied to a particular user. Now that the [Authorize] attribute ensures that you must be logged in to see the to-do view, you can filter the database query based on who is logged in.

First, inject a UserManager<ApplicationUser> into the TodoController:

Controllers/TodoController.cs

  1. [Authorize]
  2. public class TodoController : Controller
  3. {
  4. private readonly ITodoItemService _todoItemService;
  5. private readonly UserManager<ApplicationUser> _userManager;
  6. public TodoController(ITodoItemService todoItemService,
  7. UserManager<ApplicationUser> userManager)
  8. {
  9. _todoItemService = todoItemService;
  10. _userManager = userManager;
  11. }
  12. // ...
  13. }

You’ll need to add a new using statement at the top:

  1. using Microsoft.AspNetCore.Identity;

The UserManager class is part of ASP.NET Core Identity. You can use it to look up the current user in the Index action:

  1. public async Task<IActionResult> Index()
  2. {
  3. var currentUser = await _userManager.GetUserAsync(User);
  4. if (currentUser == null) return Challenge();
  5. var todoItems = await _todoItemService.GetIncompleteItemsAsync(currentUser);
  6. var model = new TodoViewModel()
  7. {
  8. Items = todoItems
  9. };
  10. return View(model);
  11. }

The new code at the top of the action method uses the UserManager to get the current user from the User property available in the action:

  1. var currentUser = await _userManager.GetUserAsync(User);

If there is a logged-in user, the User property contains a lightweight object with some (but not all) of the user’s information. The UserManager uses this to look up the full user details in the database via the GetUserAsync.

The value of currentUser should never be null, because the [Authorize] attribute is present on the controller. However, it’s a good idea to do a sanity check, just in case. You can use the Challenge() method to force the user to log in again if their information is missing:

  1. if (currentUser == null) return Challenge();

Since you’re now passing an ApplicationUser parameter to GetIncompleteItemsAsync, you’ll need to update the ITodoItemService interface:

Services/ITodoItemService.cs

  1. public interface ITodoItemService
  2. {
  3. Task<IEnumerable<TodoItem>> GetIncompleteItemsAsync(ApplicationUser user);
  4. // ...
  5. }

The next step is to update the database query and show only items owned by the current user.

Update the database

You’ll need to add a new property to the TodoItem entity model so each item can reference the user that owns it:

  1. public string OwnerId { get; set; }

Since you updated the entity model used by the database context, you also need to migrate the database. Create a new migration using dotnet ef in the terminal:

  1. dotnet ef migrations add AddItemOwnerId

This creates a new migration called AddItemOwner which will add a new column to the Items table, mirroring the change you made to the TodoItem entity model.

Note: You’ll need to manually tweak the migration file if you’re using SQLite as your database. See the Create a migration section in the Use a database chapter for more details.

Use dotnet ef again to apply it to the database:

  1. dotnet ef database update

Update the service class

With the database and the database context updated, you can now update the GetIncompleteItemsAsync method in the TodoItemService and add another clause to the Where statement:

Services/TodoItemService.cs

  1. public async Task<IEnumerable<TodoItem>> GetIncompleteItemsAsync(ApplicationUser user)
  2. {
  3. return await _context.Items
  4. .Where(x => x.IsDone == false && x.OwnerId == user.Id)
  5. .ToArrayAsync();
  6. }

If you run the application and register or log in, you’ll see an empty to-do list once again. Unfortunately, any items you try to add disappear into the ether, because you haven’t updated the Add Item operation to save the current user to new items.

Update the Add Item and Mark Done operations

You’ll need to use the UserManager to get the current user in the AddItem and MarkDone action methods, just like you did in Index. The only difference is that these methods will return a 401 Unauthorized response to the frontend code, instead of challenging and redirecting the user to the login page.

Here are both updated methods in the TodoController:

  1. public async Task<IActionResult> AddItem(NewTodoItem newItem)
  2. {
  3. if (!ModelState.IsValid)
  4. {
  5. return BadRequest(ModelState);
  6. }
  7. var currentUser = await _userManager.GetUserAsync(User);
  8. if (currentUser == null) return Unauthorized();
  9. var successful = await _todoItemService.AddItemAsync(newItem, currentUser);
  10. if (!successful)
  11. {
  12. return BadRequest(new { error = "Could not add item." });
  13. }
  14. return Ok();
  15. }
  16. public async Task<IActionResult> MarkDone(Guid id)
  17. {
  18. if (id == Guid.Empty) return BadRequest();
  19. var currentUser = await _userManager.GetUserAsync(User);
  20. if (currentUser == null) return Unauthorized();
  21. var successful = await _todoItemService.MarkDoneAsync(id, currentUser);
  22. if (!successful) return BadRequest();
  23. return Ok();
  24. }

Both service methods must now accept an ApplicationUser parameter. Update the interface definition in ITodoItemService:

  1. Task<bool> AddItemAsync(NewTodoItem newItem, ApplicationUser user);
  2. Task<bool> MarkDoneAsync(Guid id, ApplicationUser user);

And finally, update the service method implementations in the TodoItemService.

For the AddItemAsync method, set the Owner property when you construct a new TodoItem:

  1. public async Task<bool> AddItemAsync(NewTodoItem newItem, ApplicationUser user)
  2. {
  3. var entity = new TodoItem
  4. {
  5. Id = Guid.NewGuid(),
  6. OwnerId = user.Id,
  7. IsDone = false,
  8. Title = newItem.Title,
  9. DueAt = DateTimeOffset.Now.AddDays(3)
  10. };
  11. // ...
  12. }

The Where clause in the MarkDoneAsync method also needs to check for the user’s ID, so a rogue user can’t complete someone else’s items by guessing their IDs:

  1. public async Task<bool> MarkDoneAsync(Guid id, ApplicationUser user)
  2. {
  3. var item = await _context.Items
  4. .Where(x => x.Id == id && x.OwnerId == user.Id)
  5. .SingleOrDefaultAsync();
  6. // ...
  7. }

All done! Try using the application with two different user accounts. The to-do items stay private for each account.