Autenticación y Autorizacion

Autenticación es un proceso de verificacion de alguna persona cuando esta dice ser quien es. Usualmente se utiliza para esto un nombre de usuario y un contraseña, pero podría incluir otros métodos para demostrar su identidad, tales como tarjetas inteligentes, huellas digitales, etc.

Autorización es el proceso de saber si la persona, una vez indetificada, esta permitida a manipular recursos especificos. Esto es comunmente determinado conociendo si la persona tiene un rol especifico que le da acceso a los recursos solicitados.

Funcionamiento de la Autenticación y Autorizacion en PRADO

PRADO proporciona una capa extensible de autenticacion/autirizacion. Como esta descrito en el Ciclo de vida de una aplicacion PRADO, TApplication reserva diversos modulos del ciclo de vida, responsables de la autenticacion y la autorizacion. PRADO proporciona el modulo TAuthManager para este propósito. Los desarrolladores pueden incorporar sus propios modulos de autenticacion/autorizacion (auth) facilmente. TAuthManager esta diseñado para ser usado en conjunto con el modulo TUserManager, el cual implementa una base de datos de usuarios de solo lectura (read-only).

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 Autenticación 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:

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.

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).

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:

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.

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); }