In the previous exercise we discussed how the application determines where to send the HTTP request. However, what happens if the user makes a request for a page they are not authorized to view? Well, we also have an ASP.NET built-in component to make handling this situation easier.
When we create ASP.NET applications, Visual Studio provides us with an option to indicate whether or not we’d like to include authentication, which verifies one’s identity. Once a user has been authenticated, we can use authorization to specify the areas which they may access. Setting the application up with the option for authentication allows us to easily implement authorization where necessary.
One way in which authorization can be implemented is through the use of data annotations. Data annotations are attributes that can be added to our .NET classes and methods to enforce specific settings or policies. In our case, we would add the
[Authorize] data annotation to the page model for which we want users to be authorized.
UseAuthorization() component checks the user’s request with their authorization status. Remember when we talked about the importance of components being in the correct order? After
UseRouting() has established the destination for the request,
UseAuthorization() checks to see if the destination requires authorization and whether or not the user is authorized. If the authorization check passes, this component will pass the request to the next component in the pipeline. Otherwise, it will short-circuit the pipeline and either present the user with a login page or an error.
View ASP.NET authorization documentation to see examples and more details about implementing authorization in ASP.NET.
CC’s Bakery site has been upgraded so users can view their previous orders. In the code editor, view the
[Authorize] data annotation on the
My Orders page model. In the browser, navigate to “My Orders” from the menu and watch the authorization component in action. You should see a login screen.