Skip to content
  • iImagine
  • Register
  • Log In

Web Development School

Learning made easy.

  • Books
    • Beginning Web Development with ASP.Net Core & Client-Side Technologies
      • TOC
      • Part 1
        • Chapter 1: Static HTML – Designing the landing page
      • Part 2
        • Chapter 2: ASP.Net Core – Let’s talk Dynamic
        • Chapter 3: Introduction to ASP.Net Core MVC
          [ASP.Net Core v9]
      • Part 4
        • Chapter 7: Using Server Side & Client Side technologies together
          [ASP.Net Core v7 & Angular 15]
  • Environment Setup
    • Installing Angular
    • Installing Visual Studio 2022
    • Installing SQL Server 2022 Express
    • Installing Postman
    • Installing Git for Windows
  • Blog
  • iImagine WebSolutions
  • Events
  • Learning Videos
  • Toggle search form

Locking Down the Home Page

In this module we are going to tidy up some loose ends pertaining to Security and Administration on the Home Index page. As noted at the end of the last module any user can currently create, edit, or delete Vehicles from the Home page. In this module we are going to lock down these features so that only Administrators and Staff can manage vehicles.

Table Of Contents
  1. Locking Down the Vehicles controller
  2. Locking Down the Home Index view

Locking Down the Vehicles controller

Modify the VehiclesController class in the Controllers folder of the FredsCars project with the changes shown below.

FredsCars\Controllers\VehiclesController.cs

using FredsCars.Models;
using FredsCars.Models.Repositories;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;

namespace FredsCars.Controllers
{
    [Authorize(Roles = "Administrator,Staff")]
    public class VehiclesController : Controller
    {
        private IVehicleRepository _vehicleRepo;
        private IVehicleTypeRepository _vehicleTypeRepo;
        private ILogger _logger;

        public VehiclesController(IVehicleRepository vRepo,
            IVehicleTypeRepository vtRepo,
            ILogger<VehiclesController> logger)
        {
            _vehicleRepo = vRepo;
            _vehicleTypeRepo = vtRepo;
            _logger = logger;
        }

        [AllowAnonymous]
        public async Task<ViewResult> Details(int id)
        {
            Vehicle? vehicle = await _vehicleRepo.Vehicles
                .AsNoTracking()
                .Include(v => v.VehicleType)
                .FirstOrDefaultAsync(v => v.Id == id);

            if (vehicle == null)
            {
                ViewBag.NoVehicleMessage =
                "Sorry, no vehicle with that id could be found.";
            }
            
            return View(vehicle);
        }
... existing code ...

In the controller code above, we have decorated the Vehicles controller with the Authorize attribute specifying only users with a role of Administrator or Staff can access any of the action methods in the controller.

[Authorize(Roles = "Administrator,Staff")]
public class VehiclesController : Controller

As a result, any user who is not logged in with one of those roles who tries to create, edit, or delete a vehicle will be redirected to the Login page.

By decorating the Vehicles controller with the Authorize attribute we prevent users who are not logged in or who do not have the Administrator or Staff role from accessing any action method in the controller. This includes the Details action method which we want any user to be able to access. To allow access to users who are not logged in we apply the AllowAnonymous attribute to the Details action method.

[AllowAnonymous]
public async Task<ViewResult> Details(int id)

Locking Down the Home Index view

In the previous section we locked down and secured the restricted features from the server side. In this section we are going to take care of the front end and remove the Create New link and Edit and Delete buttons for Vehicle results on the Home Index page for users who are not authenticated or who do not have the Administrator or Staff role.

Modify the _VehicleTableRowResult.cshtml file in the Views\Home folder of the FredsCars project.

FredsCars\Views\Home\_VehicleTableRowResult.cshtml

@model Vehicle

<tr>
    <td>
        <a asp-controller="Vehicles" 
           asp-action="Details"
           asp-route-id="@Model.Id">
            <img src="@Model.ImagePath"
                 class="result-image" />Details</a>
        @if (User.IsInRole("Administrator") || User.IsInRole("Staff"))
        {
            <a asp-controller="Vehicles" 
                asp-action="Edit"
                asp-route-id="@Model.Id">
                <i class="bi bi-pencil text-success"></i></a>
            <a asp-controller="Vehicles"
                asp-action="Delete"
                asp-route-id="@Model.Id">
                <i class="bi bi-trash text-danger"></i></a>
        }
    </td>
    <td>
        @Html.DisplayFor(modelItem => Model.Status)
    </td>
    <td>
        @Html.DisplayFor(modelItem => Model.Year)
    </td>
... existing code ...

In the partial view above which displays Vehicle results, the razor code now has a C# if/block that checks to make sure the current user has either the Administrator or Staff role and only then displays the Edit and Delete icon buttons.

Now modify the Index view of the Home Controller.

FredsCars\Views\Home\Index.cshtml

@model VehiclesListViewModel

@{
    ViewData["Title"] = "Welcome";
}

<div class="container-fluid my-4 text-center">
    <h1>Welcome to Fred's Cars!</h1>
    Where you'll always find the right car, truck, or jeep.<br />
    Thank you for visiting our site!

    <div class="container-fluid mx-0 row"
        style="margin-top: 20px; border: 0px solid black">
        <!-- Categories -->
        <div class="col-4 col-md-3 col-lg-2"
             style="border-right: 2px solid black">
             <div class="d-grid gap-2 button-grid">
                @if (User.IsInRole("Administrator") || User.IsInRole("Staff"))
                {
                    <p class="container-fluid text-start">
                        <a asp-controller="Vehicles" asp-action="Create">Create New</a>
                    </p>
                }
                <vc:categories-component />
            </div>
        </div>
... existing code ...

In the above razor code we have applied the same if/block condition around the Create New link as we did for the Edit and Delete icon buttons.


In the screenshot below you can see that I am logged in as an Administrator so I have Edit and Delete buttons as well as the Create New link.

In the screenshot below I am logged out so the Delete and Edit icon buttons as well as the Create New link are not rendered.

What’s Next

In this module we just did a little housecleaning for security and administration. In the next module we just have one more thing left to do. And, that is to add a reset password feature.

< Prev
Next >

Leave a ReplyCancel reply

Chapter 1: Static HTML – Designing the landing page.

  • Static HTML – Designing the landing page.
  • Let’s get started!
  • Mock your site with HTML
  • Make CSS easy with Bootstrap
  • Mock your content
  • Introducing JavaScript
  • JavaScript Code Improvements
  • Results Data
  • Images and the HTML Image Element.
  • Revisiting Reusability for CSS and JavaScript
  • Reuse for HTML: PART 1
  • Reuse for HTML: PART 2
  • Details Page – Using a Bootstrap Component
  • Creating Links
  • Chapter One Conclusion

Chapter 2: ASP.Net Core – Let’s talk Dynamic

  • Introduction to ASP.Net Core
  • What is .Net?
  • What is ASP.Net
  • Introduction to Entity Framework Core

Chapter 3: ASP.Net MVC Core – Models, Views, and Controllers [ASP.Net Core v9]

  • Introduction to ASP.Net Core MVC
  • Create the project: ASP.Net Core MVC
  • Explore the ASP.Net Core Empty Web Project Template
  • Configure the Application for MVC
  • Create a Controller: Home Controller
  • Create a View: Index View for the Home Controller
  • Install Bootstrap using Libman
  • Create the Layout template
  • Create the Model
  • Install EF Core & Create the Database
  • Seed the Database: Loading test data
  • DI (Dependency Injection): Display a List of Vehicles
  • Repository Pattern: The Vehicles Repo
  • Unit Test 1: Home Controller Can Use Vehicle Repository
  • Unit Test 2: Vehicle Repository Can Return List
  • Add the ImagePath Migration and Thumbnail images to results
  • Pagination: Create a Custom Tag Helper
  • Sorting
  • Category Filter
  • Partial View: Break out the vehicle results
  • View Component: Create dynamic category buttons
  • Create the Details page
  • Create the Create Page
  • Create the Update Page
  • Create the Delete Page
  • Validation
  • Logging & Configuration
  • Storing Secrets
  • Error Handling
  • Security & Administration
  • Locking Down the Home Page
  • Add the Reset Password feature
  • Deployment

Chapter 7: Using Server Side & Client Side technologies together. [ASP.Net Core v7 & Angular v15]

  • Intro to Full Stack Development
  • Fred’s Cars – Full Stack Development
  • Prepare the environment
  • Create the Visual Studio Solution
  • Add the ASP.Net Core Web API project
  • Add the Angular Project
  • Wire it up!
  • WeatherForecast: Understanding the basics
  • Vehicles API Controller: Mock Data
  • Vehicles Angular Component: Consuming Data
  • Routing and Navigation
  • Using a Component Library: Angular Material
  • Our first Angular Material Component: MatToolbar
  • Configuring for Saas: CSS with superpowers
  • Create the Header & Footer components
  • Displaying Results with MatTable
  • Loading: Using a Progress Spinner
  • MatTable: Client-Side Paging and Sorting
  • MatSidenav: Create a Search Sidebar
  • MatCheckbox: Category Search UI
  • Adding an image to the welcome page
  • Create the database with Entity Framework Core migrations
  • MatPaginator & PageEvent: Custom Server-Side Paging
  • Unit Testing: Custom Server-Side Paging
  • Repository Pattern: VehicleRepository
  • Unit Test: Paging in the Vehicles controller
  • Server-Side Sorting
  • Unit Tests: Sorting
  • Filter (Quick Search)
  • Unit Tests: Filter feature
  • Advanced Search: Categories
  • Unit Tests: Search by category
  • Progress Spinner: Final Fix

TOC

  • What were WebForms?
  • Enter MVC
    • Understanding MVC
    • Advantages of MVC
  • ASP.Net Core MVC – A total rewrite
  • ASP.Net Core 2 MVC – Here come Razor Pages
    • Understanding Razor Pages
  • ASP.Net Core 3 – Dropping the MVC reference
    • Understanding Blazor
  • Dropping the MVC reference
  • Hello .Net 5!
  • What’s Next? – Here comes .Net 6.

Recent Posts

  • Angular Commands Cheat Sheet
  • Installing Git for Windows
  • Installing Postman
  • Installing SQL Server 2022 Express
  • Installing Visual Studio 2022

Recent Comments

No comments to show.

Archives

  • November 2023
  • October 2023
  • June 2023
  • October 2021

Categories

  • Angular
  • ASP.Net
  • Environment Setup
  • See All
  • SQL Server
  • Visual Studio
  • Web API & Rest Services

WordPress Theme Editor

Copyright © 2026 Web Development School.

Powered by PressBook Blog WordPress theme