text stringlengths 0 13.4k |
|---|
Often you'll want to require the user to log in before they can access |
certain parts of your application. For example, it makes sense to show |
the home page to everyone (whether you're logged in or not), but only |
show your to-do list after you've logged in. |
You can use the [Authorize] attribute in ASP.NET Core to require a |
logged-in user for a particular action, or an entire controller. To require |
authentication for all actions of the TodoController , add the attribute |
above the first line of the controller: |
Controllers/TodoController.cs |
[Authorize] |
public class TodoController : Controller |
{ |
// ... |
} |
Add this using statement at the top of the file: |
using Microsoft.AspNetCore.Authorization; |
Try running the application and accessing /todo without being logged |
in. You'll be redirected to the login page automatically. |
The [Authorize] attribute is actually doing an authentication |
check here, not an authorization check (despite the name of the |
attribute). Later, you'll use the attribute to check both |
authentication and authorization. |
77 |
Require authentication |
78 |
Using identity in the application |
Using identity in the application |
The to-do list items themselves are still shared between all users, |
because the stored 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 |
[Authorize] |
public class TodoController : Controller |
{ |
private readonly ITodoItemService _todoItemService; |
private readonly UserManager<ApplicationUser> _userManager; |
public TodoController(ITodoItemService todoItemService, |
UserManager<ApplicationUser> userManager) |
{ |
_todoItemService = todoItemService; |
_userManager = userManager; |
} |
// ... |
} |
You'll need to add a new using statement at the top: |
using Microsoft.AspNetCore.Identity; |
The UserManager class is part of ASP.NET Core Identity. You can use it |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.