Learn how to use the Policy system in ASP.NET Core to create authorization rules that can be evaluated in your controllers and action methods to enforce permissions for users.
- [Instructor] We've talked a lot about authentication but authorization is important too. This API uses a simple role-based system for authorization. Your API may use roles, claims, or maybe something else. Regardless of how authorization is modeled in your API, you'll need to perform authorization checks in your controllers. The policy system in ASP.NET Core makes it easy to create and reuse authorization policies. Policies are groups of authorization requirements like role checks or claim checks, that are defined in the start up class.
Let's define a policy for users who can see all other users in the system instead of just seeing themselves. I'll go ahead and open up the start up class and we'll do this in configure services which is getting pretty big now. I'll just throw it in at the end here. I'll do services.AddAuthorization. Add some options and I'll say options.AddPolicy. We'll call this policy the viewAllUsersPolicy.
And to define the policy we'll say policy dot RequireAuthenticatedUser which is kind of a given. And then we'll also say RequireRole, and the role needs to be Admin. Then let's go over to the users controller and here in GetVisibleUsers, we have this TODO for an authorization check. Let's go ahead and replace that now. Let's do var users = new PagedResults of user.
Just an empty list, then we'll say if User.Identity .IsAuthenticated. If we're authenticated we want to return either all the users in the system, if they pass that authorization policy or just myself. I can always see myself if I'm logged in. I'll do canSeeEveryone = await. And I need to inject an I authorization service here. So before I write anymore code I'll go do that at the top. I'm gonna do IAuthorizationService.
Just call this the _authzService. IAuthorizationService. Okay now we can keep going over here, we can say _authzService dot AuthorizeAsync for this current user and the authorization policy we named before that was the viewAllUsersPolicy.
Now we can check if that's exceeded. if canSeeEveryone.Succeeded then we know we have the Admin role here. If not, we just want to return one user myself, why don't we do that real quick. I'll just var myself = await _userService.GetUserAsync for this current user then we'll do users.items equals new just an array, a single item array rather of myself.
Users.TotalSize = 1 then we'll remove this line here, and we'll just be returning this as a collection of one item. Actually I didn't mean to remove that, let's cut it instead of deleting it and we're gonna put it here for the Admin section. For an Admin to see everyone we'll just do that users query here. Okay let's test out a couple of branches of this in Postman. I'll go ahead and create a new user for myself by posting to the users route.
And then I'll generate a token for my account by logging in here hitting the token route with my Nate@ account. That'll generate me an access token, copy that and then I'll go ahead and try to hit the users route again and I'll pass my bearer token. I'll say Authorization, Bearer and paste my access token in. Now this should give me just myself back, size of one. Now we'll try that again for the Admin.
Let's do admin@ landon.local and Supersecret123. Now this is an Admin token, and we'll send that along instead. Say Bearer, that Admin token we should get both users back. The ASP.NET core policy system can be used to express authorization requirements from these simple role checks all the way to complex authorization needs.
This wraps up our look at adding application security to the API in the form of authentication and authorization. As an additional challenge try adding authorization checks to the rest of the application. You can also add more links and forms so the API self documents the slash tokens and slash users routes. I'll include my solution to this challenge in the final set of exercise files.
- What is RESTful design?
- Building a new API with ASP.NET Core
- Using HTTP methods
- Returning JSON
- Creating RESTful routing with templates
- Securing RESTful APIs with HTTPS
- Representing resources
- Representing links
- Representing collections
- Sorting and searching collections
- Building forms
- Adding caching to an ASP.NET Core API
- Configuring user authentication and authorization