Impersonating other users in code

When you're writing code using the Adam API, you can rely on the fact that Adam will automatically perform the necessary security checks so users that are logged in using your code will not be able to perform any operation that they're not allowed to. Also, the API will never load any objects to which the logged on user does not have read-access. While this is desired behavior most of the times, sometimes you would like your code to do some operation that the user logged on normally does not have the right to do.

For example, while normal users normally don't have any permission to create new user-profiles, you might want to allow such a user to do just that in a form in which he can request a new user account for himself.

This can easily be done using the ImpersonationContext class. Using this class, you can change the user-account assigned of an active Application-object to any other user. Typically, for simplicity reasons, people are going to impersonate the built-in Administrator-account, but any other user is possible as well. Always call the Dispose-method of the context class when you're done impersonating to ensure that you restore the normal user's session. We recommended using the using keyword in C#.

The following code for example, shows how to impersonate the administrator to create a new user account:

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// Temporary allow the code within the using-clause to
// impersonate the built-in Administrator account so that
// the code do some operation the currently logged on user 
// normally isn't allowed to do.
using (ImpersonateContext context = new ImpersonateContext(
  app, User.AdministratorId))
{
  // Calculate a new password...
  string password = new UserHelper(app).GetRandomPassword();

  // Create a new user profile...
  User user = new User(app);
  user.AddNew();
  user.Name = myUserName;
  user.Password = password;
  user.Save();
}

Comments

Leave a comment
You must be logged in to post comments.
Sign in now
 
 
Technical
Business
rss feed