Пример #1
0
        /// <summary>
        /// Uses the specified refresh token to retrieve an access token from ACS to call the specified principal
        /// at the specified targetHost. The targetHost must be registered for target principal.  If specified realm is
        /// null, the "Realm" setting in web.config will be used instead.
        /// </summary>
        /// <param name="refreshToken">Refresh token to exchange for access token</param>
        /// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param>
        /// <param name="targetHost">Url authority of the target principal</param>
        /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
        /// <returns>An access token with an audience of the target principal</returns>
        public OAuth2AccessTokenResponse GetAccessToken(
            string refreshToken,
            string targetPrincipalName,
            string targetHost,
            string targetRealm)
        {
            if (targetRealm == null)
            {
                targetRealm = Realm;
            }

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

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

            // Get token
            OAuth2S2SClient           client = new OAuth2S2SClient();
            OAuth2AccessTokenResponse oauth2Response;

            try {
                oauth2Response =
                    client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), 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);
        }
Пример #2
0
        /// <summary>
        /// Uses the specified refresh token to retrieve an access token from ACS to call the specified principal
        /// at the specified targetHost. The targetHost must be registered for target principal.  If specified realm is
        /// null, the "Realm" setting in web.config will be used instead.
        /// </summary>
        /// <param name="refreshToken">Refresh token to exchange for access token</param>
        /// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param>
        /// <param name="targetHost">Url authority of the target principal</param>
        /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
        /// <returns>An access token with an audience of the target principal</returns>
        internal static OAuth2AccessTokenResponse GetAccessToken(string refreshToken, string targetPrincipalName, string targetHost, string targetRealm)
        {
            if (targetRealm == null)
            {
                targetRealm = WebConfigAddInDataRescue.Realm;
            }

            string resource = ProcessTokenStrings.GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm);
            string clientId = ProcessTokenStrings.GetFormattedPrincipal(WebConfigAddInDataRescue.ClientId, null, targetRealm);

            OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory
                                                     .CreateAccessTokenRequestWithRefreshToken(clientId, WebConfigAddInDataRescue.ClientSecret, refreshToken, resource);
            OAuth2S2SClient           client = new OAuth2S2SClient();
            OAuth2AccessTokenResponse oauth2Response;

            try
            {
                oauth2Response =
                    client.Issue(DocumentMetadataOp.GetStsUrl(targetRealm), 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);
        }
        /// <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>
        /// <param name="clientId">ACS client id</param>
        /// <param name="clientSecret">ACS client secret</param>
        /// <returns>An access token with an audience matching the context token's source</returns>
        public static OAuth2AccessTokenResponse GetACSAccessTokens(SharePointContextToken contextToken, string targetHost, string clientId, string clientSecret)
        {
            string targetPrincipalName = contextToken.TargetPrincipalName;

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

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

            string realm = contextToken.Realm;

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

            OAuth2AccessTokenRequest oauth2Request =
                OAuth2MessageFactory.CreateAccessTokenRequestWithRefreshToken(
                    formattedPrincipal,
                    clientSecret,
                    refreshToken,
                    resource);

            // Get token
            OAuth2S2SClient           client = new OAuth2S2SClient();
            OAuth2AccessTokenResponse oauth2Response;

            try
            {
                oauth2Response =
                    client.Issue(GetStsUrl(realm), oauth2Request) as OAuth2AccessTokenResponse;
            }
            catch (WebException wex)
            {
                if (wex.Response == null)
                {
                    throw;
                }
                var stream = wex.Response.GetResponseStream();
                if (stream == null)
                {
                    throw;
                }
                using (StreamReader sr = new StreamReader(stream))
                {
                    string responseText = sr.ReadToEnd();
                    throw new WebException(wex.Message + " - " + responseText, wex);
                }
            }

            return(oauth2Response);
        }
Пример #4
0
        protected void Page_Load(object sender, EventArgs e)
        {
            // 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);
            //    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();
        }