示例#1
0
        /// <summary>
        /// Uses the specified authorization code 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="authorizationCode">Authorization code 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>
        /// <param name="redirectUri">Redirect URI registerd for this app</param>
        /// <returns>An access token with an audience of the target principal</returns>
        public static OAuth2AccessTokenResponse GetAccessToken(
            string authorizationCode,
            string targetPrincipalName,
            string targetHost,
            string targetRealm,
            Uri redirectUri)
        {
            if (targetRealm == null)
            {
                targetRealm = Realm;
            }

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

            // Create request for token. The RedirectUri is null here.  This will fail if redirect uri is registered
            OAuth2AccessTokenRequest oauth2Request =
                OAuth2MessageFactory.CreateAccessTokenRequestWithAuthorizationCode(
                    clientId,
                    ClientSecret,
                    authorizationCode,
                    redirectUri,
                    resource);

            // Get token
            OAuth2S2SClient client         = new OAuth2S2SClient();
            var             oauth2Response = client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse;

            return(oauth2Response);
        }
示例#2
0
        /// <summary>
        /// Uses the specified authorization code 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="authorizationCode">Authorization code 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>
        /// <param name="redirectUri">Redirect URI registered for this add-in</param>
        /// <returns>An access token with an audience of the target principal</returns>
        internal static OAuth2AccessTokenResponse GetAccessToken(string authorizationCode, string targetPrincipalName, string targetHost, string targetRealm, Uri redirectUri)
        {
            if (targetRealm == null)
            {
                targetRealm = WebConfigAddInDataRescue.Realm;
            }
            string resource = ProcessTokenStrings.GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm);
            string clientId = ProcessTokenStrings.GetFormattedPrincipal(WebConfigAddInDataRescue.ClientId, null, targetRealm);

            // Create request for token. The RedirectUri is null here.  This will fail if redirect uri is registered
            OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory
                                                     .CreateAccessTokenRequestWithAuthorizationCode(clientId, WebConfigAddInDataRescue.ClientSecret, authorizationCode, redirectUri, resource);

            // Get token
            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 app-only 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="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 GetAppOnlyAccessToken(
            string targetPrincipalName,
            string targetHost,
            string targetRealm = null)
        {
            targetRealm ??= this.Options.Realm;

            string resource          = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm);
            string clientIdPrincipal = GetFormattedPrincipal(this.Options.ClientId, this.Options.HostedAppHostName, targetRealm);

            var oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithClientCredentials(clientIdPrincipal, this.Options.ClientSecret, resource);

            oauth2Request.Resource = resource;

            try
            {
                // Get token
                var client = new OAuth2S2SClient();
                return(client.Issue(GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse);
            }
            catch (WebException wex) when(wex.Response != null)
            {
                using (var sr = new StreamReader(wex.Response.GetResponseStream()))
                {
                    string responseText = sr.ReadToEnd();
                    throw new WebException(wex.Message + " - " + responseText, wex);
                }
            }
        }
示例#4
0
        /// <summary>
        /// Retrieves an app-only 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="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 static OAuth2AccessTokenResponse GetAppOnlyAccessToken(
            string targetPrincipalName,
            string targetHost,
            string targetRealm)
        {
            if (targetRealm == null)
            {
                targetRealm = Realm;
            }

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

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

            oauth2Request.Resource = 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);
        }
示例#5
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);
        }
示例#6
0
        public OAuth2AccessTokenResponse GetAccessToken(string authCode)
        {
            var realm      = GetRealmFromTargetUrl(Office365Url);
            var targetHost = new Uri(Office365Url).Authority;
            var resource   = GetFormattedPrincipal(TargetPrincipalName, targetHost, realm);
            var clientId   = GetFormattedPrincipal(ConsumerKey, null, realm);

            var oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithAuthorizationCode(
                clientId,
                ConsumerSecret,
                Globals.UrlEncode(authCode),
                resource);

            oauth2Request.RedirectUri = CallbackUrl;

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

            return(null);
        }
        /// <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);
        }
        /// <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 static 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 (RequestFailedException)
            {
                if (!string.IsNullOrEmpty(SecondaryClientSecret))
                {
                    oauth2Request  = OAuth2MessageFactory.CreateAccessTokenRequestWithRefreshToken(clientId, SecondaryClientSecret, refreshToken, resource);
                    oauth2Response =
                        client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse;
                }
                else
                {
                    throw;
                }
            }
            catch (WebException wex)
            {
                using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream()))
                {
                    string responseText = sr.ReadToEnd();
                    throw new WebException(wex.Message + " - " + responseText, wex);
                }
            }

            return(oauth2Response);
        }
示例#9
0
        private string IssueTenantAccessToken(string tenantId)
        {
            string text  = string.Format("{0}@{1}", this.settings.PartnerId, tenantId);
            string arg   = string.Format("{0}/{1}", this.settings.AcsId, this.settings.AcsUrl.Authority);
            string text2 = string.Format("{0}@{1}", arg, tenantId);
            JsonWebSecurityToken jsonWebSecurityToken = new JsonWebSecurityToken(text, text2, DateTime.UtcNow, DateTime.UtcNow.AddDays(1.0), Enumerable.Empty <JsonWebTokenClaim>(), CertificateStore.GetSigningCredentials(this.settings.CertificateSubject));
            string text3 = string.Format("{0}/{1}@{2}", this.settings.ServiceId, this.settings.ServiceHostName, tenantId);
            OAuth2AccessTokenRequest oauth2AccessTokenRequest = OAuth2MessageFactory.CreateAccessTokenRequestWithAssertion(jsonWebSecurityToken, text3);

            oauth2AccessTokenRequest.Scope = text3;
            OAuth2S2SClient           oauth2S2SClient           = new OAuth2S2SClient();
            OAuth2AccessTokenResponse oauth2AccessTokenResponse = (OAuth2AccessTokenResponse)oauth2S2SClient.Issue(this.settings.AcsUrl.AbsoluteUri, oauth2AccessTokenRequest);

            return(oauth2AccessTokenResponse.AccessToken);
        }
        /// <summary>
        /// 指定された認証コードを使用し、ACS からアクセス トークンを取得して指定された targetHost で指定されたプリンシパルを
        /// 呼び出します。targetHost は、ターゲット プリンシパルに登録されている必要があります。指定されたレルムが
        /// null の場合、web.config の "Realm" 設定が代わりに使用されます。
        /// </summary>
        /// <param name="authorizationCode">アクセス トークンを交換するための認証コード</param>
        /// <param name="targetPrincipalName">アクセス トークンを取得するターゲット プリンシパルの名前</param>
        /// <param name="targetHost">ターゲット プリンシパルの URL 機関</param>
        /// <param name="targetRealm">アクセス トークンの nameid と対象ユーザーに使用するレルム</param>
        /// <param name="redirectUri">このアドインに登録されているリダイレクト URI</param>
        /// <returns>ターゲット プリンシパルの対象ユーザーを持つアクセス トークン</returns>
        public static OAuth2AccessTokenResponse GetAccessToken(
            string authorizationCode,
            string targetPrincipalName,
            string targetHost,
            string targetRealm,
            Uri redirectUri)
        {
            if (targetRealm == null)
            {
                targetRealm = Realm;
            }

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

            // トークンの要求を作成します。ここでは、RedirectUri は null です。リダイレクト URI が登録されている場合は失敗します
            OAuth2AccessTokenRequest oauth2Request =
                OAuth2MessageFactory.CreateAccessTokenRequestWithAuthorizationCode(
                    clientId,
                    ClientSecret,
                    authorizationCode,
                    redirectUri,
                    resource);

            // トークンを取得します
            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);
        }
        /// <summary>
        /// Retrieves an app-only 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="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 static OAuth2AccessTokenResponse GetAppOnlyAccessToken(
            string targetPrincipalName,
            string targetHost,
            string targetRealm)
        {

            if (targetRealm == null)
            {
                targetRealm = Realm;
            }

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

            OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithClientCredentials(clientId, ClientSecret, resource);
            oauth2Request.Resource = 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;
        }
        /// <summary>
        /// Uses the specified authorization code 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="authorizationCode">Authorization code 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>
        /// <param name="redirectUri">Redirect URI registerd for this app</param>
        /// <returns>An access token with an audience of the target principal</returns>
        public static OAuth2AccessTokenResponse GetAccessToken(
            string authorizationCode,
            string targetPrincipalName,
            string targetHost,
            string targetRealm,
            Uri redirectUri)
        {
            if (targetRealm == null)
            {
                targetRealm = Realm;
            }

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

            // Create request for token. The RedirectUri is null here.  This will fail if redirect uri is registered
            OAuth2AccessTokenRequest oauth2Request =
                OAuth2MessageFactory.CreateAccessTokenRequestWithAuthorizationCode(
                    clientId,
                    ClientSecret,
                    authorizationCode,
                    redirectUri,
                    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;
        }
示例#13
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();
        }
        /// <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;
        }
        /// <summary>
        /// Uses the specified authorization code 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="authorizationCode">Authorization code 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>
        /// <param name="redirectUri">Redirect URI registerd for this app</param>
        /// <returns>An access token with an audience of the target principal</returns>
        public static OAuth2AccessTokenResponse GetAccessToken(
            string authorizationCode,
            string targetPrincipalName,
            string targetHost,
            string targetRealm,
            Uri redirectUri)
        {
            if (targetRealm == null)
            {
                targetRealm = Realm;
            }

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

            // Create request for token. The RedirectUri is null here.  This will fail if redirect uri is registered
            OAuth2AccessTokenRequest oauth2Request =
                OAuth2MessageFactory.CreateAccessTokenRequestWithAuthorizationCode(
                    clientId,
                    ClientSecret,
                    authorizationCode,
                    redirectUri,
                    resource);

            // Get token
            OAuth2S2SClient client = new OAuth2S2SClient();
            var oauth2Response = client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse;

            return oauth2Response;
        }
示例#16
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(GetAcsMetadataEndpointUrlWithRealm(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;
        }
示例#17
0
        private static string GetACSToken(OrganizationId tenantID, IConfigurationSession dataSession, ExecutionLog logger, Task task)
        {
            string             result           = null;
            LocalTokenIssuer   localTokenIssuer = new LocalTokenIssuer(tenantID);
            LocalConfiguration configuration    = ConfigProvider.Instance.Configuration;
            Uri    uri           = null;
            string text          = null;
            string applicationId = configuration.ApplicationId;
            string text2         = null;

            foreach (PartnerApplication partnerApplication in configuration.PartnerApplications)
            {
                if (partnerApplication.Enabled && partnerApplication.Name.Contains("Intune"))
                {
                    text2 = partnerApplication.ApplicationIdentifier;
                    break;
                }
            }
            foreach (AuthServer authServer in configuration.AuthServers)
            {
                if (authServer.Enabled && authServer.Type == AuthServerType.MicrosoftACS)
                {
                    text = authServer.IssuerIdentifier;
                    uri  = new Uri(authServer.TokenIssuingEndpoint);
                    break;
                }
            }
            if (localTokenIssuer.SigningCert == null)
            {
                logger.LogOneEntry(task.GetType().Name, string.Empty, ExecutionLog.EventType.Error, "No certificate found.", null);
            }
            if (text2 == null)
            {
                logger.LogOneEntry(task.GetType().Name, string.Empty, ExecutionLog.EventType.Error, "No partnerId found.", null);
            }
            if (uri == null)
            {
                logger.LogOneEntry(task.GetType().Name, string.Empty, ExecutionLog.EventType.Error, "No authorizationEndpoint found.", null);
            }
            if (string.IsNullOrEmpty(text))
            {
                logger.LogOneEntry(task.GetType().Name, string.Empty, ExecutionLog.EventType.Error, "No issuerIdentifier found.", null);
            }
            if (localTokenIssuer.SigningCert != null && text2 != null && uri != null && !string.IsNullOrEmpty(text))
            {
                string arg  = applicationId;
                string arg2 = text2;
                string intuneResourceUrl = UnifiedPolicyConfiguration.GetInstance().GetIntuneResourceUrl(dataSession);
                string arg3      = text;
                string authority = uri.Authority;
                string text3     = string.Format("{0}@{1}", arg, tenantID.ToExternalDirectoryOrganizationId());
                string text4     = string.Format("{0}/{1}@{2}", arg3, authority, tenantID.ToExternalDirectoryOrganizationId());
                string text5     = string.Format("{0}/{1}@{2}", arg2, intuneResourceUrl, tenantID.ToExternalDirectoryOrganizationId());
                X509SigningCredentials   x509SigningCredentials   = new X509SigningCredentials(localTokenIssuer.SigningCert, "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256", "http://www.w3.org/2001/04/xmlenc#sha256");
                JsonWebSecurityToken     jsonWebSecurityToken     = new JsonWebSecurityToken(text3, text4, DateTime.UtcNow, DateTime.UtcNow.AddMinutes(5.0), new List <JsonWebTokenClaim>(), x509SigningCredentials);
                OAuth2AccessTokenRequest oauth2AccessTokenRequest = OAuth2MessageFactory.CreateAccessTokenRequestWithAssertion(jsonWebSecurityToken, text5);
                OAuth2S2SClient          oauth2S2SClient          = new OAuth2S2SClient();
                try
                {
                    OAuth2AccessTokenResponse oauth2AccessTokenResponse = (OAuth2AccessTokenResponse)oauth2S2SClient.Issue(uri.AbsoluteUri, oauth2AccessTokenRequest);
                    if (oauth2AccessTokenResponse != null)
                    {
                        result = "Bearer " + oauth2AccessTokenResponse.AccessToken;
                    }
                }
                catch (RequestFailedException ex)
                {
                    ex.ToString();
                    WebException    ex2             = (WebException)ex.InnerException;
                    HttpWebResponse httpWebResponse = (HttpWebResponse)ex2.Response;
                    Stream          responseStream  = httpWebResponse.GetResponseStream();
                    Encoding        encoding        = Encoding.GetEncoding("utf-8");
                    string          text6           = "Auth service call failed: ";
                    if (responseStream != null)
                    {
                        StreamReader streamReader = new StreamReader(responseStream, encoding);
                        char[]       array        = new char[256];
                        for (int k = streamReader.Read(array, 0, 256); k > 0; k = streamReader.Read(array, 0, 256))
                        {
                            text6 += new string(array, 0, k);
                        }
                    }
                    logger.LogOneEntry(task.GetType().Name, string.Empty, ExecutionLog.EventType.Error, text6, ex);
                }
            }
            return(result);
        }