Running code inside MOSS with elevated permissions
Last week I was working on a simple web part that would get come data from an MS SQL database and show in a grid. Per client's infrastructure requirements the connection to the sql server might only be done using integrated security, as sql users are not allowed to be created/used. By default, if you specify "Trusted_Connection = true", one of three things would happen: if the user is accessing the web site locally (the same server the MOSS WFE is running), her credentials will be used to connect to the SQL server; if the user is accessing the web site from the remote computer then depending on whether KerberOS authentication is turned on on the network either the user credentials or NT AUTHORITY/ANONIMOUS USER will be used for connection. Neither would not work in our case as the network team refused to enable KerberOS; after some research and with a hint from our inhouse MOSS guru Ryan Thomas I found that MOSS API gives you a way of executing a piece of code as the user running MOSS application pool; the way of doing it is in fact as easy as invoking a delegate;
you need to pass a delegate to a method containing your code to SPSecurity.RunWithElevatedPrivileges() method; it's even easier when using anonymous delegates feature of C# 2.0:
SPSecurity
.RunWithElevatedPrivileges(new SPSecurity.CodeToRunElevated(delegate() {
... your code to connect to SQL server ...
}));
And all you have left to do is to configure appropriate permissions for the App Pool user on the SQL server.