Skip to main content
Logo

WebAPI security

The WebAPI also makes it easier to deal with website security; handling both Users and Security Groups. On a typical intranet, extranet or login enabled website, there will nearly always be a need to determine authentication and authorisation to a given resource or areas or controls displayed on a specific page.

User

The first thing you may want to do with a user object is to ensure that the current user is actually logged in.  If the current user hasn't previously logged in (i.e. is a Public User), then we will redirect them to the login page for the website.

@using Contensis.Framework.Web
 
@{
    if (!CurrentUser.IsAuthenticated) {
        Response.Redirect("~/Account/Login.aspx");
    }
}

To extend this concept further, you may want to output a personalised message to the current user.  Again, we'll perform a check to ensure that the user is logged in first.

@using Contensis.Framework.Web
 
<div id="personalised-area">
    @if (CurrentUser.IsAuthenticated)
    {
        <span>Hello @CurrentUser.DisplayName</span>
    }
    else
    {
        <span>Please log in </span>
    }
</div>

There may be times when you want to search for specific users within the system.  In these instances, you need to use AppContext to widen your context to the whole website.  The following example uses LINQ to retrieve all users whose Lastname contains the word "bloggs".

@using Contensis.Framework.Web
 
@{
    IEnumerable<User> userSearch = AppContext.Current.Security.Users.Where(u => u.Lastname.Contains("bloggs"));
     
    <ul>
    @foreach(User myUser in userSearch)
    {
        <li>@myUser.DisplayName</li>  
    }
    </ul>
}

Groups

You may also wish to output a list of users that are members of a particular security group within Contensis.  The following example shows how to output all the names of all the Users contained in the Public Relations Security Group.

 

@using Contensis.Framework.Web
 
@{
    UserCollection users = AppContext.Current.Security.Groups.FindBy("System Administrators").Members;
     
    if (users.Count > 0) {
        <ul class="sys_users">
            @foreach (User myUser in users)
            {
                <li>@myUser.DisplayName</li>
            }
        </ul>
    }
}

Membership

You may also want to display something on a Razor view dependant on whether the current user is a member of a specific Security Group. In this example, a number of hyperlinks are placed on the page, but the Edit and Delete links can only be seen by Users who are members of the UK Sales Security Group.

@using Contensis.Framework.Web
 
<ul class="sys_actions">
    <li><a href="/view/">View</a></li>
    <li><a href="/watch/">Add watch</a></li>
    @if (CurrentUser.IsMemberOf("UK Sales")) {
        <li><a href="/edit/">Edit</a></li>
        <li><a href="/delete/">Delete</a></li>
    }
</ul>