skip to Main Content

I’m creating a Web App BackEnd in c#/ASP.NET.
I need to make the pages accessible only after the log in / authentication based on the allowed users in a database (.db sqlite).
Maybe saving cookies in the browser and checking those…
I need to do it from the Back-End.

Also, I need to know how to not show the .html pages directly but through controllers (and not making them accessible with the complete url ex.:"domain/page.html"), maybe i could manage the authentication through a PagesController.cs

Let me know your suggestions and ideas. Thanks 🙂

EDIT:
Now my only question is: how can I create a session which is needed to show every page except the login.html?

2

Answers


  1. Example 1 – Assigning Default User Role

    I will assume that you are using Entity Framework to manage your Authentication Users and Roles.

    I worked on a similar thing on my leagues platform. I wanted to have an Area that could only be accessible to administrators.

    Area List

    Each area had its own controllers and views (http pages).

    Admin Subfolders

    This is a controller example:

    Controller Example

    I set a class decoration with the rule: Only Users with Role "SuperUtilizador" aka SuperUser are allowed to access and call the Views and the API Methods.

    This removes the possibility of an user without session or a normal user to access my controller.
    When an user registers in your application, you can automatically assign it to a role "User" and then add this rule to your controllers, this will prevent non logged people to access your content.

    There are more efficient ways to do this. This is an easy one.

    Example 2: Custom Auth Policies

    On your startup.cs, you can add custom policies, and later add those to your controllers decorations, same logic as example 1. This is a custom policies for my Pages, only authenticated users (no matter what role) can access.

    Add this inside the ConfigureServices function.

    services.AddAuthorization(options =>
    {
        options.AddPolicy("OnlyLoggedInUsers", policy =>
        {
            policy.RequireAuthenticatedUser();
        });
    });
    

    Then, on your controllers:

        [Area("LeagueWorkBench")]
        [Authorize(Policy = "OnlyLoggedInUsers")]
        public class GameController : Controller
        {
    

    Hope this helps.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search