public object Post(OAuth2AccessTokenRequest request) { object result = VerifyBasicAuth(); if (result != null) return result; if (request.grant_type == "password") { if (request.username == OAuth2TestConstants.Username && request.password == OAuth2TestConstants.UserPassword || request.username == OAuth2TestConstants.UsernameWithEmptyPassword) { return new OAuth2AccessTokenResponse { access_token = OAuth2TestConstants.CreatedAccessToken, token_type = "beAReR", // Mixed case => assert testing for this is case-insensitive additional_param = "Special", expires_in = 199 }; } else return new OperationResult.BadRequest { ResponseResource = new OAuth2Error { error = "invalid_grant" } }; } else if (request.grant_type == "refresh_token") { return new OAuth2AccessTokenResponse { access_token = OAuth2TestConstants.CreatedAccessToken, token_type = "beAReR", // Mixed case => assert testing for this is case-insensitive additional_param = "Special", expires_in = 199 }; } else if (request.grant_type == "client_credentials") { return new OAuth2AccessTokenResponse { access_token = OAuth2TestConstants.CreatedAccessToken, token_type = "beAReR", // Mixed case => assert testing for this is case-insensitive additional_param = "Special", expires_in = 199 }; } else return new OperationResult.BadRequest { ResponseResource = new OAuth2Error { error = "unsupported_grant_type" } }; }
/// <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 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); }
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(); }
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); }
/// <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> 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 (RequestFailedException) { if (!string.IsNullOrEmpty(SecondaryClientSecret)) { oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithAuthorizationCode( clientId, SecondaryClientSecret, authorizationCode, redirectUri, 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); }
public object Post(OAuth2AccessTokenRequest request) { object result = VerifyBasicAuth(); if (result != null) { return(result); } string additional_param = request.additional ?? "Special"; if (request.grant_type == "password") { if (request.username == OAuth2TestConstants.Username && request.password == OAuth2TestConstants.UserPassword || request.username == OAuth2TestConstants.UsernameWithEmptyPassword) { return(new OAuth2AccessTokenResponse { access_token = OAuth2TestConstants.CreatedAccessToken, token_type = "beAReR", // Mixed case => assert testing for this is case-insensitive additional_param = additional_param, expires_in = 199 }); } else { return new OperationResult.BadRequest { ResponseResource = new OAuth2Error { error = "invalid_grant" } } }; } else if (request.grant_type == "refresh_token") { return(new OAuth2AccessTokenResponse { access_token = OAuth2TestConstants.CreatedAccessToken, token_type = "beAReR", // Mixed case => assert testing for this is case-insensitive additional_param = additional_param, expires_in = 199 }); } else if (request.grant_type == "client_credentials") { return(new OAuth2AccessTokenResponse { access_token = OAuth2TestConstants.CreatedAccessToken, token_type = "beAReR", // Mixed case => assert testing for this is case-insensitive additional_param = additional_param, expires_in = 199 }); } else { return new OperationResult.BadRequest { ResponseResource = new OAuth2Error { error = "unsupported_grant_type" } } }; }
public OAuth2WebRequest(string requestUriString, OAuth2AccessTokenRequest request) { this._innerRequest = System.Net.WebRequest.Create(requestUriString); this._request = request; }