In this guide, I am going to show you how to create a simple ASP.NET Web Application with authentication. I will create a special page that will be available only to authenticated users.
My artifacts are:
- Visual Studio 2022
- Project Template – ASP.NET Core Web App
- .NET 6.0 (Long-term support)
Step 1 – Create a New Application
Run Visual Studio 2022 and create a new project ‘ASP.NET Core Web App’.
Choose .NET 6 Framework and ‘Individual Accounts’(user can register and create login credentials) authentication type. Leave ‘Configure for HTTPS’ checked.
Step 2 – Prepare Database
1. Open the appSettings.json file and set a more user-friendly name for database. In our case it is ‘YarkulTestAuthWebApp’.
2. Go to the menu View -> Other Windows -> Package Manager Console and run the command ‘update-database’. This command starts the database migration. As a result, a set of standard tables for authorization should be created.
If you see the error message ‘update-database : The term ‘update-database’ is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.’ then try to restart Visual Studio and build your project.
And now after migration is done in the SQL Server Object Explorer you can see a list of tables for authentication purposes.
You may also be interested to read my articles related to the Database:
- How to Get Connection String from Appsettings.json? .net Core Console Application
- Console .Net 6.0 App with Entity Framework Core 6.0.6
- How to Install Microsoft SQL Server 2019 Express Edition?
Step 3 – Add a New Page For Authorized Users Only
Let’s add some information to this page:
Step 4 – Add Authorize attribute for ‘ForAuthUsersOnlyModel’ Page
To secure our page I will add an Authorize attribute. It limits access to that component to authenticated users.
Step 5 – Test Application – Navigate to Secure page without Authorization
After we run our application and try to navigate to our page we should be redirected to the login page https://localhost:7170/Identity/Account/Login?ReturnUrl=%2FForAuthUsersOnly
Step 6 – Test Application – Register User and Navigate to Sercure page
To register a user, we need to verify the email. Since we created the application from the box, the Microsoft developers were very kind and added for such demo applications the possibility to confirm the email without sending the email itself(thank you guys!).
After confirmation you should log in:
And if you enter the path to our secret page, you will see it:
As you can see it was not hard to create this application. Microsoft did most of the work for you. And now you know how to create a simple application with authorization.