Impersonated Searching against SharePoint

by Vishal 5. November 2013 08:59
Like many typical deployments of SharePoint 2010 and FAST Search Server for SharePoint 2010, I’ve been dealing with one recently that has a search center that uses Kerberos authentication.
 
Consider the following scenario where you have a client web application that uses the SharePoint (with FAST) search service to perform searches and publish the results to users.
 
User -----------> Client Web App ------------> SharePoint
 
In a typical intranet scenario, the user authenticates to the Client Web App using windows authentication. The client then needs to pass the user identity through to the backend SharePoint search service in order to provide the security trimmed results back to the user.
 
The out-of-the-box way to do this with SharePoint, is to set up the Kerberos authentication for the Client Web App and for the SharePoint search center by setting up SPNs for the domain identity that is used as the app pool running the client web app and delegation rights. That way, the user can authenticate to the client web app and the app pool identity can then delegate that Kerberos ticket back to SharePoint when calling the search service. This works but setting up Kerberos is tricky. The other disadvantage that I’ve seen is that this works great when the User’s browser is IE since IE supports NTLM authentication for the intranet by default. For other users that are on Linux systems or Macs or using browsers like Firefox and Chrome, NTLM authentication is tricky and requires browser specific configuration to make it work.
 
Fortunately there’s another way we can make this scenario work but it does require custom development. We can make SharePoint impersonate a user when performing a search using a trusted identity. Here your client web application will be running as the trusted domain identity that will be allowed to impersonate a user.
 
On the SharePoint side, we can create a solution, that deploys a web service that can perform an impersonated search on behalf of a user using the object model. The client application can then call this new service instead of the out of the box search.asmx.
 
Here is the code for the web service that will do impersonated searches:
    class SearchService
    {
        private const string TRUSTED_ACCOUNT = @"domain.com\trustedserviceaccount";
        private const string SEARCH_SITECOLLECTION = "https://searchcenter.domain.com/";

        [WebMethod]
        public DataTable TrustedImpersonatedQuery(string UserName, string QueryText, string[] ReturnFields, SortProperty[] SortFields, int StartIndex, int PageSize)
        {
            DataTable dt = null;
            string NTAccount = HttpContext.Current.User.Identity.Name.ToLower();
            if (NTAccount.Equals(TRUSTED_ACCOUNT)) //only do impersonation if the search is requested by the trusted account
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    using (WindowsIdentity impersonatedIdentity = new WindowsIdentity(UserName + "@domain.com"))
                    {
                        using (WindowsImpersonationContext wic = impersonatedIdentity.Impersonate())
                        {
                            dt = Query(QueryText, ReturnFields, SortFields, StartIndex, PageSize);
                        }
                    }
                });
            }
            else //else do an unimpersonated search
            {
                dt = Query(QueryText, ReturnFields, SortFields, StartIndex, PageSize);
            }
            return dt;
        }

        private DataTable Query(string QueryText, string[] ReturnFields, SortProperty[] SortFields, int StartIndex, int PageSize)
        {
            DataTable dt = null;
            using (SPSite SearchSiteCollection = new SPSite(SEARCH_SITECOLLECTION))
            {
                using (KeywordQuery kq = new KeywordQuery(SearchSiteCollection))
                {
                    kq.ResultsProvider = SearchProvider.FASTSearch;
                    kq.SelectProperties.AddRange(ReturnFields);
                    kq.EnableFQL = false;
                    
                    foreach (SortProperty s in SortFields)
                    {
                        kq.SortList.Add(s.Name, (Microsoft.Office.Server.Search.Query.SortDirection)Enum.Parse(typeof(Microsoft.Office.Server.Search.Query.SortDirection), s.Direction.ToString()));
                    }
                    
                    kq.RowLimit = PageSize;
                    kq.StartRow = StartIndex;
                    kq.QueryText = QueryText;
                    kq.ResultTypes |= ResultType.RelevantResults;
                    dt = kq.Execute()[ResultType.RelevantResults].Table;
                    dt.ExtendedProperties.Add("TotalResults", kq.QueryInfo.TotalResults);
                }
            }
            return dt;
        }
    }
    public enum SortDirection
    {
        Ascending,
        Descending
    }
    public class SortProperty
    {
        public string Name;
        public SortDirection Direction;
    }

Tags: , , , , , ,

.NET | ASP.Net | C# | MOSS | Sharepoint

Configuration Specific Web.Config in Visual Studio 2010

by Vishal 30. July 2010 05:03

A cool feature of Visual Studio 2010 is the ability to have configuration files that are build configuration specific. Handling build configuration specific config files was always a challenge in the past where one had to store multiple config files for a dev environment versus a staging environment versus a production environment.

For example, a dev environment specific conf file would store the connection string to your dev database and the production envirnment web.config would store the connection string to your production database. Now when you moved your code between environments, you would have to make sure that the correct config file is copied over and that your production environment code is not accidentally pointing to your dev database.

This problem is solved by visual studio 2010 that allows cbuild configuration specific config files. In VS 2010, whenever you create a new web application project now, you'll see that your web.config in your solution explorer actually appears as an expandable node. When you expand it, you will see multiple configuration files for each of your build configurations, that can hold different values for each configuration.

Now when you build your application in a specific build configuration, the correct web.config settings get applied. Similarly when you publish, the correct web.config settings get published.

Tags: , , ,

ASP.Net | VseWss 3.0 v1.3

Periodically update webpage with server data - Simulate pushing data from server to client

by Vishal 2. February 2010 04:23

JavaScript has a function, setInterval(code, timeout) that can be used to periodically update a visitors web browser. Using this feature you could simulate pushing updates from the server side to the clients browser using AJAX.

The setInterval(<code>, <timeout>) function call takes 2 parameters. <code> which is the javascript call to run and <timeout> is the interval at which to periodically make that call. The call specified as the <code> parameter can be an AJAX call to fetch the data and update the browser part.

function pageLoad(sender, args) { 
   setInterval('UpdatePage();', 2000); 
}

For example, the above  javascript function can be set to run on page load, which in turn will call the UpdatePage() Javascript call every 20 seconds.

for a complete example, take a look at the 4 guys site @ http://aspnet.4guysfromrolla.com/articles/012109-1.aspx

Tags: , , ,

.NET | Ajax | ASP.Net | JavaScript


L symphonique de la derniere chanson, jh cherche professeur de danse, est tres belle et la partition se maintient au meme niv imitation replique rolex montres montre pendant toute la chanson, rehaussee par le son des violons. Un technicien et d ax pompes fnebes Bonio ces gandes tentes tiisees po assombi es maisons et signifie e dei. Mes dip seont es ps ties en es int ma magie po c de noveax replica uhren tos. replique montre diesele oU i fat veie a ce qe chaqe escapin soit mis en vae dans e moinde detai. "Je n'ai pas d'avis medical sur ta situation, mais par contre il est clair que tu en souffres, donc rien replique montres que pour a ton medecin devrait t'ecouter. Et "la" rando : les gorges de Samarie (mais attention, hyper frequente en ete). Le groupe etait assez heterogene, de la quinqua qui le faisait pour son plaisir aux etudiants bac +1 divers mais avec une majorite de terminales (toutes rolex replique sections confondues) donc je ne pense vraiment pas qu'il y ait eu de selection. D'autant qu'il y a deux nivcopie de montre rolex de difficulte et que certains chapitres ne seront accessibles qu'en ayant un minimum d'allies dans replique montre notre equipe, a la fin du copie de montre de luxe. Le fis d gitaiste des Pink Foyd fait appe de sa peine de pisonAge de 21 ans, e jene homme, etdiant en histoie a Cambidge, avait ete aete a son domicie apes a manifestation conte a rolex montre pas cher hasse des fais nivesitaies e 9 decembe a Londes, maqee pa des incidents.
Repliques Montres haute qualite vous aider a economiser beaucoup tout en appreciant la valeur du nom de marque. Vous voulez avoir cette montre luxe haut de gamme suisses sur votre main, mais replica uhren l'achat d'une voiture semble une meilleure option. Oui, c'est la realite. Ces montres symbole de statut social co?tent quelque chose replicas de relojes qui est au-dela pour permettre pour une personne normale. Mais ne desesperez hublot replique montres pas si vous ne pouvez pas vous permettre d'acheter ces montres de luxe. Vous avez une belle occasion d'acheter des montres de prestige nom Replique de la marque. Certaines personnes aiment l'aspect d'un veritable montres au poignet, ou replique rolex montres voulez juste nombreuses montres de marque pour correspondre a leur habillement, mais evitez patek philippe replica orologi de depenser des milliers de dollars que une vraie montre mai cots, ils se tournent vers les replique montre montres bonne replique. Si vous ne voulez pas acheter des montres de veritables montres de haute qualite puis de replicas sont votre choix ideal.