Skip to content

Protecting pages with logins

Simon Yohannes edited this page Jan 25, 2020 · 11 revisions

let's say you have a section of your website you want to protect behind a login, and the path for that section is /news/. first create a controller that inherits from puck.core.Controllers.BaseController which will have an action named "Protected":

public class ProtectedController : BaseController
    {
        [Authorize(Roles = "premium")]
        public ActionResult Protected() {
            return base.Puck();
        }
    }

the name of the controller or the action aren't important and can change, you just need a controller that inherits from puck.core.Controllers.BaseController with an Action that has an [Authorize] attribute that returns base.Puck().

next you need to add a new route to Startup.cs (add it below the "puckarea" route):

endpoints.MapControllerRoute(
  name: "news",
  pattern: "news/{**path}"
  ,defaults: new { controller = "Protected", action = "Protected"}
);

the route will match anything in your news section and route it to your new controller where authorization takes place and if successful, base.Puck() will be executed to retrieve the current page. if unsuccessful, they'll obviously be redirected to the login page.

working with a custom Identity User

check out this page on setting up your own Identity User.

changing the login page paths

you can customise the default LoginPath,LogoutPath and AccessDeniedPath by modifying your Startup.cs file. modify the call to services.AddPuckServices:

if (Configuration.GetValue<bool?>("UseSQLServer") ?? false)
                services.AddPuckServices<User, Role, DbContextSQLServer>(Env, Configuration, ServiceLifetime.Scoped,configureCookieAuthenticationOptions:x=> { x.LoginPath = "/accounts/login";});
            else if (Configuration.GetValue<bool?>("UsePostgreSQL") ?? false)
                services.AddPuckServices<User, Role, DbContextPostgreSQL>(Env, Configuration, ServiceLifetime.Scoped, configureCookieAuthenticationOptions: x => { x.LoginPath = "/accounts/login"; });
            else if (Configuration.GetValue<bool?>("UseMySQL") ?? false)
                services.AddPuckServices<User, Role, DbContextMySQL>(Env, Configuration, ServiceLifetime.Scoped, configureCookieAuthenticationOptions: x => { x.LoginPath = "/accounts/login"; });
            else if (Configuration.GetValue<bool?>("UseSQLite") ?? false)
                services.AddPuckServices<User, Role, DbContextSQLite>(Env, Configuration, ServiceLifetime.Scoped, configureCookieAuthenticationOptions: x => { x.LoginPath = "/accounts/login"; });

in the above example we're specifying the LoginPath for all database types but you only need to specify it for the database you're using.