Authentication and Authorization

Authentication is a process of verifying whether someone is who he claims he is. It usually involves a username and a password, but may include any other methods of demonstrating identity, such as a smart card, fingerprints, etc.

Authorization is finding out if the person, once identified, is permitted to manipulate specific resources. This is usually determined by finding out if that person is of a particular role that has access to the resources.

How PRADO Auth Framework Works

PRADO provides an extensible authentication/authorization framework. As described in application lifecycles, TApplication reserves several lifecycles for modules responsible for authentication and authorization. PRADO provides the TAuthManager module for such purposes. Developers can plug in their own auth modules easily. TAuthManager is designed to be used together with TUserManager module, which implements a read-only user database.

When a page request occurs, TAuthManager will try to restore user information from session. If no user information is found, the user is considered as an anonymous or guest user. To facilitate user identity verification, TAuthManager provides two commonly used methods: login() and logout(). A user is logged in (verified) if his username and password entries match a record in the user database managed by TUserManager. A user is logged out if his user information is cleared from session and he needs to re-login if he makes new page requests.

During Authorization application lifecycle, which occurs after Authentication lifecycle, TAuthManager will verify if the current user has access to the requested page according to a set of authorization rules. The authorization is role-based, i.e., a user has access to a page if 1) the page explicitly states that the user has access; 2) or the user is of a particular role that has access to the page. If the user does not have access to the page, TAuthManager will redirect user browser to the login page which is specified by LoginPage property.

Using PRADO Auth Framework

To enable PRADO auth framework, add the TAuthManager module and TUserManager module to application configuration,

<service id="page" class="TPageService">
  <modules>
    <module id="auth" class="System.Security.TAuthManager"
               UserManager="users" LoginPage="UserLogin" />
    <module id="users" class="System.Security.TUserManager"
               PasswordMode="Clear">
      <user name="demo" password="demo" />
      <user name="admin" password="admin" />
    </module>
  </modules>
</service>

In the above, the UserManager property of TAuthManager is set to the users module which is TUserManager. Developers may replace it with a different user management module that is derived from TUserManager.

Authorization rules for pages are specified in page configurations as follows,

<authorization>
    <allow pages="PageID1,PageID2"
              users="User1,User2"
              roles="Role1" />
    <deny pages="PageID1,PageID2"
              users="?"
              verb="post" />
</authorization>

An authorization rule can be either an allow rule or a deny rule. Each rule consists of four optional properties:

  • pages - list of comma-separated page names that this rule applies to. If empty, not set or wildcard '*', this rule will apply to all pages under the current directory and all its subdirectories recursively.
  • users - list of comma-separated user names that this rule applies to. If empty, not set or wildcard '*', this rule will apply to all users including anonymous/guest user. A character ? refers to anonymous/guest user. And a character @ refers to authenticated users (available since v3.1).
  • roles - list of comma-separated user roles that this rule applies to. If empty, not set or wildcard '*', this rule will apply to all user roles.
  • verb - page access method that this rule applies to. It can be either get or post. If empty, not set or wildcard '*', the rule will apply to both methods.

When a page request is being processed, a list of authorization rules may be available. However, only the first effective rule matching the current user will render the authorization result.

  • Rules are ordered bottom-up, i.e., the rules contained in the configuration of current page folder go first. Rules in configurations of parent page folders go after.
  • A rule is effective if the current page is in the listed pages of the rule AND the current user action (get or post) is in the listed actions.
  • A rule matching occurs if the current user name is in the listed user names of an effective rule OR if the user's role is in the listed roles of that rule.
  • If no rule matches, the user is authorized.

In the above example, anonymous users will be denied from posting to PageID1 and PageID2, while User1 and User2 and all users of role Role1 can access the two pages (in both get and post methods).

Available from Prado versions 3.1.1 onwards.

Since version 3.1.1, the pages attribute in the authorization rules can take relative page paths with wildcard '*'. For example, pages="admin.Home" refers to the Home page under the admin directory, and pages="admin.*" would refer to all pages under the admin directory and subdirectories.

Also introduced in version 3.1.1 are IP rules. They are specified by a new attribute ips in authorization rules. The IP rules are used to determine if an authorization rule aplies to an end-user according to his IP address. One can list a few IPs together, separated by comma ','. Wildcard '*' can be used in the rules. For example, ips="192.168.0.2, 192.168.1.*" means the rule applies to users whose IP address is 192.168.0.2 or 192.168.1.*. The latter matches any host in the subnet 192.168.1. If the attribute 'ips' is empty, not set or wildcard '*', the corresponding rule will apply to requests coming from any host address.

Using TUserManager

As aforementioned, TUserManager implements a read-only user database. The user information are specified in either application configuration or an external XML file.

We have seen in the above example that two users are specified in the application configuration. Complete syntax of specifying the user and role information is as follows,

<user name="demo" password="demo" roles="demo,admin" />
<role name="admin" users="demo,demo2" />

where the roles attribute in user element is optional. User roles can be specified in either the user element or in a separate role element.

Using TDbUserManager

TDbUserManager is introduced in v3.1.0. Its main purpose is to simplify the task of managing user accounts that are stored in a database. It requires developers to write a user class that represents the necessary information for a user account. The user class must extend from TDbUser.

To use TDbUserManager, configure it in the application configuration like following:

<module id="db"
     class="System.Data.TDataSourceConfig" ..../>
<module id="users"
     class="System.Security.TDbUserManager"
     UserClass="Path.To.MyUserClass"
     ConnectionID="db" />
<module id="auth"
     class="System.Security.TAuthManager"
     UserManager="users" LoginPage="Path.To.LoginPage" />

In the above, UserClass specifies what class will be used to create user instance. The class must extend from TDbUser. ConnectionID refers to the ID of a TDataSourceConfig module which specifies how to establish database connection to retrieve user information.

The user class has to implement the two abstract methods in TDbUser: validateUser() and createUser(). Since user account information is stored in a database, the user class may make use of its DbConnection property to reach the database.

Available from Prado versions 3.1.1 onwards.

Since 3.1.1, TAuthManager provides support to allow remembering login by setting AllowAutoLogin to true. Accordingly, TDbUser adds two methods to facilitate the implementation of this feature. In particular, two new methods are introduced: createUserFromCookie() and saveUserToCookie(). Developers should implement these two methods if remembering login is needed. Below is a sample implementation:

public function createUserFromCookie($cookie)
{
	if(($data=$cookie->Value)!=='')
	{
		$application=Prado::getApplication();
		if(($data=$application->SecurityManager->validateData($data))!==false)
		{
			$data=unserialize($data);
			if(is_array($data) && count($data)===3)
			{
				list($username,$address,$token)=$data;
				$sql='SELECT passcode FROM user WHERE LOWER(username)=:username';
				$command=$this->DbConnection->createCommand($sql);
				$command->bindValue(':username',strtolower($username));
				if($token===$command->queryScalar() && $token!==false && $address=$application->Request->UserHostAddress)
					return $this->createUser($username);
			}
		}
	}
	return null;
}

public function saveUserToCookie($cookie)
{
	$application=Prado::getApplication();
	$username=strtolower($this->Name);
	$address=$application->Request->UserHostAddress;
	$sql='SELECT passcode FROM user WHERE LOWER(username)=:username';
	$command=$this->DbConnection->createCommand($sql);
	$command->bindValue(':username',strtolower($username));
	$token=$command->queryScalar();
	$data=array($username,$address,$token);
	$data=serialize($data);
	$data=$application->SecurityManager->hashData($data);
	$cookie->setValue($data);
}