Using the Claims to Windows Token Service to run code with different credentials

Every now and then you need to run code with specific credentials. If you have the C2WTS service running you can use that to get an identity and then use impersonation to run code with the credentials of the given identity. I created myself a helper method to make this a bit easier:

    public static class SecurityHelper {
        public static void RunAs(string upn, Action action) {
            using (var identity = S4UClient.UpnLogon(upn))
            using (var context = identity.Impersonate())
            {
                try {
                    action();
                } finally {
                    if (context != null) {
                        context.Undo();
                    }
                }
            }
        }
    }

 

You can use this helper class in the following way:

    SecurityHelper.RunAs(upn, () => {
        using (var connection = new SqlConnection("Server=.;Database=DatabaseName;Integrated Security=True"))
        using (var command = new SqlCommand("SomeStoredProcedure", connection)) {
            command.CommandType = CommandType.StoredProcedure;

            try {
                connection.Open();
                customClaimValue = command.ExecuteScalar();
            } catch (Exception ex) {
                customClaimValue = ex.ToString();
            }
        }
    });

The above code will connect to SQL server with the identity of the given UPN.

Cheers,

Wesley

No Comments