Skip to main content

Set User Roles for Scheduled Jobs in Optimizely

ยท One min read

You can assign a principal with roles to a scheduled job using an extension method:

Extension Method

public static class ScheduledJobBaseExtensions
{
private static Injected<IPrincipalAccessor> _principalAccessor;

/// Sets the principal for the job, including name and roles.
public static void SetPrincipal(this ScheduledJobBase job, string name = null, IEnumerable<string> roles = null)
{
name ??= job.GetType().Name;
var claims = new List<Claim> { new Claim(ClaimTypes.Name, name) };
if (roles != null)
claims.AddRange(roles.Select(role => new Claim(ClaimTypes.Role, role)));

_principalAccessor.Service.Principal = new ClaimsPrincipal(new ClaimsIdentity(claims));
}
}

Usage in a jobโ€‹

this.SetPrincipal(roles: new[] { "Administrators" });
  • This ensures scheduled jobs run with the correct user identity and roles.
  • Useful for jobs that require role-based permissions.