Databases Reference
In-Depth Information
default: throw new ArgumentException(“state”);
}
}
The
Authorize
method is responsible for throwing
SecurityException
(a built-in excep-
tion class defined in the
System.Security
namespace) if the current user is not authorized
to perform a given set of actions for the specified entity type. Here is how this method is
implemented in the
UnleashedObjectContext
class:
private static void Authorize(Type entityType, Actions action)
{
IPrincipal user =
Thread.CurrentPrincipal
;
if (!
IsAuthorized
(user, entityType, action))
{
throw new
SecurityException
(string.Format(
“User '{0}' is not authorized to {1} entities of type '{2}'”,
user.Identity.Name, action, entityType.Name));
}
}
To obtain the
IPrincipal
object representing the current user of the application, the
Authorize
method relies on the static property of the
Thread
class called
CurrentPrincipal
.
This is different from how you implemented the authorization logic in the dynamic page
templates earlier. There, you used the
User
property of the
Page
class, and although the
static
User
property of the
HttpContext
class would be a closer alternative, using the
Thread.CurrentPrincipal
in the UnleashedObjectContext avoids adding dependency on
the ASP.NET to the business layer.
The
Authorize
method delegates the task of evaluating the authorization rules to the
IsAuthorized
method, which takes a user, an entity type, and a set of actions as parame-
ters and returns a boolean value, which indicates whether the user is permitted to perform
them. This method tries to find the
AuthorizationAttribute
that might be applied to the
entity class and, if found, calls its
IsAuthorized
method to evaluate the authorization
rules. If the
AuthorizationAttribute
cannot be found,
IsAuthorized
method returns
true
, following the ASP.NET convention of allowing access unless it is explicitly denied.
private static readonly
ConcurrentDictionary<Type, AuthorizationAttribute>
authorizationAttributes = new ConcurrentDictionary<Type,
AuthorizationAttribute>();
private static bool IsAuthorized(IPrincipal user, Type entityType,
Actions action)
{
var authorizationAttribute = authorizationAttributes.
GetOrAdd
(
entityType,
type =>
TypeDescriptor.GetAttributes
(type)
.OfType<AuthorizationAttribute>().FirstOrDefault());