/// <summary> /// アクセス トークンが有効でない場合は更新します。 /// </summary> /// <param name="accessToken">更新するアクセス トークン。</param> /// <param name="tokenRenewalHandler">トークン更新ハンドラー。</param> private static void RenewAccessTokenIfNeeded(ref Tuple <string, DateTime> accessToken, Func <OAuth2AccessTokenResponse> tokenRenewalHandler) { if (IsAccessTokenValid(accessToken)) { return; } try { OAuth2AccessTokenResponse oAuth2AccessTokenResponse = tokenRenewalHandler(); DateTime expiresOn = oAuth2AccessTokenResponse.ExpiresOn; if ((expiresOn - oAuth2AccessTokenResponse.NotBefore) > AccessTokenLifetimeTolerance) { // アクセス トークンが失効する少し前に更新します // これを使用した SharePoint への呼び出しを正常に完了するための時間を確保できます。 expiresOn -= AccessTokenLifetimeTolerance; } accessToken = Tuple.Create(oAuth2AccessTokenResponse.AccessToken, expiresOn); } catch (WebException) { } }
/// <summary> /// Renews the access token if it is not valid. /// </summary> /// <param name="accessToken">The access token to renew.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> private static void RenewAccessTokenIfNeeded(ref Tuple <string, DateTime> accessToken, Func <OAuth2AccessTokenResponse> tokenRenewalHandler) { if (IsAccessTokenValid(accessToken)) { return; } try { OAuth2AccessTokenResponse oAuth2AccessTokenResponse = tokenRenewalHandler(); DateTime expiresOn = oAuth2AccessTokenResponse.ExpiresOn; if ((expiresOn - oAuth2AccessTokenResponse.NotBefore) > AccessTokenLifetimeTolerance) { // Make the access token get renewed a bit earlier than the time when it expires // so that the calls to SharePoint with it will have enough time to complete successfully. expiresOn -= AccessTokenLifetimeTolerance; } accessToken = Tuple.Create(oAuth2AccessTokenResponse.AccessToken, expiresOn); } catch (WebException) { } }
public static OAuth2AccessTokenResponse Read(string responseString) { OAuth2AccessTokenResponse oAuth2AccessTokenResponse = new OAuth2AccessTokenResponse(); oAuth2AccessTokenResponse.DecodeFromJson(responseString); return(oAuth2AccessTokenResponse); }
protected void Page_Load(object sender, EventArgs e) { /* Build the display when the app loads */ if (!Page.IsPostBack) { try { //Save the context token, access token, and web url in hidden fields hdnContextToken.Value = TokenHelper.GetContextTokenFromRequest(Page.Request); hdnHostWeb.Value = Page.Request["SPHostUrl"]; string remoteWebUrl = Request.Url.Authority; SharePointContextToken spContextToken = TokenHelper.ReadAndValidateContextToken(hdnContextToken.Value, remoteWebUrl); Uri hostWebUri = new Uri(hdnHostWeb.Value); string hostWebAuthority = hostWebUri.Authority; OAuth2AccessTokenResponse accessToken = TokenHelper.GetAccessToken(spContextToken, hostWebAuthority); hdnAccessToken.Value = accessToken.AccessToken; //bind the followers and followed for display followersImages.DataSource = LoadSocialUsers(SocialUserType.Follower, SocialUserFilter.All); followersImages.DataBind(); followedImages.DataSource = LoadSocialUsers(SocialUserType.Followed, SocialUserFilter.All); followedImages.DataBind(); } catch (Exception x) { messages.Text = "Exception in Page_Load: " + x.Message; } } }
private void Listings() { // get content token string from request context string hostWeb = Request.QueryString["SPHostUrl"]; string contextTokenString = TokenHelper.GetContextTokenFromRequest(Request); if (contextTokenString != null) { // get context token as strongly-typed object SharePointContextToken contextToken = TokenHelper.ReadAndValidateContextToken(contextTokenString, hostWeb); // get access token as an strongly-typed object OAuth2AccessTokenResponse accessToken = TokenHelper.GetAccessToken(contextToken, hostWeb); // get access token as string string accessTokenString = accessToken.AccessToken; // get app-only access token as strongly-typed object string targetPrincipalName = contextToken.TargetPrincipalName; string tenancy = contextToken.Realm; OAuth2AccessTokenResponse appOnlyAccessToken = TokenHelper.GetAppOnlyAccessToken(targetPrincipalName, hostWeb, tenancy); // get app-only access token as string string appOnlyAccessTokenString = appOnlyAccessToken.AccessToken; } }
/// <summary> /// Renueva el token de acceso si no es válido. /// </summary> /// <param name="accessToken">Token de acceso para renovar.</param> /// <param name="tokenRenewalHandler">Controlador de renovación del token.</param> private static void RenewAccessTokenIfNeeded(ref Tuple <string, DateTime> accessToken, Func <OAuth2AccessTokenResponse> tokenRenewalHandler) { if (IsAccessTokenValid(accessToken)) { return; } try { OAuth2AccessTokenResponse oAuth2AccessTokenResponse = tokenRenewalHandler(); DateTime expiresOn = oAuth2AccessTokenResponse.ExpiresOn; if ((expiresOn - oAuth2AccessTokenResponse.NotBefore) > AccessTokenLifetimeTolerance) { // Renovar el token de acceso un poco antes de su expiración // para que las llamadas a SharePoint con este tengan tiempo suficiente para completarse correctamente. expiresOn -= AccessTokenLifetimeTolerance; } accessToken = Tuple.Create(oAuth2AccessTokenResponse.AccessToken, expiresOn); } catch (WebException) { } }
static void AuthorizeGoogleAccess_Using_JWT() { Console.WriteLine("Loading certificate from " + JWT_CertificatePath); // Load certificate from file and get a crypto service provider for SHA256 signing X509Certificate2 certificate = new X509Certificate2(JWT_CertificatePath, "notasecret", X509KeyStorageFlags.Exportable); using (RSACryptoServiceProvider cp = (RSACryptoServiceProvider)certificate.PrivateKey) { // Create new crypto service provider that supports SHA256 (and don't ask me why the first one doesn't) CspParameters cspParam = new CspParameters { KeyContainerName = cp.CspKeyContainerInfo.KeyContainerName, KeyNumber = cp.CspKeyContainerInfo.KeyNumber == KeyNumber.Exchange ? 1 : 2 }; using (var aes_csp = new RSACryptoServiceProvider(cspParam) { PersistKeyInCsp = false }) { // Parameters for JWT creation AssertionArgs args = new AssertionArgs { Audience = TokenEndpointUrl, Issuer = JWT_Issuer, Scope = Scope }; Console.WriteLine("Authorizing with Google"); OAuth2AccessTokenResponse token = Session.OAuth2_GetAccessTokenFromJWT_RSASHA256(aes_csp, args); } } }
/// <summary> /// Creates a ClientContext token for the incoming WebAPI request. This is done by /// - looking up the servicesToken /// - extracting the cacheKey /// - get the AccessToken from cache. If the AccessToken is expired a new one is requested using the refresh token /// - creation of a ClientContext object based on the AccessToken /// </summary> /// <param name="httpControllerContext">Information about the HTTP request that reached the WebAPI controller</param> /// <returns>A valid ClientContext object</returns> public static ClientContext GetClientContext(HttpControllerContext httpControllerContext) { if (httpControllerContext == null) { throw new ArgumentNullException("httpControllerContext"); } string cacheKey = GetCacheKeyValue(httpControllerContext); if (!String.IsNullOrEmpty(cacheKey)) { WebAPIContexCacheItem cacheItem = WebAPIContextCache.Instance.Get(cacheKey); //request a new access token from ACS whenever our current access token will expire in less than 1 hour if (cacheItem.AccessToken.ExpiresOn < (DateTime.Now.AddHours(-1))) { Uri targetUri = new Uri(cacheItem.SharePointServiceContext.HostWebUrl); OAuth2AccessTokenResponse accessToken = TokenHelper.GetAccessToken(cacheItem.RefreshToken, TokenHelper.SharePointPrincipal, targetUri.Authority, TokenHelper.GetRealmFromTargetUrl(targetUri)); cacheItem.AccessToken = accessToken; //update the cache WebAPIContextCache.Instance.Put(cacheKey, cacheItem); Log.Info(CoreResources.Services_TokenRefreshed, cacheKey, cacheItem.SharePointServiceContext.HostWebUrl); } return(TokenHelper.GetClientContextWithAccessToken(cacheItem.SharePointServiceContext.HostWebUrl, cacheItem.AccessToken.AccessToken)); } else { Log.Warning(Constants.LOGGING_SOURCE, CoreResources.Services_CookieWithCachKeyNotFound); throw new Exception("The cookie with the cachekey was not found...nothing can be retrieved from cache, so no clientcontext can be created."); } }
static void AuthorizeGoogleAccess_Using_AuthorizationCodeGrantWithRedirect() { // Get temporary credentials from Google (authorization code) and use it for initial URL Uri authorizationUrl = Session.OAuth2_GetAuthorizationRequestUrl(Scope); // Ask user to authorize use of the request token Console.WriteLine("Now opening a browser with autorization info. Please follow instructions there."); Process.Start(authorizationUrl.AbsoluteUri); Console.WriteLine("\nIn the end you will be redirected to 'localhost' which most probably"); Console.WriteLine("does not contain any meaningful content."); Console.WriteLine("\nPlease copy URL from browser and paste it here: "); string redirectUrl = Console.ReadLine(); string authorizationCode = Session.OAuth2_GetAuthorizationCodeFromRedirectUrl(redirectUrl); if (!string.IsNullOrWhiteSpace(redirectUrl)) { // Extract authorization code from redirect URL // Get access credentials from Google OAuth2AccessTokenResponse token = Session.OAuth2_GetAccessTokenFromAuthorizationCode(authorizationCode); } }
public static OAuth2Message CreateFromEncodedResponse(string responseString) { if (responseString.StartsWith("{\"error")) { return(OAuth2ErrorResponse.CreateFromEncodedResponse(responseString)); } return(OAuth2AccessTokenResponse.Read(responseString)); }
public void CanGetAccessTokenUsingNullPassword() { OAuth2AccessTokenResponse token = Session.OAuth2_Configure(GetSettings()) .OAuth2_GetAccessTokenUsingOwnerUsernamePassword(OAuth2TestConstants.UsernameWithEmptyPassword, null); Assert.IsNotNull(token); Assert.That(token.access_token, Is.Not.Null.And.Not.Empty); }
private ClientContext ConnectToSPWeb(OAuth2AccessTokenResponse accessToken) { var ctx = TokenHelper.GetClientContext(SPWebUrl, accessToken.AccessToken); ctx.Load(ctx.Web); ctx.ExecuteQueryRetry(); Log($"Connected to {ctx.Web.Url}"); return(ctx); }
public string GetToken(Uri siteUrl) { // implement simple token caching if (lastToken == null || DateTime.Now.AddMinutes(3) >= lastToken.ExpiresOn) { lastToken = tokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, siteUrl.Authority); } return(lastToken.AccessToken); }
public void CanGetAccessTokenWithAdditionalParametersUsingOAuth2Extensions() { OAuth2AccessTokenResponse token = Session.OAuth2_Configure(GetSettings()) .OAuth2_GetAccessTokenUsingClientCredentials(); Assert.IsNotNull(token); Assert.That(token.access_token, Is.Not.Null.And.Not.Empty); Assert.AreEqual(199, token.expires_in); Assert.AreEqual("Special", (string)token.AllParameters["additional_param"]); }
public void CanUseRefreshTokenToGetNewAccessToken() { // Arrange // Act OAuth2AccessTokenResponse token = Session.OAuth2_Configure(GetSettings()) .OAuth2_RefreshAccessToken("myrefreshtoken"); // Assert Assert.IsNotNull(token); }
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); }
public void CanGetAccessTokenWithAdditionalParametersUsingOAuth2Extensions() { OAuth2AccessTokenResponse token = Session.OAuth2_Configure(GetSettings()) .OAuth2_GetAccessTokenUsingOwnerUsernamePassword( OAuth2TestConstants.Username, OAuth2TestConstants.UserPassword, extraRequestArgs: new Dictionary <string, string> { ["additional"] = "Even more special" }); Assert.IsNotNull(token); Assert.That(token.access_token, Is.Not.Null.And.Not.Empty); Assert.AreEqual(199, token.expires_in); Assert.AreEqual("Even more special", (string)token.AllParameters["additional_param"]); }
static void AuthorizeGoogleAccess_Using_AuthorizationCodeGrantWithPincode() { // Get temporary credentials from Google (authorization code) and use it for initial URL Uri authorizationUrl = Session.OAuth2_GetAuthorizationRequestUrl(Scope); // Ask user to authorize use of the request token Console.WriteLine("Now opening a browser with autorization info. Please follow instructions there."); Process.Start(authorizationUrl.AbsoluteUri); Console.WriteLine("\nPlease enter Google authorization code from browser authorization: "); string authorizationCode = Console.ReadLine(); if (!string.IsNullOrWhiteSpace(authorizationCode)) { // Get access credentials from Google OAuth2AccessTokenResponse token = Session.OAuth2_GetAccessTokenFromAuthorizationCode(authorizationCode); } }
private static void AuthenticateUser() { sessionState.RemoteWebUrl = request.Url.Authority; sessionState.HostWebUrl = request["SPHostUrl"]; sessionState.HostWebDomain = (new Uri(sessionState.HostWebUrl)).Authority; sessionState.HostWebTitle = request.Form["SPSiteTitle"]; string contextTokenString = request.Form["SPAppToken"]; // create SharePoint context token object SharePointContextToken contextToken = TokenHelper.ReadAndValidateContextToken(contextTokenString, sessionState.RemoteWebUrl); // read session state from SharePoint context token object sessionState.HostTenantId = contextToken.Realm; sessionState.TargetResource = contextToken.Audience; sessionState.RefreshToken = contextToken.RefreshToken; sessionState.RefreshTokenExpires = contextToken.ValidTo; // use refresh token to acquire access token response from Azure ACS OAuth2AccessTokenResponse AccessTokenResponse = TokenHelper.GetAccessToken(contextToken, sessionState.HostWebDomain); // Read access token and ExpiresOn value from access token response sessionState.AccessToken = AccessTokenResponse.AccessToken; sessionState.AccessTokenExpires = AccessTokenResponse.ExpiresOn; // call SharePoint REST API to get information about current user string restUri = sessionState.HostWebUrl + "/_api/web/currentUser/"; string jsonCurrentUser = ExecuteGetRequest(restUri, sessionState.AccessToken); // convert json result to strongly-typed C# object SharePointUserResult userResult = JsonConvert.DeserializeObject <SharePointUserResult>(jsonCurrentUser); sessionState.CurrentUserName = userResult.Title; sessionState.CurrentUserEmail = userResult.Email; // write session state out to ASP.NET session object session["SharePointSessionState"] = sessionState; // update UserIsAuthenticated session variable session["UserIsAuthenticated"] = "true"; }
/// <summary> /// Uses the information regarding the requesting app to obtain an access token and caches that using the cachekey. /// This method is called from the Register WebAPI service api. /// </summary> /// <param name="sharePointServiceContext">Object holding information about the requesting SharePoint app</param> public static void AddToCache(WebAPIContext sharePointServiceContext) { if (sharePointServiceContext == null) { throw new ArgumentNullException("sharePointServiceContext"); } TokenHelper.ClientId = sharePointServiceContext.ClientId; TokenHelper.ClientSecret = sharePointServiceContext.ClientSecret; TokenHelper.HostedAppHostName = sharePointServiceContext.HostedAppHostName; SharePointContextToken sharePointContextToken = TokenHelper.ReadAndValidateContextToken(sharePointServiceContext.Token); OAuth2AccessTokenResponse accessToken = TokenHelper.GetAccessToken(sharePointContextToken, new Uri(sharePointServiceContext.HostWebUrl).Authority); WebAPIContexCacheItem cacheItem = new WebAPIContexCacheItem() { RefreshToken = sharePointContextToken.RefreshToken, AccessToken = accessToken, SharePointServiceContext = sharePointServiceContext }; WebAPIContextCache.Instance.Put(sharePointServiceContext.CacheKey, cacheItem); }
protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { try { /* Save the context token, access token, and web url in hidden fields * These will be needed by subsequent REST calls */ hdnContextToken.Value = TokenHelper.GetContextTokenFromRequest(Page.Request); hdnHostWeb.Value = Page.Request["SPHostUrl"]; string remoteWebUrl = Request.Url.Authority; SharePointContextToken spContextToken = TokenHelper.ReadAndValidateContextToken(hdnContextToken.Value, remoteWebUrl); Uri hostWebUri = new Uri(hdnHostWeb.Value); string hostWebAuthority = hostWebUri.Authority; OAuth2AccessTokenResponse accessToken = TokenHelper.GetAccessToken(spContextToken, hostWebAuthority); hdnAccessToken.Value = accessToken.AccessToken; //Get the current user and save in hidden fields string endpoint = hdnHostWeb.Value + "/_api/web/currentuser"; XNamespace d = "http://schemas.microsoft.com/ado/2007/08/dataservices"; XDocument responseDoc = GetDataREST(endpoint); hdnDisplayName.Value = responseDoc.Descendants(d + "Title").First().Value; hdnUserId.Value = responseDoc.Descendants(d + "Id").First().Value; //Show assignment candidates assignmentPosts.DataSource = GetAssignmentCandidates(); assignmentPosts.DataBind(); } catch (Exception x) { messages.Text = x.Message; } } }
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); }
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 }
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(); }