コード例 #1
0
        protected void Page_Load(object sender, EventArgs e)
        {
            TokenHelper.TrustAllCertificates();
            string contextTokenString = TokenHelper.GetContextTokenFromRequest(Request);

            if (contextTokenString != null)
            {
                contextToken =
                    TokenHelper.ReadAndValidateContextToken(contextTokenString, Request.Url.Authority);

                sharepointUrl = new Uri(Request.QueryString["SPAppWebUrl"]);
                accessToken =
                    TokenHelper.GetAccessToken(contextToken, sharepointUrl.Authority).AccessToken;
                AddListButton.CommandArgument = accessToken;
                RefreshListButton.CommandArgument = accessToken;
                RetrieveListButton.CommandArgument = accessToken;
                AddItemButton.CommandArgument = accessToken;
                DeleteListButton.CommandArgument = accessToken;
                ChangeListTitleButton.CommandArgument = accessToken;
                RetrieveLists(accessToken);

            }
            else if (!IsPostBack)
            {
                Response.Write("Could not find a context token.");
            }
        }
コード例 #2
0
ファイル: SharePointContext.cs プロジェクト: Calisto1980/PnP
        public SharePointAcsContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, string contextToken, SharePointContextToken contextTokenObj)
            : base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber)
        {
            if (string.IsNullOrEmpty(contextToken))
            {
                throw new ArgumentNullException("contextToken");
            }

            if (contextTokenObj == null)
            {
                throw new ArgumentNullException("contextTokenObj");
            }

            this.contextToken = contextToken;
            this.contextTokenObj = contextTokenObj;
        }
コード例 #3
0
        protected void Page_Load(object sender, EventArgs e)
        {
            TokenHelper.TrustAllCertificates();
            string contextTokenString = TokenHelper.GetContextTokenFromRequest(Request);

            if (contextTokenString != null)
            {
                contextToken = TokenHelper.ReadAndValidateContextToken(contextTokenString, Request.Url.Authority);
               var hostWeb = Request.QueryString["SPHostUrl"];

               //for admin security--
               //obtain sharepoint url from referrer instead of the Querystring (insures that the app was launched from sharepoint)
               Uri referrer = new Uri(Request.UrlReferrer.ToString());

               //split the referrer host and use only the hostname to get the root tenant id--
               string tenanthost = referrer.Host;
               //get base tenant id by splittin the hosturl
               string[] pieces = tenanthost.Split('.');
               string tenantid = pieces[0];
               //remove any known collection identifiers
               if (tenantid.EndsWith("-my", StringComparison.CurrentCultureIgnoreCase))
               {
                   TenantId = tenantid.Replace("-my", "");
               }
               else if (tenantid.EndsWith("-public", StringComparison.CurrentCultureIgnoreCase))
               {
                   TenantId = tenantid.Replace("-public", "");
               }

                //get user uri from Querystring
               sharepointUrl = new Uri(Request.QueryString["SPHostUrl"]);
               string rooturl = sharepointUrl.GetLeftPart(UriPartial.Authority).Replace("-my.sharepoint", ".sharepoint");

               //get rooturi from base tenantid
               Uri rooturi = new Uri(rooturl);

                //build accessToken for user info
                string accessToken = TokenHelper.GetAccessToken(contextToken, sharepointUrl.Authority).AccessToken;

                //build apponly access token for admin info
                string appOnlyAccessToken = TokenHelper.GetAppOnlyAccessToken(contextToken.TargetPrincipalName, rooturi.Authority, contextToken.Realm).AccessToken;

                //Get site Client context for Current User
                ClientContext clientContext = TokenHelper.GetClientContextWithAccessToken(sharepointUrl.ToString(), accessToken);
                //Get appOnly client context for root calls
                ClientContext clientContextapp = TokenHelper.GetClientContextWithAccessToken(rooturl, appOnlyAccessToken);

                //load current web
                Web web = clientContext.Web;
                clientContext.Load(web);
                clientContext.ExecuteQuery();

               //get logged in user's info
               clientContext.Load(web.CurrentUser);
               clientContext.ExecuteQuery();

               //save loginname
               currentUser = clientContext.Web.CurrentUser.LoginName;
               int userId = clientContext.Web.CurrentUser.Id;
               string userName = clientContext.Web.CurrentUser.Title;

               GroupCollection siteGroups = clientContextapp.Site.RootWeb.SiteGroups;
               clientContextapp.Load(siteGroups);
               clientContextapp.ExecuteQuery();

               UserCollection admins = siteGroups.GetByName("Owners").Users;
               clientContextapp.Load(admins);
               clientContextapp.ExecuteQuery();

               isAdmin = false;
               //var res = "";
               foreach (User user in admins)
                {
                    if (user.LoginName == currentUser)
                    {
                       isAdmin = true;
                    }
                }
            //res += isAdmin;

            //res += siteName;
               // res += currentUser;
            //res += mainurl;
            //res += rooturl;
            //res += referrer;
            //res += isAdmin;
            //res += tenantid;

            //ltlTest.Text = res;
            var vals = checkTenant(TenantId);
            int c = vals.Count;
            if (c > 0)
            {
                hidden.Text = vals[0];
                recommended.Text = vals[1];
                approved.Text = vals[2];
            }
            else
            {
                hidden.Text = "";
                recommended.Text = "1,2,3,4,5,6";
                approved.Text = "0";

            }

            favorites.Text = checkUser(currentUser, TenantId);

            //var initarray = checkTenant(string tenantg);
            //if user has full control of root site, load admin scripts and button
             if (isAdmin)
             {
                 adminscripts.Text = loadAdminScripts();
                 adminbutton.Text = loadAdminButton();
                 adminname.Text = userName;
                 addhiddenfunc.Text = "parse(hidden);addHidden();";
             }
             else
             {
                 adminscripts.Text = "";
                 adminbutton.Text = "";
                 adminname.Text = "";
                 addhiddenfunc.Text = "";
             }

                //

             UserToken = getUserToken(userId);
             usertoken.Text = UserToken;
             insharepoint.Text = "true";
             hostweb.Text = hostWeb;

            }
            else if (!IsPostBack)
            {
                hidden.Text = "";
                recommended.Text = "1,2,3,4,5,6";
                favorites.Text = "";
                approved.Text = "0";
                adminname.Text = "";
                adminbutton.Text = "";
                adminscripts.Text = "";
                insharepoint.Text = "false";
                hostweb.Text = "";
                return;
            }
        }
コード例 #4
0
ファイル: SharePointContext.cs プロジェクト: zkiifreak/PnP
        public SharePointAcsContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, string contextToken, SharePointContextToken contextTokenObj)
            : base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber)
        {
            if (string.IsNullOrEmpty(contextToken))
            {
                throw new ArgumentNullException("contextToken");
            }

            if (contextTokenObj == null)
            {
                throw new ArgumentNullException("contextTokenObj");
            }

            this.contextToken    = contextToken;
            this.contextTokenObj = contextTokenObj;
        }
コード例 #5
0
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                #region HighTrust Version
                ////get the access token and host so that we can use it for other requests on the site
                //var hostWeb = Page.Request["SPHostUrl"];

                ////passing null as the Windows identity so we can use it as an AppOnly request
                //using (var ctx = TokenHelper.GetS2SClientContextWithWindowsIdentity(new Uri(hostWeb), null))
                //{
                //    ctx.Load(ctx.Web, web => web.Title, user => user.CurrentUser);
                //    ctx.ExecuteQuery();
                //    Microsoft.SharePoint.Client.User curUser = ctx.Web.CurrentUser;

                //    //if the current user is me, then show the link to the clean up page
                //    if (curUser.IsSiteAdmin)
                //    {
                //        string link = "<a href='cleanapp.aspx'>Clean Up App</a>";
                //        CleanUpLit.Text = link;
                //    }

                //    //now query the list and get all the social events
                //    Response.Write(ctx.Web.Title);
                //}

                #endregion

                #region LowTrust Version

                if (!IsPostBack)
                {
                    //get the context token and host web
                    var contextToken = TokenHelper.GetContextTokenFromRequest(Page.Request);
                    var hostWeb      = Page.Request["SPHostUrl"];

                    //create the tokenContent from it so we can get an AccessToken to use for AppOnly cals
                    SharePointContextToken tokenContent = TokenHelper.ReadAndValidateContextToken(contextToken, Request.Url.Authority);

                    //get the Access tokenj
                    string accessToken = TokenHelper.GetAccessToken(tokenContent.RefreshToken, TokenHelper.SharePointPrincipal,
                                                                    new Uri(hostWeb).Authority, TokenHelper.GetRealmFromTargetUrl(new Uri(hostWeb))).AccessToken;

                    //now store it in view state so we can call out to other pages in our app with it
                    ViewState[HDN_HOST_WEB]  = hostWeb;
                    ViewState[HDN_ACC_TOKEN] = accessToken;

                    //write it out to hidden so that it can be used by client code
                    //Url encode the hostWeb so it can be passed to REST endpoint and successfully parsed (otherwise the ":" in the URL blocks it)
                    hiddenLit.Text = GetHiddenHtml(HDN_HOST_WEB, HttpUtility.UrlEncode(hostWeb)) + GetHiddenHtml(HDN_ACC_TOKEN, accessToken);

                    // The following code gets the client context and Title property by using TokenHelper.
                    // To access other properties, the app may need to request permissions on the host web.
                    var spContext = SharePointContextProvider.Current.GetSharePointContext(Context);

                    using (var clientContext = spContext.CreateUserClientContextForSPHost())
                    //using (var clientContext = TokenHelper.GetClientContextWithAccessToken(hostWeb, accessToken))
                    {
                        clientContext.Load(clientContext.Web, web => web.Title, user => user.CurrentUser);
                        clientContext.ExecuteQuery();
                        Microsoft.SharePoint.Client.User curUser = clientContext.Web.CurrentUser;

                        //if the current user is me, then show the link to the clean up page
                        if (curUser.IsSiteAdmin)
                        {
                            CleanUpPnl.Visible = true;
                        }

                        ////now query the list and get all the social events
                        //Response.Write(clientContext.Web.Title);

                        #region SQL data test
                        ////TEST TO CHECK OUT DATABASE CONNECTIVITY
                        //SqlConnection cn = new SqlConnection(conStr);
                        //SqlCommand cm = new SqlCommand("tblObjectGraph");
                        //cm.Connection = cn;
                        //cm.CommandText = "select * from tblObjectGraph";
                        //SqlDataAdapter da = new SqlDataAdapter(cm);

                        //DataSet ds = new DataSet();
                        //da.Fill(ds);

                        //string data = string.Empty;
                        //foreach(DataRow dr in ds.Tables[0].Rows)
                        //{
                        //    data += "ID = " + ((double)dr["ObjectGraphID"]).ToString() + "; Url = " + (string)dr["ObjectGraphUrl"] + "; TwitterTags = " + (string)dr["TwitterTags"] + "<br/>";
                        //}

                        //Response.Write("Database data:<p>" + data + "</p>");
                        #endregion

                        #region IIS Info
                        //Response.Write("<p>PhysicalPath = " + Request.PhysicalPath + "<br/>" +
                        //    "PhysicalApplicationPath = " + Request.PhysicalApplicationPath + "<br/></p>");

                        //string vars = string.Empty;
                        //foreach (string key in Request.ServerVariables.Keys)
                        //{
                        //    vars += key + " = " + Request.ServerVariables[key] + "<br/>";
                        //}

                        //Response.Write("<p>Server Variables:</p><p>" + vars + "</p>");
                        #endregion
                    }
                }
                #endregion

                #region LowTrust VS 2012 Version
                // The following code gets the client context and Title property by using TokenHelper.
                // To access other properties, you may need to request permissions on the host web.

                //var contextToken = TokenHelper.GetContextTokenFromRequest(Page.Request);
                //var hostWeb = Page.Request["SPHostUrl"];

                //using (var clientContext = TokenHelper.GetClientContextWithContextToken(hostWeb, contextToken, Request.Url.Authority))
                //{
                //    clientContext.Load(clientContext.Web, web => web.Title, user => user.CurrentUser);
                //    clientContext.ExecuteQuery();
                //    Response.Write(clientContext.Web.Title);
                //}
                #endregion
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
                Response.Write("ERROR: " + ex.Message);
            }
        }
        public static void ListRemoteEventReceiver(SPRemoteEventProperties properties)
        {
            // This code works only if OAuth on the server that's running SharePoint is set up with an ACS token.
            // Code that works with S2S setup is similar, but some changes are required.
            string logListTitle = "EventLog";

            // Return if the event is from the EventLog list. Otherwise, it may go into an infinite loop.
            if (string.Equals(properties.ItemEventProperties.ListTitle, logListTitle, StringComparison.OrdinalIgnoreCase))
            {
                return;
            }

            // Get the token from the request header.
            HttpRequestMessageProperty requestProperty = (HttpRequestMessageProperty)OperationContext.Current.IncomingMessageProperties[HttpRequestMessageProperty.Name];
            string contextTokenString = requestProperty.Headers["X-SP-ContextToken"];

            // If there is a valid token, continue.
            if (contextTokenString != null)
            {
                SharePointContextToken contextToken =
                    TokenHelper.ReadAndValidateContextToken(contextTokenString, requestProperty.Headers[HttpRequestHeader.Host]);

                Uri    sharepointUrl = new Uri(properties.ItemEventProperties.WebUrl);
                string accessToken   = TokenHelper.GetAccessToken(contextToken, sharepointUrl.Authority).AccessToken;
                bool   exists        = false;

                // Retrieve the log list "EventLog" and add the name of the event that occurred to it with a date/time stamp.
                using (ClientContext clientContext = TokenHelper.GetClientContextWithAccessToken(sharepointUrl.ToString(), accessToken))
                {
                    clientContext.Load(clientContext.Web);
                    clientContext.ExecuteQuery();
                    List logList = clientContext.Web.Lists.GetByTitle(logListTitle);

                    try
                    {
                        clientContext.Load(logList);
                        clientContext.ExecuteQuery();
                        exists = true;
                    }

                    catch (Microsoft.SharePoint.Client.ServerUnauthorizedAccessException)
                    {
                        // If the user doesn't have permissions to access the server that's running SharePoint, return.
                        return;
                    }

                    catch (Microsoft.SharePoint.Client.ServerException)
                    {
                        // If an error occurs on the server that's running SharePoint, return.
                        exists = false;
                    }

                    // Create a log list called "EventLog" if it doesn't already exist.
                    if (!exists)
                    {
                        ListCreationInformation listInfo = new ListCreationInformation();
                        listInfo.Title = logListTitle;
                        // Create a generic custom list.
                        listInfo.TemplateType = 100;
                        clientContext.Web.Lists.Add(listInfo);
                        clientContext.Web.Context.ExecuteQuery();
                    }

                    // Add the event entry to the EventLog list.
                    string         itemTitle    = "Event: " + properties.EventType.ToString() + " occurred on: " + DateTime.Now.ToString(" yyyy/MM/dd/HH:mm:ss:fffffff");
                    ListCollection lists        = clientContext.Web.Lists;
                    List           selectedList = lists.GetByTitle(logListTitle);
                    clientContext.Load <ListCollection>(lists);
                    clientContext.Load <List>(selectedList);
                    ListItemCreationInformation listItemCreationInfo = new ListItemCreationInformation();
                    var listItem = selectedList.AddItem(listItemCreationInfo);
                    listItem["Title"] = itemTitle;
                    listItem.Update();
                    clientContext.ExecuteQuery();
                }
            }
        }
コード例 #7
0
        public void PageInitialize()
        {
            sharepointUrl = new Uri(Request.QueryString[Config.ListURL]);

            if (Session[COOKIE_NAME] == null)
            {
                string contextTokenString = TokenHelper.GetContextTokenFromRequest(Request);
                Session["contextToken"] = contextTokenString;
                if (contextTokenString != null)
                {
                    contextToken = TokenHelper.ReadAndValidateContextToken(contextTokenString, Request.Url.Authority);
                    var cookieName = contextToken.CacheKey.Substring(0, 40);
                    Session.Add(COOKIE_NAME, cookieName);
                    var refreshToken = contextToken.RefreshToken;
                    Response.Cookies.Add(new HttpCookie(cookieName, refreshToken));
                    accessToken = TokenHelper.GetAccessToken(refreshToken,
                    SHAREPOINT_2013_PRINCIPAL, sharepointUrl.Authority, TokenHelper.GetRealmFromTargetUrl(sharepointUrl)).AccessToken;
                }
                else if (!IsPostBack)
                {
                    Response.Write("Could not find a context token.");
                    return;
                }
            }
            else
            {
                var key = Session[COOKIE_NAME] as string;
                var refreshToken = Request.Cookies[key].Value;
                accessToken = TokenHelper.GetAccessToken(refreshToken, SHAREPOINT_2013_PRINCIPAL, sharepointUrl.Authority, TokenHelper.GetRealmFromTargetUrl(sharepointUrl)).AccessToken;
            }
        }
コード例 #8
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                Configuration configuration = WebConfigurationManager.OpenWebConfiguration("~");
                TraceSection section = (TraceSection)configuration.GetSection("system.web/trace");
                section.Enabled = false;
                configuration.Save();
            }

            // Get the client context.
            TokenHelper.TrustAllCertificates();
            contextTokenString = TokenHelper.GetContextTokenFromRequest(Request);

            if (contextTokenString != null)
            {
                // Get context token
                contextToken = TokenHelper.ReadAndValidateContextToken(contextTokenString, Request.Url.Authority);

                // Get the host web's URL and the access token.
                sharepointUrl = new Uri(Request.QueryString["SPHostUrl"]);
                accessToken = TokenHelper.GetAccessToken(contextToken, sharepointUrl.Authority).AccessToken;

                // Pass the access token to the button event handler.
                Button1.CommandArgument = accessToken;
            }
        }
コード例 #9
0
ファイル: TokenHelper.cs プロジェクト: bayzid026/mvc
    /// <summary>
    /// Retrieves an access token from ACS to call the source of the specified context token at the specified 
    /// targetHost. The targetHost must be registered for the principal that sent the context token.
    /// </summary>
    /// <param name="contextToken">Context token issued by the intended access token audience</param>
    /// <param name="targetHost">Url authority of the target principal</param>
    /// <returns>An access token with an audience matching the context token's source</returns>
    public static OAuth2AccessTokenResponse GetAccessToken(SharePointContextToken contextToken, string targetHost)
    {
        string targetPrincipalName = contextToken.TargetPrincipalName;

            // Extract the refreshToken from the context token
            string refreshToken = contextToken.RefreshToken;

            if (String.IsNullOrEmpty(refreshToken))
            {
                return null;
            }

            string targetRealm = Realm ?? contextToken.Realm;

            return GetAccessToken(refreshToken,
                                  targetPrincipalName,
                                  targetHost,
                                  targetRealm);
    }
コード例 #10
0
        protected void Page_Load(object sender, EventArgs e)
        {
            uriHostWeb = new Uri(Request.QueryString["SPHostUrl"]);

              contextTokenString = TokenHelper.GetContextTokenFromRequest(Request);

              if (contextTokenString != null) {
            contextToken = TokenHelper.ReadAndValidateContextToken(contextTokenString, Request.Url.Authority);

            targetPrincipalName = contextToken.TargetPrincipalName;
            realm = contextToken.Realm;
            accessToken = TokenHelper.GetAccessToken(contextToken, uriHostWeb.Authority);
            accessTokenString = TokenHelper.GetAccessToken(contextToken, uriHostWeb.Authority).AccessToken;
            appOnlyAccessToken = TokenHelper.GetAppOnlyAccessToken(contextToken.TargetPrincipalName, uriHostWeb.Authority, contextToken.Realm);
            appOnlyAccessTokenString = appOnlyAccessToken.AccessToken;

            // cache state that can be shared across user
            Cache["uriHostWeb"] = uriHostWeb;
            Cache["appOnlyAccessTokenString"] = appOnlyAccessTokenString;

            // cache state that must be tracked on per-user basis
            Session["contextTokenString"] = contextTokenString;
            Session["accessTokenString"] = accessTokenString;

              }

              #region "Incoming Data"

              HtmlTableWriter table1 = new HtmlTableWriter();

              table1.AddRow("Request URL", this.Request.Path);

              foreach (var param in Request.Form.AllKeys) {
            table1.AddRow("Request.Form['" + param + "']", Request.Form[param].ToString());
              }

              foreach (var param in Request.QueryString.AllKeys) {
            table1.AddRow("Request.QueryString['" + param + "']", Request.QueryString[param].ToString());
              }

              placeholderIncomingData.Controls.Add(new LiteralControl(table1.ToString()));

              #endregion

              #region "Context Token"

              HtmlTableWriter table2 = new HtmlTableWriter();
              table2.AddRow("Context Token (RAW)", contextTokenString);

              if (contextToken != null) {
            table2.AddRow("Content Token (JSON)", contextToken.ToString());
            table2.AddRow("Cache Key", contextToken.CacheKey);
            table2.AddRow("Realm", contextToken.Realm);
            table2.AddRow("Security Token Service Uri", contextToken.SecurityTokenServiceUri);
            table2.AddRow("Target Principal Name", contextToken.TargetPrincipalName);

            table2.AddRow("Valid From", contextToken.ValidFrom.ToString());
            table2.AddRow("Valid To", contextToken.ValidTo.ToString());
            table2.AddRow("Refresh Token", contextToken.RefreshToken);

            placeholderContextToken.Controls.Add(new LiteralControl(table2.ToString()));
              }

              #endregion

              #region "Access Token"
              if (contextToken != null) {

            HtmlTableWriter table3 = new HtmlTableWriter();
            // create OAuth access token
            table3.AddRow("Access Token", accessTokenString);
            table3.AddRow("Access Token (JSON)", accessToken.ToString());
            table3.AddRow("Resource", accessToken.Message["resource"]);
            table3.AddRow("NotBefore", accessToken.NotBefore.ToString());
            table3.AddRow("ExpiresOn", accessToken.ExpiresOn.ToString());
            table3.AddRow("ExpiresIn", TimeSpan.FromSeconds(Convert.ToInt32(accessToken.ExpiresIn)).TotalHours.ToString("0.0") + " hours");

            foreach (var msg in accessToken.Message) {
              //table3.AddRow("Message - " + msg.Key, msg.Value);
            }

            placeholderAccessToken.Controls.Add(new LiteralControl(table3.ToString()));
              }
              #endregion

              #region "App-only Access Token"
              if (contextToken != null) {
            appOnlyAccessToken = TokenHelper.GetAppOnlyAccessToken(contextToken.TargetPrincipalName, uriHostWeb.Authority, contextToken.Realm);
            appOnlyAccessTokenString = appOnlyAccessToken.AccessToken;

            HtmlTableWriter table4 = new HtmlTableWriter();
            // create OAuth access token
            table4.AddRow("App-only Access Token", appOnlyAccessTokenString);
            table4.AddRow("App-only Access Token (JSON)", appOnlyAccessToken.ToString());
            table4.AddRow("Resource", appOnlyAccessToken.Message["resource"]);
            table4.AddRow("NotBefore", appOnlyAccessToken.NotBefore.ToString());
            table4.AddRow("ExpiresOn", appOnlyAccessToken.ExpiresOn.ToString());
            table4.AddRow("ExpiresIn", TimeSpan.FromSeconds(Convert.ToInt32(appOnlyAccessToken.ExpiresIn)).TotalHours.ToString("0.0") + " hours");

            foreach (var msg in appOnlyAccessToken.Message) {
              table4.AddRow("Message - " + msg.Key, msg.Value);
            }

            placeholderAppOnlyAccessToken.Controls.Add(new LiteralControl(table4.ToString()));
              }

              #endregion
        }
コード例 #11
0
        protected void Page_Load(object sender, EventArgs e)
        {
            TokenHelper.TrustAllCertificates();

            string contextTokenString = TokenHelper.GetContextTokenFromRequest(Request);

            if (contextTokenString != null)
            {
                SharePointContextToken contextToken =
                    TokenHelper.ReadAndValidateContextToken(contextTokenString, Request.Url.Authority);

                Response.Write("<h2>Valid context token found</h2>");
                Response.Write("<p>" + contextToken.ToString() + "</p>");
                Response.Flush();

                Uri    sharepointUrl = new Uri(Request.QueryString["SPHostUrl"]);
                string accessToken   =
                    TokenHelper.GetAccessToken(contextToken, sharepointUrl.Authority).AccessToken;

                Response.Write("<h2>Valid access token retrieved</h2>");
                Response.Write("<p>" + accessToken + "</p>");
                Response.Flush();

                //string appOnlyAccessToken = TokenHelper.GetAppOnlyAccessToken(contextToken.TargetPrincipalName, sharepointUrl.Authority, contextToken.Realm).AccessToken;

                ClientContext clientContext =
                    TokenHelper.GetClientContextWithAccessToken(
                        sharepointUrl.ToString(), accessToken);

                //Load the properties for the web object.
                Web web = clientContext.Web;
                clientContext.Load(web);
                clientContext.ExecuteQuery();

                //clientContext.Load(clientContext.Web);

                //clientContext.ExecuteQuery();

                //Response.Write("<h2>Web title retrieved</h2>");
                //Response.Write("<p>" + clientContext.Web.Title + "</p>");
                //Response.Flush();


                string appOnlyAccessToken = TokenHelper.GetAppOnlyAccessToken(contextToken.TargetPrincipalName, sharepointUrl.Authority, contextToken.Realm).AccessToken;


                Response.Write("<h2>Valid app-only access token retrieved</h2>");
                Response.Write("<p>" + appOnlyAccessToken + "</p>");
                Response.Flush();

                clientContext.Dispose();

                clientContext = TokenHelper.GetClientContextWithAccessToken(sharepointUrl.ToString(), appOnlyAccessToken);

                clientContext.Load(clientContext.Web);
                clientContext.ExecuteQuery();

                Response.Write("<h2>Web title retrieved with an app only token</h2>");
                Response.Write("<p>" + clientContext.Web.Title + "</p>");

                clientContext.Dispose();
            }
        }
コード例 #12
0
        protected void Page_Load(object sender, EventArgs e)
        {
            TokenHelper.TrustAllCertificates();

            string contextTokenString = TokenHelper.GetContextTokenFromRequest(Request);

            if (contextTokenString != null)
            {
                SharePointContextToken contextToken =
                    TokenHelper.ReadAndValidateContextToken(contextTokenString, Request.Url.Authority);

                Response.Write("<h2>Valid context token found</h2>");
                Response.Write("<p>" + contextToken.ToString() + "</p>");
                Response.Flush();
                Uri    sharepointUrl = new Uri(Request.QueryString["SPHostUrl"]);
                string accessToken   =
                    TokenHelper.GetAccessToken(contextToken, sharepointUrl.Authority).AccessToken;

                Response.Write("<h2>Valid access token retrieved</h2>");
                Response.Write("<p>" + accessToken + "</p>");
                Response.Flush();


                ClientContext clientContext =
                    TokenHelper.GetClientContextWithAccessToken(
                        sharepointUrl.ToString(), accessToken);
                clientContext.Load(clientContext.Web);
                clientContext.ExecuteQuery();

                Response.Write("<h2>Web title retrieved</h2>");
                Response.Write("<p>" + clientContext.Web.Title + "</p>");
                Response.Flush();


                HttpWebRequest request =
                    (HttpWebRequest)HttpWebRequest.Create(sharepointUrl.ToString() + "_api/Web/title");
                request.Headers.Add("Authorization", "Bearer " + accessToken);
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                StreamReader    reader   = new StreamReader(response.GetResponseStream());

                Response.Write("<h2>Web title retrieved using REST</h2>");
                Response.Write("<p>" + reader.ReadToEnd() + "</p>");
                Response.Flush();


                //Load the properties for the web object
                Web web = clientContext.Web;
                clientContext.Load(web);
                clientContext.ExecuteQuery();

                //Load the lists from the web object
                ListCollection lists = web.Lists;
                clientContext.Load <ListCollection>(lists);
                clientContext.ExecuteQuery();

                //print out the information
                clientContext.Load(web.CurrentUser);
                clientContext.ExecuteQuery();
                string str = clientContext.Web.CurrentUser.LoginName + "<br>";

                UserCollection users = web.SiteUsers;
                clientContext.Load <UserCollection>(users);
                clientContext.ExecuteQuery();

                foreach (User siteUser in users)
                {
                    str += "SiteUser: "******"<br>";
                }

                foreach (string key in Request.QueryString.AllKeys)
                {
                    str += key + " = " + Request.QueryString[key] + "<br>";
                }

                foreach (List list in lists)
                {
                    str += "List: " + list.Title + "<br>";
                }
                Response.Write(str);

                Response.Write("<p>Web title retrieved: " + clientContext.Web.Title + "</p>");
                Response.Flush();
            }
        }
コード例 #13
0
        protected void Page_Load(object sender, EventArgs e)
        {
            // This is the original code generated by the template.
            //var contextToken = TokenHelper.GetContextTokenFromRequest(Page.Request);
            //var hostWeb = Page.Request["SPHostUrl"];

            //using (var clientContext = TokenHelper.GetClientContextWithContextToken(hostWeb, contextToken, Request.Url.Authority))
            //{
            //    clientContext.Load(clientContext.Web, web => web.Title);
            //    clientContext.ExecuteQuery();
            //    Response.Write(clientContext.Web.Title);
            //}

            // Get app info from web.config
            string clientID = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientId"))
                                ? WebConfigurationManager.AppSettings.Get("HostedAppName")
                                : WebConfigurationManager.AppSettings.Get("ClientId");
            string clientSecret = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientSecret"))
                                ? WebConfigurationManager.AppSettings.Get("HostedAppSigningKey")
                                : WebConfigurationManager.AppSettings.Get("ClientSecret");

            // Get values from Page.Request
            string reqAuthority     = Request.Url.Authority;
            string hostWeb          = Page.Request["SPHostUrl"];
            string hostWebAuthority = (new Uri(hostWeb)).Authority;

            // Get Context Token
            string contextTokenStr = TokenHelper.GetContextTokenFromRequest(Request);
            SharePointContextToken contextToken =
                TokenHelper.ReadAndValidateContextToken(contextTokenStr, reqAuthority);

            // Read data from the Context Token
            string targetPrincipalName = contextToken.TargetPrincipalName;
            string cacheKey            = contextToken.CacheKey;
            string refreshTokenStr     = contextToken.RefreshToken;
            string realm = contextToken.Realm;

            // Create principal and client strings
            string targetPrincipal = GetFormattedPrincipal(targetPrincipalName, hostWebAuthority, realm);
            string appPrincipal    = GetFormattedPrincipal(clientID, null, realm);

            // Request an access token from ACS
            string stsUrl = TokenHelper.AcsMetadataParser.GetStsUrl(realm);
            OAuth2AccessTokenRequest oauth2Request =
                OAuth2MessageFactory.CreateAccessTokenRequestWithRefreshToken(
                    appPrincipal, clientSecret, refreshTokenStr, targetPrincipal);
            OAuth2S2SClient           client         = new OAuth2S2SClient();
            OAuth2AccessTokenResponse oauth2Response = client.Issue(stsUrl, oauth2Request) as OAuth2AccessTokenResponse;
            string accessTokenStr = oauth2Response.AccessToken;

            // Build the CSOM context with the access token
            ClientContext clientContext = TokenHelper.GetClientContextWithAccessToken(hostWeb, accessTokenStr);

            clientContext.Load(clientContext.Web, web => web.Title);
            clientContext.ExecuteQuery();

            // Dump values to the page
            DataTable dt = new DataTable();

            dt.Columns.Add("Name");
            dt.Columns.Add("Value");

            dt.Rows.Add("QueryString", Request.QueryString);
            dt.Rows.Add("clientID", clientID);
            dt.Rows.Add("clientSecret", clientSecret);
            dt.Rows.Add("hostWeb", hostWeb);
            dt.Rows.Add("contextTokenStr", contextTokenStr);
            dt.Rows.Add("contextToken", contextToken);
            dt.Rows.Add("targetPrincipalName", targetPrincipalName);
            dt.Rows.Add("cacheKey", cacheKey);
            dt.Rows.Add("refreshTokenStr", refreshTokenStr);
            dt.Rows.Add("realm", realm);
            dt.Rows.Add("targetPrincipal", targetPrincipal);
            dt.Rows.Add("appPrincipal", appPrincipal);
            dt.Rows.Add("stsUrl", stsUrl);
            dt.Rows.Add("oauth2Request", oauth2Request);
            dt.Rows.Add("client", client);
            dt.Rows.Add("oauth2Response", oauth2Response);
            dt.Rows.Add("accessTokenStr", accessTokenStr);
            dt.Rows.Add("Host Web Title", clientContext.Web.Title);

            grd.DataSource = dt;
            grd.DataBind();
        }
コード例 #14
0
        /// <summary>
        /// Retrieves an access token from ACS to call the source of the specified context token at the specified 
        /// targetHost. The targetHost must be registered for principal the that sent the context token.
        /// </summary>
        /// <param name="contextToken">Context token issued by the intended access token audience</param>
        /// <param name="targetHost">Url authority of the target principal</param>
        /// <returns>An access token with an audience matching the context token's source</returns>
        public static OAuth2AccessTokenResponse GetAccessToken(SharePointContextToken contextToken, string targetHost)
        {
            string targetPrincipalName = contextToken.TargetPrincipalName;

            // Extract the refreshToken from the context token
            string refreshToken = contextToken.RefreshToken;

            if (String.IsNullOrEmpty(refreshToken))
            {
                return null;
            }

            string realm = Realm ?? contextToken.Realm;

            string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, realm);
            string clientId = GetFormattedPrincipal(ClientId, null, realm);

            OAuth2AccessTokenRequest oauth2Request =
                OAuth2MessageFactory.CreateAccessTokenRequestWithRefreshToken(
                    clientId,
                    ClientSecret,
                    refreshToken,
                    resource);

            // Get token
            OAuth2S2SClient client = new OAuth2S2SClient();
            OAuth2AccessTokenResponse oauth2Response;
            try
            {
                oauth2Response =
                    client.Issue(AcsMetadataParser.GetStsUrl(realm), oauth2Request) as OAuth2AccessTokenResponse;
            }
            catch (WebException wex)
            {
                using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream()))
                {
                    string responseText = sr.ReadToEnd();
                    throw new WebException(wex.Message + " - " + responseText, wex);
                }
            }

            return oauth2Response;
        }
コード例 #15
0
        protected void Page_Load(object sender, EventArgs e)
        {
            TokenHelper.TrustAllCertificates();

            string contextTokenString = TokenHelper.GetContextTokenFromRequest(Request);

            if (contextTokenString != null)
            {
                SharePointContextToken contextToken =
                    TokenHelper.ReadAndValidateContextToken(contextTokenString, Request.Url.Authority);

                Uri    sharepointUrl = new Uri(Request.QueryString["SPHostUrl"]);
                string accessToken   =
                    TokenHelper.GetAccessToken(contextToken, sharepointUrl.Authority).AccessToken;

                Response.Write("<h2>Valid context token retrieved</h2>");
                Response.Write("<p>" + contextToken + "</p>");
                Response.Flush();


                Response.Write("<h2>Valid access token retrieved</h2>");
                Response.Write("<p>" + accessToken + "</p>");
                Response.Flush();

                //Create a namespace manager for parsing the ATOM XML returned by the queries.
                XmlNamespaceManager xmlnspm = new XmlNamespaceManager(new NameTable());
                //Add the pertinent namespaces to the namespace manager.
                xmlnspm.AddNamespace("atom", "http://www.w3.org/2005/Atom");
                xmlnspm.AddNamespace("d", "http://schemas.microsoft.com/ado/2007/08/dataservices");
                xmlnspm.AddNamespace("m", "http://schemas.microsoft.com/ado/2007/08/dataservices/metadata");

                //Request the name of the site.
                HttpWebRequest request =
                    (HttpWebRequest)HttpWebRequest.Create(sharepointUrl.ToString() + "_api/Web/title");
                request.Method      = "GET";
                request.Accept      = "application/atom+xml";
                request.ContentType = "application/atom+xml;type=entry";
                request.Headers.Add("Authorization", "Bearer " + accessToken);

                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                StreamReader    reader   = new StreamReader(response.GetResponseStream());

                var titleXml = new XmlDocument();
                titleXml.LoadXml(reader.ReadToEnd());
                var webTitle = titleXml.SelectSingleNode("d:Title", xmlnspm);
                siteName = webTitle.InnerXml;

                Response.Write("<h2>Site name retrieved using REST</h2>");
                Response.Write("<p>" + siteName + "</p>");
                Response.Flush();

                //Request information about the current user.
                HttpWebRequest currentUserRequest =
                    (HttpWebRequest)HttpWebRequest.Create(sharepointUrl.ToString() + "_api/Web/currentUser");
                currentUserRequest.Method      = "GET";
                currentUserRequest.Accept      = "application/atom+xml";
                currentUserRequest.ContentType = "application/atom+xml;type=entry";
                currentUserRequest.Headers.Add("Authorization", "Bearer " + accessToken);

                HttpWebResponse currentUserResponse = (HttpWebResponse)currentUserRequest.GetResponse();
                StreamReader    currentUserReader   = new StreamReader(currentUserResponse.GetResponseStream());

                var currentUserXml = new XmlDocument();
                currentUserXml.LoadXml(currentUserReader.ReadToEnd());
                var currentUserTitle = currentUserXml.SelectSingleNode("//atom:entry/atom:content/m:properties/d:LoginName", xmlnspm);
                currentUser = currentUserTitle.InnerXml;

                Response.Write("<h2>Current user</h2>");
                Response.Write("<p>" + currentUser + "</p>");
                Response.Flush();

                string appOnlyAccessToken = TokenHelper.GetAppOnlyAccessToken(contextToken.TargetPrincipalName, sharepointUrl.Authority, contextToken.Realm).AccessToken;

                Response.Write("<h2>Valid app-only access token retrieved</h2>");
                Response.Write("<p>" + appOnlyAccessToken + "</p>");
                Response.Flush();

                //Request information about the welcome page of the root folder.
                HttpWebRequest rootFolderRequest =
                    (HttpWebRequest)HttpWebRequest.Create(sharepointUrl.ToString() + "_api/Web/RootFolder");
                rootFolderRequest.Method      = "GET";
                rootFolderRequest.Accept      = "application/atom+xml";
                rootFolderRequest.ContentType = "application/atom+xml;type=entry";
                rootFolderRequest.Headers.Add("Authorization", "Bearer " + appOnlyAccessToken);

                HttpWebResponse rootFolderResponse = (HttpWebResponse)rootFolderRequest.GetResponse();
                StreamReader    rootFolderReader   = new StreamReader(rootFolderResponse.GetResponseStream());

                var welcomePageXml = new XmlDocument();
                welcomePageXml.LoadXml(rootFolderReader.ReadToEnd());

                var rootFolderTitle = welcomePageXml.SelectSingleNode("//atom:entry/atom:content/m:properties/d:WelcomePage", xmlnspm);
                rootFolder = rootFolderTitle.InnerXml;

                Response.Write("<h2>Root folder welcome page retrieved using REST</h2>");
                Response.Write("<p>" + rootFolder + "</p>");
                Response.Flush();
            }
        }
コード例 #16
0
ファイル: Default.aspx.cs プロジェクト: erkindunya/CBD365
        protected void Page_Load(object sender, EventArgs e)
        {
            uriHostWeb = new Uri(Request.QueryString["SPHostUrl"]);

            contextTokenString = TokenHelper.GetContextTokenFromRequest(Request);

            if (contextTokenString != null)
            {
                contextToken = TokenHelper.ReadAndValidateContextToken(contextTokenString, Request.Url.Authority);

                targetPrincipalName = contextToken.TargetPrincipalName;
                realm                    = contextToken.Realm;
                accessToken              = TokenHelper.GetAccessToken(contextToken, uriHostWeb.Authority);
                accessTokenString        = TokenHelper.GetAccessToken(contextToken, uriHostWeb.Authority).AccessToken;
                appOnlyAccessToken       = TokenHelper.GetAppOnlyAccessToken(contextToken.TargetPrincipalName, uriHostWeb.Authority, contextToken.Realm);
                appOnlyAccessTokenString = appOnlyAccessToken.AccessToken;

                // cache state that can be shared across user
                Cache["uriHostWeb"] = uriHostWeb;
                Cache["appOnlyAccessTokenString"] = appOnlyAccessTokenString;

                // cache state that must be tracked on per-user basis
                Session["contextTokenString"] = contextTokenString;
                Session["accessTokenString"]  = accessTokenString;
            }

            #region "Incoming Data"

            HtmlTableWriter table1 = new HtmlTableWriter();

            table1.AddRow("Request URL", this.Request.Path);

            foreach (var param in Request.Form.AllKeys)
            {
                table1.AddRow("Request.Form['" + param + "']", Request.Form[param].ToString());
            }

            foreach (var param in Request.QueryString.AllKeys)
            {
                table1.AddRow("Request.QueryString['" + param + "']", Request.QueryString[param].ToString());
            }

            placeholderIncomingData.Controls.Add(new LiteralControl(table1.ToString()));

            #endregion

            #region "Context Token"

            HtmlTableWriter table2 = new HtmlTableWriter();
            table2.AddRow("Context Token (RAW)", contextTokenString);

            if (contextToken != null)
            {
                table2.AddRow("Content Token (JSON)", contextToken.ToString());
                table2.AddRow("Cache Key", contextToken.CacheKey);
                table2.AddRow("Realm", contextToken.Realm);
                table2.AddRow("Security Token Service Uri", contextToken.SecurityTokenServiceUri);
                table2.AddRow("Target Principal Name", contextToken.TargetPrincipalName);

                table2.AddRow("Valid From", contextToken.ValidFrom.ToString());
                table2.AddRow("Valid To", contextToken.ValidTo.ToString());
                table2.AddRow("Refresh Token", contextToken.RefreshToken);

                placeholderContextToken.Controls.Add(new LiteralControl(table2.ToString()));
            }

            #endregion

            #region "Access Token"
            if (contextToken != null)
            {
                HtmlTableWriter table3 = new HtmlTableWriter();
                // create OAuth access token
                table3.AddRow("Access Token", accessTokenString);
                table3.AddRow("Access Token (JSON)", accessToken.ToString());
                table3.AddRow("Resource", accessToken.Message["resource"]);
                table3.AddRow("NotBefore", accessToken.NotBefore.ToString());
                table3.AddRow("ExpiresOn", accessToken.ExpiresOn.ToString());
                table3.AddRow("ExpiresIn", TimeSpan.FromSeconds(Convert.ToInt32(accessToken.ExpiresIn)).TotalHours.ToString("0.0") + " hours");

                foreach (var msg in accessToken.Message)
                {
                    //table3.AddRow("Message - " + msg.Key, msg.Value);
                }

                placeholderAccessToken.Controls.Add(new LiteralControl(table3.ToString()));
            }
            #endregion

            #region "App-only Access Token"
            if (contextToken != null)
            {
                appOnlyAccessToken       = TokenHelper.GetAppOnlyAccessToken(contextToken.TargetPrincipalName, uriHostWeb.Authority, contextToken.Realm);
                appOnlyAccessTokenString = appOnlyAccessToken.AccessToken;

                HtmlTableWriter table4 = new HtmlTableWriter();
                // create OAuth access token
                table4.AddRow("App-only Access Token", appOnlyAccessTokenString);
                table4.AddRow("App-only Access Token (JSON)", appOnlyAccessToken.ToString());
                table4.AddRow("Resource", appOnlyAccessToken.Message["resource"]);
                table4.AddRow("NotBefore", appOnlyAccessToken.NotBefore.ToString());
                table4.AddRow("ExpiresOn", appOnlyAccessToken.ExpiresOn.ToString());
                table4.AddRow("ExpiresIn", TimeSpan.FromSeconds(Convert.ToInt32(appOnlyAccessToken.ExpiresIn)).TotalHours.ToString("0.0") + " hours");

                foreach (var msg in appOnlyAccessToken.Message)
                {
                    table4.AddRow("Message - " + msg.Key, msg.Value);
                }

                placeholderAppOnlyAccessToken.Controls.Add(new LiteralControl(table4.ToString()));
            }

            #endregion
        }