Best way to prevent unauthenticated access to Sharp Pages Content Pages

I’ve added {{ redirectIfNotAuthenticated }} to the top of many of my content pages to prevent unauthenticated access.

Is there a way this can be applied more generically to many pages?

I added the following block at the top of the _layout.html page. This works for my use case.

{{#if !matchesPathInfo('/login') }}
    {{ redirectIfNotAuthenticated('/login') }}
{{/if}}

Yeah adding it to the layout is a good option if you have very few pages that don’t require authentication, otherwise I’d generally have a _requires-auth-partial.html that contains the redirect and other user account info and include that at the top of pages that require auth:

{{ 'requires-auth' | partial }}

Note: you should be able to specify just redirectIfNotAuthenticated instead of redirectIfNotAuthenticated('/login') as it fallsback to use the HtmlRedirect in your AuthFeature which defaults to ~/login.

1 Like