DEV Community

loading...
Cover image for Simple MVC Security in ASP.NET | Blog Security pt. 1: Locking it down

Simple MVC Security in ASP.NET | Blog Security pt. 1: Locking it down

sbrevolution5 profile image Seth A Burleson Updated on ・2 min read

I'm working on a full fledged blog site ( I currently plan to post on dev.to as well, but its a project to show potential employers) and I've just learned how simple it is to implement security. Its almost completely built in to the template, I'll show you how to leverage it to make your site more professional and secure.

What you need to get started

I'm using my Blog project I've spent about a week on, but you don't need anything in depth to try this out. What I'd recommend is a simple scaffolded MVC with ASP.NET Core, Setup your database however you like so it handles user accounts, and we can get started.

As a quick overview, I have a few models, the ones we'll be working with are blogs (collections of posts) and posts.

Step 1: Denying access

You shall not pass

In my blog application currently anyone can edit the database, which is bad. I don't want Anyone who stumbles on the site to be able to create a blog without registering and having permission from myself, and I definitely don't want them deleting my hard work. So lets lock it down!

In the controller for my blogs, right in front of my create get action, I'm going to add one simple line of code [Authorize] and then ensure that the using Microsoft.AspNetCore.Authorization; directive is at the top of my controller. (use ctrl+. to fix this error when the red error ramen comes up).

This Locks out any unregistered user from the page, and redirects them to the login page to put them on track.

Step 2: Allowing a little access

unlocked

Since anyone can register, this is a bit like closing the door but leaving it completely unlocked. If the user is smart enough to register (Most are) they're going to get through the rigorous security. If we beef things up a little we can only allow administrators into the create blog posts. [Authorize(Role = "Administrator")] solves the problem. They will be asked to log in, and then met with an access denied message instead of the ability to create a blog.

I'd rather them not access most of the blog controller, just the index of blogs. Taking a more drastic measure is to instead add [Authorize(Role = "Administrator)] to the entire class. Now access denied will show up for all actions within the Blog controller. On the Index and details actions, we can add [AllowAnonymous] to ensure. This will let Anonymous users back in, so they can browse the blogs and see their details.

This works, but there is a pretty big oversight.

Locked out

The temporary fix is to remove the security so you can work on it.

We'll fix that in my next blog, which will cover Assigning roles and changing whats displayed to the user.

Discussion (0)

Forem Open with the Forem app