Sudden 'No valid key mapping found for securityToken' error - azure

TL;DR
Our website suddenly had the below error with no code or web.config changes. Would Azure have changed?
I have a website which has been running on Azure with no issues for a few months. Then the other day, we now have this error:
WIF10201: No valid key mapping found for securityToken: 'System.IdentityModel.Tokens.X509SecurityToken' and issuer: 'https://sts.windows.net/<guid>/'.
We have made no changes to the web.config or the values in Tenants and IssuingAuthorityKeys.
Searching SO and the web give lots of code based answers, but we haven't changed any code.
The web.config is like this:
<system.identityModel>
<identityConfiguration>
<issuerNameRegistry type="DatabaseIssuerNameRegistry, Site.Web" />
<audienceUris>
<add value="https://localhost:44301" />
<add value="https://<other urls...>" />
</audienceUris>
<securityTokenHandlers>
<add type="System.IdentityModel.Services.Tokens.MachineKeySessionSecurityTokenHandler, System.IdentityModel.Services, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<remove type="System.IdentityModel.Tokens.SessionSecurityTokenHandler, System.IdentityModel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
</securityTokenHandlers>
<certificateValidation certificateValidationMode="None" />
</identityConfiguration>
</system.identityModel>
The issuerNameRegistry class is as follows:
public class DatabaseIssuerNameRegistry : ValidatingIssuerNameRegistry
{
public static bool ContainsTenant(string tenantId)
{
using (DBEntities context = new DBEntities())
{
return context.Tenants
.Where(tenant => tenant.Id == tenantId)
.Any();
}
}
public static bool ContainsKey(string thumbprint)
{
using (DBEntities context = new DBEntities())
{
return context.IssuingAuthorityKeys
.Where(key => key.Id == thumbprint)
.Any();
}
}
public static void RefreshKeys(string metadataLocation)
{
IssuingAuthority issuingAuthority = ValidatingIssuerNameRegistry.GetIssuingAuthority(metadataLocation);
bool newKeys = false;
bool refreshTenant = false;
foreach (string thumbprint in issuingAuthority.Thumbprints)
{
if (!ContainsKey(thumbprint))
{
newKeys = true;
refreshTenant = true;
break;
}
}
foreach (string issuer in issuingAuthority.Issuers)
{
if (!ContainsTenant(GetIssuerId(issuer)))
{
refreshTenant = true;
break;
}
}
if (newKeys || refreshTenant)
{
using (DBEntities context = new DBEntities())
{
if (newKeys)
{
context.IssuingAuthorityKeys.RemoveRange(context.IssuingAuthorityKeys);
foreach (string thumbprint in issuingAuthority.Thumbprints)
{
context.IssuingAuthorityKeys.Add(new IssuingAuthorityKey { Id = thumbprint });
}
}
if (refreshTenant)
{
foreach (string issuer in issuingAuthority.Issuers)
{
string issuerId = GetIssuerId(issuer);
if (!ContainsTenant(issuerId))
{
context.Tenants.Add(new Tenant { Id = issuerId });
}
}
}
context.SaveChanges();
}
}
}
private static string GetIssuerId(string issuer)
{
return issuer.TrimEnd('/').Split('/').Last();
}
protected override bool IsThumbprintValid(string thumbprint, string issuer)
{
return ContainsTenant(GetIssuerId(issuer))
&& ContainsKey(thumbprint);
}
}

Judging from this Technet article, it seems that Microsoft may have updated the way they handle Tenant keys.
I had to add the following code into my Global.asax.cs file:
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
// ....
string configPath = AppDomain.CurrentDomain.BaseDirectory + "\\" + "Web.config";
string metadataAddress =
ConfigurationManager.AppSettings["ida:FederationMetadataLocation"];
ValidatingIssuerNameRegistry.WriteToConfig(metadataAddress, configPath);
}

Check out my answer on a similar post. It only applies to solutions created in VS2013 or later.
https://stackoverflow.com/a/38131092/5919316
Here is a copy of it:
For solutions created in VS2013 and later, the solution should contain the logic to roll over keys automatically. No need to put the value in the web.config file.
You might run into this issue when migrating your solution from local to another environment. In that case you will probably try to point your solution to a new application in Azure Active Directory. Check the following:
Make sure all urls in the web.config are pointing to the correct url not the one automatically generated when you set it up locally
Remove all enteries from IssuingAuthorityKeys table. The keys will autopopulate when you re-build the solution and run it. On the server you might need to replace the dlls manually for it to refresh
Last and most important, delete all rows from the Tenants table. On the first run on the new environment, an Admin from the owning Active Directory has to sign up and authorize the application.
If the values in both tables are still not populated automatically after these steps, check this article for steps on how to manually get the values.

Related

Retrieve the Session in the GlimpseSecurityPolicy RuntimeEvent.ExecuteResource

Using glimpse I'm able to access the session information accept when using the RuntimeEvent.ExecuteResource. Without this the axd file is exposed and I'd rather have it disabled unless specific users are logged in. The session will be null in both examples below. Also I've tried having the class implement IRequiresSessionState but that didn't help either.
namespace Glimpse
{
public class GlimpseSecurityPolicy:IRuntimePolicy
{
public RuntimePolicy Execute(IRuntimePolicyContext policyContext)
{
try
{
var name = HttpContext.Current.Session["username"];
var name2 = policyContext.GetHttpContext().Session["username"];
}
catch (Exception)
{
}
// You can perform a check like the one below to control Glimpse's permissions within your application.
// More information about RuntimePolicies can be found at http://getglimpse.com/Help/Custom-Runtime-Policy
// var httpContext = policyContext.GetHttpContext();
// if (!httpContext.User.IsInRole("Administrator"))
// {
// return RuntimePolicy.Off;
// }
return RuntimePolicy.On;
}
public RuntimeEvent ExecuteOn
{
// The RuntimeEvent.ExecuteResource is only needed in case you create a security policy
// Have a look at http://blog.getglimpse.com/2013/12/09/protect-glimpse-axd-with-your-custom-runtime-policy/ for more details
get { return RuntimeEvent.EndRequest | RuntimeEvent.ExecuteResource; }
}
}
}
The reason for this is that the Glimpse HttpHandler which processes the requests for Glimpse.axd does not implement the IRequireSessionState interface.
It is that HttpHandler that will eventually execute all IRuntimePolicy instances that have RuntimeEvent.ExecuteResource configured as part of the ExecuteOn property value.
I think the easiest solution for you is to create your own IHttpHandler that implements the IRequireSessionState interface and forwards all calls to the Glimpse HttpHandler as shown below.
public class SessionAwareGlimpseHttpHandler : IHttpHandler, IRequiresSessionState
{
private readonly HttpHandler _glimpseHttpHandler =
new Glimpse.AspNet.HttpHandler();
public void ProcessRequest(HttpContext context)
{
_glimpseHttpHandler.ProcessRequest(context);
}
public bool IsReusable
{
get { return _glimpseHttpHandler.IsReusable; }
}
}
Don't forget to update your web.config to use that handler instead of the original one:
...
<system.webServer>
...
<handlers>
<add name="Glimpse" path="glimpse.axd" verb="GET" type="YourNamespace.SessionAwareGlimpseHttpHandler, YourAssembly" preCondition="integratedMode" />
</handlers>
...
</system.webServer>
...
Once all this is in place, you should be able to access the Session inside your IRuntimePolicy.

Instantiation of POCO objects with ServiceStack's IAppSettings is not working

I have registered AppSettings within my AppHost as shown below:
container.Register<IAppSettings>(new AppSettings());
I have added following settings within my web.config file:
<appSettings>
<add key="baseaddress" value="http://example.com" />
<add key="credential" value="{Username:foo,Password:bar}" />
</appSettings>
That's my service:
public class ExampleService : Service
{
public IAppSettings Settings { get; set; }
public void Post(ExampleRequest request)
{
// NOT WORKING -> always NULL!
var credentials = Settings.Get<Credential>("credential", null);
// OK
var baseUrl = Settings.GetString("baseaddress");
// more code...
}
}
This is my Credential class:
public class Credential
{
public string Username { get; set; }
public string Password { get; set; }
}
The baseUrl is always set but the credentials variable is always NULL and I don't know why...
In the latest v4.0.31 of ServiceStack there's First Class support for AppSettings so you don't have to register it yourself as it's already registered for you:
container.Register<IAppSettings>(new AppSettings());
But I've tested this and it works as expected where it deserializes into a populated Credential instance with:
var credential = AppSettings.Get<Credential>("credential", null);
Are you sure you're using the exact key names? as your last sentence uses baseUrl and credentials but your appSettings says baseaddress and credential.
You would need something like this in your config <security mode="TransportWithMessageCredential"> to automatically add a security header to your post. Or you need to add and parse your own headers. You don't show your full web config or a sample call to your "Post" so I am running on some assumptions here.

How do I modify WIF's ValidatingIssuerNameRegistry to support Azure AD, ACS, Facebook, LiveID and other IDPs?

I have an application that I'd like to expose to as many users as possible. To accomplish this I'm following the directions as explained here to connect my app to Azure Active Directory and a variation of these instructions to connect AAD to Azure ACS 2.0.
Azure ACS 2.0 will handle all the federated domains, and Microsoft Accounts (formerly LiveID or Passport). It will also handle Facebook, Twitter, and other OAuth services.
Azure Active directory will handle Office 365, and anyone who is syncing their corporate Active Directory to the cloud.
My home realm discovery page will issue a GET at the following URL to determine if the LiveID or AzureAD domain should be used.
https://login.microsoftonline.com/GetUserRealmExtended.srf?login=EMAIL#COMPANY.com
or
http://odc.officeapps.live.com/odc/emailhrd/getidp?hm=0&emailAddress=USER%COMPANY.com
If the user doesn't exist, I'll use Azure ACS with a federation to that company. Lacking that, the user won't be able to log in.
Now that I explained my configuration, I intend to have Windows Identity Foundation (WIF) to allow authentications from both ACS 2.0 and ADFS.
Question
How do I get WIF 4.5, and specifically the ValidatingIssuerNameRegistry to properly handle multiple trusts to multiple IDPs?
Below is code that comes with VS2013 when federating an application with Azure Active Directory. It responds to all federation requests and does other things that I don't understand. Any links or information on this class would be helpful
public class DatabaseIssuerNameRegistry : ValidatingIssuerNameRegistry
{
public static bool ContainsTenant(string tenantId)
{
using (TenantDbContext context = new TenantDbContext())
{
return context.Tenants
.Where(tenant => tenant.Id == tenantId)
.Any();
}
}
public static bool ContainsKey(string thumbprint)
{
using (TenantDbContext context = new TenantDbContext())
{
return context.IssuingAuthorityKeys
.Where(key => key.Id == thumbprint)
.Any();
}
}
public static void RefreshKeys(string metadataLocation)
{
IssuingAuthority issuingAuthority = ValidatingIssuerNameRegistry.GetIssuingAuthority(metadataLocation);
bool newKeys = false;
foreach (string thumbprint in issuingAuthority.Thumbprints)
{
if (!ContainsKey(thumbprint))
{
newKeys = true;
break;
}
}
if (newKeys)
{
using (TenantDbContext context = new TenantDbContext())
{
context.IssuingAuthorityKeys.RemoveRange(context.IssuingAuthorityKeys);
foreach (string thumbprint in issuingAuthority.Thumbprints)
{
context.IssuingAuthorityKeys.Add(new IssuingAuthorityKey { Id = thumbprint });
}
context.SaveChanges();
}
}
}
public static bool TryAddTenant(string tenantId, string signupToken)
{
if (!ContainsTenant(tenantId))
{
using (TenantDbContext context = new TenantDbContext())
{
SignupToken existingToken = context.SignupTokens.Where(token => token.Id == signupToken).FirstOrDefault();
if (existingToken != null)
{
context.SignupTokens.Remove(existingToken);
context.Tenants.Add(new Tenant { Id = tenantId });
context.SaveChanges();
return true;
}
}
}
return false;
}
public static void AddSignupToken(string signupToken, DateTimeOffset expirationTime)
{
using (TenantDbContext context = new TenantDbContext())
{
context.SignupTokens.Add(new SignupToken
{
Id = signupToken,
ExpirationDate = expirationTime
});
context.SaveChanges();
}
}
public static void CleanUpExpiredSignupTokens()
{
DateTimeOffset now = DateTimeOffset.UtcNow;
using (TenantDbContext context = new TenantDbContext())
{
IQueryable<SignupToken> tokensToRemove = context.SignupTokens.Where(token => token.ExpirationDate <= now);
if (tokensToRemove.Any())
{
context.SignupTokens.RemoveRange(tokensToRemove);
context.SaveChanges();
}
}
}
protected override bool IsThumbprintValid(string thumbprint, string issuer)
{
string issuerID = issuer.TrimEnd('/').Split('/').Last();
return ContainsTenant(issuerID) &&
ContainsKey(thumbprint);
}
}
Vittorio Bertocci does a good job of explaining the DatabaseIssuerNameRegistry in this post.
VS2013 RTM, Organizational Accounts and Publishing to Windows Azure Web Sites!
The bottom line is that DatabaseIssuerNameRegistry is just an Entity Framework based ValidatingIssuerNameRegistry that looks up the issuer name from a database using the the thumbprint of the token and verifies that it matches the configured value for the Issuer name, as opposed to using the web.config.It is more flexible and handles updating thumbprints if/when the authority changes them.

sharepoint custom workflow activity is doing nothing, not even log messages

I am trying to create a custom workflow activity which gives me the list of recipients that I am storing in list. But once I deploy and start the workflow nothing is happening, not even log messages are coming. So i tried to debug the code but breakpoints are not set and I am getting the error "The Breakpoint will not currently be hit. No symbols have been loaded for this document." Can anyone please help me to deal with this issue.
Below are the steps I have followed in creating this activity.
1. created a workflow activity library.
(please find my code file attached)
added .dll to GAC
updated web.config and WSS.actions files.
Now I see the action in designer, so i have created a workflow using designer.
strted the workflow manually on an item.
Here nothing is happening, not even an error. Please let me know if you need any further information.
Please find the code below.
using System;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Collections;
using System.Drawing;
using System.Linq;
using System.Workflow.ComponentModel.Compiler;
using System.Workflow.ComponentModel.Serialization;
using System.Workflow.ComponentModel;
using System.Workflow.ComponentModel.Design;
using System.Workflow.Runtime;
using System.Workflow.Activities;
using System.Workflow.Activities.Rules;
using Microsoft.SharePoint;
using System.Diagnostics;
using Microsoft.SharePoint.Workflow;
using Microsoft.SharePoint.WorkflowActions;
namespace CustomWorkflowActivityLibrary
{
public partial class CustomWorkflowActivity: SequenceActivity
{
SPList _list;
private EventLog _log;
SPFieldUserValueCollection objUserFieldValueCol;
string semailsettingKeyword1;
string semailsettingKeyword2;
public CustomWorkflowActivity()
{
InitializeComponent();
}
public static DependencyProperty __ContextProperty = DependencyProperty.Register("__Context", typeof(WorkflowContext), typeof(CustomWorkflowActivity));
[DescriptionAttribute("__Context")]
[BrowsableAttribute(true)]
[DesignerSerializationVisibilityAttribute(DesignerSerializationVisibility.Visible)]
public WorkflowContext __Context
{
get { return ((WorkflowContext)(base.GetValue(CustomWorkflowActivity.__ContextProperty))); }
set { base.SetValue(CustomWorkflowActivity.__ContextProperty, value); }
}
public static DependencyProperty ListIdProperty = DependencyProperty.Register("ListId", typeof(string), typeof(CustomWorkflowActivity));
[DescriptionAttribute("ListId")]
[BrowsableAttribute(true)]
[DesignerSerializationVisibilityAttribute(DesignerSerializationVisibility.Visible)]
public string ListId
{
get { return ((string)(base.GetValue(CustomWorkflowActivity.ListIdProperty))); }
set { base.SetValue(CustomWorkflowActivity.ListIdProperty, value); }
}
public static DependencyProperty ListItemProperty = DependencyProperty.Register("ListItem", typeof(int), typeof(CustomWorkflowActivity));
[DescriptionAttribute("ListItem")]
[BrowsableAttribute(true)]
[DesignerSerializationVisibilityAttribute(DesignerSerializationVisibility.Visible)]
public int ListItem
{
get { return ((int)(base.GetValue(CustomWorkflowActivity.ListItemProperty))); }
set { base.SetValue(CustomWorkflowActivity.ListItemProperty, value); }
}
private void codeActivity1_ExecuteCode(object sender, EventArgs e)
{
}
protected override ActivityExecutionStatus Execute(ActivityExecutionContext executionContext)
{
_log = new EventLog("Add Description");
_log.Source = "Share Point Workflows";
try
{
//Execute method as a elevated method
SPSecurity.CodeToRunElevated elevatedExecuteMethod = new SPSecurity.CodeToRunElevated(ExecuteMethod);
SPSecurity.RunWithElevatedPrivileges(elevatedExecuteMethod);
}
catch (Exception ex)
{
_log.WriteEntry("Error" + ex.Message.ToString(), EventLogEntryType.Error);
}
return ActivityExecutionStatus.Closed;
}
private void ExecuteMethod()
{
try
{
//retrieveing the Site object
SPSite _site = new SPSite(__Context.Site.Url);
//retrieveing the Web object
SPWeb _web = (SPWeb)(__Context.Web);
//retrieveing the list object
_list = _web.Lists[new Guid(this.ListId)];
//retrieveing the list item object
SPListItem _listItem = _list.GetItemById(this.ListItem);
_site.AllowUnsafeUpdates = true;
_web.AllowUnsafeUpdates = true;
string semailsubject = _listItem["E-Mail Subject"].ToString();
string semailfrom = _listItem["emailfrom"].ToString();
_log = new EventLog("get vendor info");
_log.WriteEntry("semailsubject");
_log.WriteEntry("semailfrom");
/* _listItem.Update();
_list.Update();
_site.AllowUnsafeUpdates = false;
_web.AllowUnsafeUpdates = false;*/
using (SPSite mysite = new SPSite("http://dlglobaltest.dl.com/Admin/IT/Application%20Development%20Group/LibraryEmailDistribution"))
{
using (SPWeb myweb = mysite.OpenWeb())
{
SPList settingsList = myweb.Lists["EmailDistributionSettings"];
SPQuery oQuery = new SPQuery();
oQuery.Query = "<Where><Eq><FieldRef Name='Sender' /><Value Type='Text'>" + semailfrom + "</Value></Eq></Where>";
SPListItemCollection ColListItems = settingsList.GetItems(oQuery);
foreach (SPListItem oListItem in ColListItems)
{
semailsettingKeyword1 = oListItem["Keyword1"].ToString();
semailsettingKeyword2 = oListItem["Keyword2"].ToString();
//SPFieldUserValue objUserFieldValue = new SPFieldUserValue(myweb, oListItem["Recipients"].ToString());
if ((semailsubject.Contains(semailsettingKeyword1)) || (semailsubject.Contains(semailsettingKeyword2)))
{
objUserFieldValueCol = new SPFieldUserValueCollection(myweb, oListItem["Recipients"].ToString());
_log = new EventLog(objUserFieldValueCol.ToString());
}
}
}
}
}
catch (Exception ex)
{ }
}
}
}
Web.Config:
<authorizedType Assembly="CustomWorkflowActivityLibrary, Version=1.0.0.0, Culture=neutral, PublicKeyToken=a95e146fc1062337" Namespace="CustomWorkflowActivityLibrary" TypeName="*" Authorized="True" />
WSS.Actions:
<Action Name="Get Recipients"
ClassName="CustomWorkflowActivityLibrary.CustomWorkflowActivity"
Assembly="CustomWorkflowActivityLibrary, Version=1.0.0.0, Culture=neutral, PublicKeyToken=a95e146fc1062337"
AppliesTo="all" Category="Custom">
<RuleDesigner Sentence="Get Recipients for %1 ">
<FieldBind Field="ListId,ListItem" Text="this list" Id="1" DesignerType="ChooseListItem" />
</RuleDesigner>
<Parameters>
<Parameter Name="__Context" Type="Microsoft.SharePoint.WorkflowActions.WorkflowContext" Direction="In" />
<Parameter Name="ListId" Type="System.String, mscorlib" Direction="In" />
<Parameter Name="ListItem" Type="System.Int32, mscorlib" Direction="In" />
</Parameters>
</Action>
Thanks,
I am not sure if this will help but you could try changing the following line in your code from this:
SPSecurity.RunWithElevatedPrivileges(elevatedExecuteMethod);
To this:
SPSecurity.RunWithElevatedPrivileges(delegate(){
ExecuteMethod();
});
Another shot-in-the-dark reply:
Try changing the class you're inheriting ( http://msdn.microsoft.com/en-us/library/ms173149(v=VS.80).aspx ) from SequenceActivity to Activity (SequenceActivity inherits from CompositeActivity, which itself inherits from Activity. See: http://msdn.microsoft.com/en-us/library/system.workflow.activities.sequenceactivity(v=VS.90).aspx )
If that doesn't work, try removing your constructor entirely. You should be able to use the base (Sequence)Activity constructor (since you're inheriting the class, not implementing it)
Hope that helps...

In sharepoint designer's workflow editor how do I get the workflow initiators username?

In Sharepoint designer's workflow editor I wish to retrieve the username/name of the work flow initiator (i.e. who kicked it off or triggered the workflow) - this is relatively easy to do using 3rd party products such as Nintex Workflow 2007 (where I would use something like {Common:Initiator}) - but I can't seem to find any way out of the box to do this using share point designer and MOSS 2007.
Update
It does not look like this rather obvious feature is supported OOTB, so I ended up writing a custom activity (as suggested by one of the answers). I have listed the activities code here for reference though I suspect there are probably a few instances of this floating around out there on blogs as it's a pretty trivial solution:
public partial class LookupInitiatorInfo : Activity
{
public static DependencyProperty __ActivationPropertiesProperty =
DependencyProperty.Register("__ActivationProperties",
typeof(Microsoft.SharePoint.Workflow.SPWorkflowActivationProperties),
typeof(LookupInitiatorInfo));
public static DependencyProperty __ContextProperty =
DependencyProperty.Register("__Context", typeof (WorkflowContext),
typeof (LookupInitiatorInfo));
public static DependencyProperty PropertyValueVariableProperty =
DependencyProperty.Register("PropertyValueVariable", typeof (string),
typeof(LookupInitiatorInfo));
public static DependencyProperty UserPropertyProperty =
DependencyProperty.Register("UserProperty", typeof (string),
typeof (LookupInitiatorInfo));
public LookupInitiatorInfo()
{
InitializeComponent();
}
[Description("ActivationProperties")]
[ValidationOption(ValidationOption.Required)]
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
public Microsoft.SharePoint.Workflow.SPWorkflowActivationProperties __ActivationProperties
{
get { return ((Microsoft.SharePoint.Workflow.SPWorkflowActivationProperties)(base.GetValue(__ActivationPropertiesProperty))); }
set { base.SetValue(__ActivationPropertiesProperty, value); }
}
[Description("Context")]
[ValidationOption(ValidationOption.Required)]
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
public WorkflowContext __Context
{
get { return ((WorkflowContext)(base.GetValue(__ContextProperty))); }
set { base.SetValue(__ContextProperty, value); }
}
[Description("UserProperty")]
[ValidationOption(ValidationOption.Required)]
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
public string UserProperty
{
get { return ((string) (base.GetValue(UserPropertyProperty))); }
set { base.SetValue(UserPropertyProperty, value); }
}
[Description("PropertyValueVariable")]
[ValidationOption(ValidationOption.Required)]
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
public string PropertyValueVariable
{
get { return ((string) (base.GetValue(PropertyValueVariableProperty))); }
set { base.SetValue(PropertyValueVariableProperty, value); }
}
protected override ActivityExecutionStatus Execute(ActivityExecutionContext executionContext)
{
// value values for the UserProperty (in most cases you
// would use LoginName or Name)
//Sid
//ID
//LoginName
//Name
//IsDomainGroup
//Email
//RawSid
//Notes
try
{
string err = string.Empty;
if (__ActivationProperties == null)
{
err = "__ActivationProperties was null";
}
else
{
SPUser user = __ActivationProperties.OriginatorUser;
if (user != null && UserProperty != null)
{
PropertyInfo property = typeof (SPUser).GetProperty(UserProperty);
if (property != null)
{
object value = property.GetValue(user, null);
PropertyValueVariable = (value != null) ? value.ToString() : "";
}
else
{
err = string.Format("no property found with the name \"{0}\"", UserProperty);
}
}
else
{
err = "__ActivationProperties.OriginatorUser was null";
}
}
if (!string.IsNullOrEmpty(err))
Common.LogExceptionToWorkflowHistory(new ArgumentOutOfRangeException(err), executionContext,
WorkflowInstanceId);
}
catch (Exception e)
{
Common.LogExceptionToWorkflowHistory(e, executionContext, WorkflowInstanceId);
}
return ActivityExecutionStatus.Closed;
}
}
And then wire it up with the following .action xml file:
<?xml version="1.0" encoding="utf-8"?>
<WorkflowInfo Language="en-us">
<Actions>
<Action Name="Lookup initiator user property"
ClassName="XXX.ActivityLibrary.LookupInitiatorInfo"
Assembly="XXX.ActivityLibrary, Version=1.0.0.0, Culture=neutral, PublicKeyToken=XXX"
AppliesTo="all"
Category="WormaldWorkflow Custom Actions">
<RuleDesigner Sentence="Lookup initating users property named %1 and store in %2">
<FieldBind Field="UserProperty" DesignerType="TextArea" Id="1" Text="LoginName" />
<FieldBind Field="PropertyValueVariable" DesignerType="ParameterNames" Text="variable" Id="2"/>
</RuleDesigner>
<Parameters>
<Parameter Name="__Context" Type="Microsoft.Sharepoint.WorkflowActions.WorkflowContext, Microsoft.SharePoint.WorkflowActions" Direction="In"/>
<Parameter Name="__ActivationProperties" Type="Microsoft.SharePoint.Workflow.SPWorkflowActivationProperties, Microsoft.SharePoint" Direction="In"/>
<Parameter Name="UserProperty" Type="System.String, mscorlib" Direction="In" />
<Parameter Name="PropertyValueVariable" Type="System.String, mscorlib" Direction="Out" />
</Parameters>
</Action>
</Actions>
</WorkflowInfo>
For those that google into this article and are now using SharePoint 2010, the workflow initiator variable is now supported OOTB in SharePoint Designer.
The datasource would be "Workflow Context" and the field is, of course, "Initiator" and you can choose to return it as the "Display Name", "Email", "Login Name" or the "User ID Number"
I don't think this is possible to do in SharePoint Designer out of the box. You could probably write a custom action to get the originator, but I don't believe it is exposed through the SPD workflow interface at all.
The best you could probably do is get the user who created or modified the item in the list, but this wouldn't handle cases where the workflow was manually run.
I can think about a simple but not very sophisticated solution for this one by using just SPD. Just in workflow steps create a test item in a secondary list (probably a task list which stores the workflowId and itemId properties for refrence back) and then do a lookup in your workflow on that list to see who is the creator of that item, that value would be the current workflow initiator.
The custom activity solution only work if you are working with moss, if you only have wss 3.0 you can put one step more in your workflow and set a custom comment field with any information, this make the last modified person to change and become the same as the workflow initiator, then you can use the ModifiedBy field to make any decision that you need.

Resources