Authenticated User - Layout Snippet

Authenticated User - Layout Snippet

Snippets are Layout Elements that you can drag n drop into the layout canvas. You add them to the Views folder of your theme and they have to end with Snippet.cshtml. Layout Snippets it's one of my favourites features of Orchard.  

In this Blog Post, I will show you how to make a Page only accessible for authenticated users. There are plenty of ways to do it but I will use the Layout Snippet way. 

If a user is not Logged In the WorkContext.CurrentUser will be null. 

We will a create a cshtml file in the Views folder of our theme, with the name AuthenticatedUserSnippet. 

@{
    if (WorkContext.CurrentUser == null)
    {
        Response.Redirect("~/Users/Account/LogOn");
    }
}

Now we can now drag the Authenticated User snippet wherever we want and If the user is not Logged In will be redirected to login page. 

You can download the above file from GitHubyou can add it to the Views folder of your theme and you are ready.