DEV Community

Cover image for Simple MVC Security in ASP.NET | Blog Security pt. 2: Permission and Display
Seth A Burleson
Seth A Burleson

Posted on • Edited on

1 1

Simple MVC Security in ASP.NET | Blog Security pt. 2: Permission and Display

Part 2 in a series on security for an MVC blog site. See Part 1 here

Step 3: Let yourself back in.

let me in
So your application is now so secure that even you can't get in.
Lets make a dataservice with a method that will call 2 other functions:

public class DataService
    {
        /* Any injected services go here!!
           Don't forget the constructor!! */

        public async Task ManageDataAsync()
        {
            //Task 1: Seed roles (create and enter into Authorization system
            await SeedRolesAsync();
            // Task 2 seed a few users into AspNetUsers
            await SeedUsersAsync();
        }
Enter fullscreen mode Exit fullscreen mode

I used a dataservice to seed roles when there are none. (this is the first method in that service)

public async Task SeedRolesAsync()
        {
            //Are there roles in the system? 
            if (_context.Roles.Any())
            {
                return;
            }
            //Spin through enum and do stuff
            foreach (var role in Enum.GetNames(typeof(BlogRole)))
            {
                //create Role in system for each role
                await _roleManager.CreateAsync(new IdentityRole(role));
            }
        }
Enter fullscreen mode Exit fullscreen mode

BlogRole is an enum with Administrator and Moderator are the options, so now we have 2 roles that exist in our database.

Lets then seed an adminUser

private async Task SeedUsersAsync()
        {
            if (_context.Users.Any())
            {
                return;
            }
            var adminUser = new BlogUser()
            {
                Email = "AdminEmail@AdminMailAddress.com",
                UserName = "AdminEmail@AdminMailAddress.com",
                FirstName = "Admin",
                LastName = "Istrator"
                //OTHER DATA FOR USER CLASS
            };
            await _userManager.CreateAsync(adminUser, _configuration["AdminPassword"]);
            await _userManager.AddToRoleAsync(adminUser, BlogRole.Administrator.ToString());


        }
Enter fullscreen mode Exit fullscreen mode

Where my Admin Password is in my appSettings.json, to keep it private from github. You may also use IdentityUser where I used BlogUser to initialize a user.

The ManageDataAsync is called in your program.cs file
Where the contents of main look like:

        public static async Task Main(string[] args)
        {
            //CreateHostBuilder(args).Build().Run();
            var host = CreateHostBuilder(args).Build();
            var dataService = host.Services.CreateScope().ServiceProvider.GetRequiredService<DataService>();
            await dataService.ManageDataAsync();

            host.Run();
        }
Enter fullscreen mode Exit fullscreen mode

Step 4: Hiding things from the unregistered masses

invisible

If a new unregistered user comes to my site, I don't want them to click on something that takes them to a page where access is denied. In my view, I'll add a simple if statement

@if (User.IsInRole("Administrator"))
                    {

                        <li class="nav-item">
                            <a class="nav-link" asp-area="" asp-controller="Blogs" asp-action="Index">Blogs</a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" asp-area="" asp-controller="Posts" asp-action="Index">Posts</a>
                        </li>
                    }
Enter fullscreen mode Exit fullscreen mode

The inner content will be whatever you want to display to users in the administrator role. Adding an || to your if can allow for multiple roles, and else statements can be used to display different data for different roles.

An interesting idea is to give the user a gray button that redirects to a purchase page if they aren't a premium user, showing them what they're missing and giving them an option to upgrade.

AWS GenAI LIVE image

Real challenges. Real solutions. Real talk.

From technical discussions to philosophical debates, AWS and AWS Partners examine the impact and evolution of gen AI.

Learn more

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more