To build on the answers given by Anders Rask, if you want to allow anonymous users to submit an InfoPath form (e.g., an InfoPath form on an Internet website), you will likely need to impersonate another account to perform the submission. However, if only authenticated users should be able to submit the form, a custom permission level is probably a better approach. In that case, I would suggest creating a SharePoint group for the InfoPath form(s), granting the custom permission level to the SharePoint group, and adding anyone that needs to submit the InfoPath form(s) to the SharePoint group.
From a performance standpoint, I believe it is best to cache SharePoint objects instead of calling the same SharePoint API multiple times, since there is often extensive logic associated with retrieving SharePoint objects. In addition, as indicated by the CA1822: Mark members as static code analysis warning, methods should be static unless they need access to instance data. Thus, the impersonation pattern becomes:
SPContext context = SPContext.Current;
SPSite contextSite = context.Site;
SPWeb contextWeb = context.Web;
using (SPSite site = new SPSite(contextSite.ID, GetSystemToken(contextSite))) {
using (SPWeb web = site.OpenWeb(contextWeb.ID)) {
// Do real work here
}
}
static SPUserToken GetSystemToken(SPSite site) {
bool cade = SPSecurity.CatchAccessDeniedException;
SPSecurity.CatchAccessDeniedException = false;
SPUserToken token = null;
try {
token = site.SystemAccount.UserToken;
}
catch (UnauthorizedAccessException) {
SPSecurity.RunWithElevatedPrivileges(delegate() {
using (SPSite elevatedSite = new SPSite(site.ID)) {
token = elevatedSite.SystemAccount.UserToken;
}
});
}
finally {
SPSecurity.CatchAccessDeniedException = cade;
}
return token;
}
Note: The code pattern above can be used to impersonate any account by replacing GetSystemToken(contextSite) with the appropriate SPUserToken.