/// <summary> /// Acquires an IUserIdentity from Azure Active Directory using the argument authorizationCode. /// </summary> /// <param name="authorizationCode">An authorization code provided by Azure Active Directory used to retrieve an IUserIdentity</param> /// <returns>Returns an IUserIdentity representing a successfully authenticated Azure Active Directory user who has privileges for this configured application</returns> public static IUserIdentity GetAuthenticatedUserIDentity(string authorizationCode) { var authenticationContext = new Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext(string.Format("https://login.windows.net/{0}", AAD.TENANT_ID)); var clientCredential = new Microsoft.IdentityModel.Clients.ActiveDirectory.ClientCredential(AAD.CLIENT_ID, AAD.CLIENT_KEY); var authenticationResult = authenticationContext.AcquireTokenByAuthorizationCode(authorizationCode, new Uri(AAD.REPLY_URL), clientCredential); return new UserIdentity(authenticationResult.UserInfo); }
public static async Task <AuthResult> GetToken(string userUniqueId, Microsoft.IdentityModel.Clients.ActiveDirectory.TokenCache tokenCache, string resourceId) { Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext context = new Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext(AuthSettings.EndpointUrl + "/" + AuthSettings.Tenant, tokenCache); var result = await context.AcquireTokenSilentAsync(resourceId, new Microsoft.IdentityModel.Clients.ActiveDirectory.ClientCredential(AuthSettings.ClientId, AuthSettings.ClientSecret), new Microsoft.IdentityModel.Clients.ActiveDirectory.UserIdentifier(userUniqueId, Microsoft.IdentityModel.Clients.ActiveDirectory.UserIdentifierType.UniqueId)); AuthResult authResult = AuthResult.FromADALAuthenticationResult(result, tokenCache); return(authResult); }
public static async Task <AuthResult> GetTokenByAuthCodeAsync(string authorizationCode, Microsoft.IdentityModel.Clients.ActiveDirectory.TokenCache tokenCache) { Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext context = new Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext(AuthSettings.EndpointUrl + "/" + AuthSettings.Tenant, tokenCache); Uri redirectUri = new Uri(AuthSettings.RedirectUrl); var result = await context.AcquireTokenByAuthorizationCodeAsync(authorizationCode, redirectUri, new Microsoft.IdentityModel.Clients.ActiveDirectory.ClientCredential(AuthSettings.ClientId, AuthSettings.ClientSecret)); AuthResult authResult = AuthResult.FromADALAuthenticationResult(result, tokenCache); return(authResult); }
/// <summary> /// Invoked when this page is about to be displayed in a Frame. /// </summary> /// <param name="e">Event data that describes how this page was reached. /// This parameter is typically used to configure the page.</param> protected override void OnNavigatedTo(NavigationEventArgs e) { this.navigationHelper.OnNavigatedTo(e); if (e.NavigationMode == NavigationMode.New) { authContext = Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext.CreateAsync("https://login.windows.net/appsthepagedot.onmicrosoft.com", true).GetResults(); lastFileName.Text = Convert.ToString(LocalStorage.GetSetting("lastFileName")); } }
public static async Task <AuthenticationResult> GetTokenByAuthCodeAsync(string authorizationCode, AuthenticationSettings authenticationSettings) { var tokenCache = TokenCacheFactory.GetADALTokenCache(); Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext context = new Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext(authenticationSettings.EndpointUrl + "/" + authenticationSettings.Tenant, tokenCache); Uri redirectUri = new Uri(authenticationSettings.RedirectUrl); var result = await context.AcquireTokenByAuthorizationCodeAsync(authorizationCode, redirectUri, new Microsoft.IdentityModel.Clients.ActiveDirectory.ClientCredential(authenticationSettings.ClientId, authenticationSettings.ClientSecret)); AuthenticationResult authResult = ConvertAuthenticationResult(result, tokenCache); return(authResult); }
public static async Task <string> SendGraphGetRequest(AuthenticationResult authResult, string api, string query, string tenant, string adminClientId, string adminClientSecret) { var authContext = new Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext("https://login.microsoftonline.com/" + tenant); var credential = new Microsoft.IdentityModel.Clients.ActiveDirectory.ClientCredential(adminClientId, adminClientSecret); // Here you ask for a token using the web app's clientId as the scope, since the web app and service share the same clientId. // AcquireTokenSilentAsync will return a token from the token cache, and throw an exception if it cannot do so. //var authContext = new AuthenticationContext(authority, new NaiveSessionCache(userObjectId)); //// We don't care which policy is used to access the TaskService, so let's use the most recent policy //var mostRecentPolicy = authTicket.Identity.FindFirst(AcrClaimType).Value; //var result = await authContext.AcquireTokenSilentAsync(new string[] { clientId }, credential, UserIdentifier.AnyUser, mostRecentPolicy); //// First, use ADAL to acquire a token using the app's identity (the credential) //// The first parameter is the resource we want an access_token for; in this case, the Graph API. var result = authContext.AcquireToken("https://graph.windows.net", credential); // For B2C user managment, be sure to use the beta Graph API version. var http = new HttpClient(); var url = "https://graph.windows.net/" + tenant + api + "?" + "api-version=beta"; if (!string.IsNullOrEmpty(query)) { url += "&" + query; } //Console.ForegroundColor = ConsoleColor.Cyan; //Console.WriteLine("GET " + url); //Console.WriteLine("Authorization: Bearer " + result.AccessToken.Substring(0, 80) + "..."); //Console.WriteLine(""); // Append the access token for the Graph API to the Authorization header of the request, using the Bearer scheme. var request = new HttpRequestMessage(HttpMethod.Get, url); //request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", authResult.Token); request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken); var response = await http.SendAsync(request); if (!response.IsSuccessStatusCode) { string error = await response.Content.ReadAsStringAsync(); object formatted = JsonConvert.DeserializeObject(error); throw new WebException("Error Calling the Graph API: \n" + JsonConvert.SerializeObject(formatted, Formatting.Indented)); } //Console.ForegroundColor = ConsoleColor.Green; //Console.WriteLine((int)response.StatusCode + ": " + response.ReasonPhrase); //Console.WriteLine(""); return(await response.Content.ReadAsStringAsync()); }
public async static System.Threading.Tasks.Task <string> GetToken(string authority, string resource, string scope) { var authContext = new Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext(authority); Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationResult result = await authContext.AcquireTokenAsync(resource, _clientCredential); if (result == null) { throw new System.InvalidOperationException("Failed to obtain the access token"); } return(result.AccessToken); }
private async Task <string> GetAppTokenAsync() { // *****ADAL code Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationResult tokenResult = null; string userObjectID = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value; Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext authContext = new Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext(authority, false); Microsoft.IdentityModel.Clients.ActiveDirectory.ClientCredential credential = new Microsoft.IdentityModel.Clients.ActiveDirectory.ClientCredential(clientId, appKey); tokenResult = await authContext.AcquireTokenAsync(resAzureGraphAPI, credential); return(tokenResult.AccessToken); }
public static async Task <string> GetAuthUrlAsync(ResumptionCookie resumptionCookie, string resourceId) { var encodedCookie = UrlToken.Encode(resumptionCookie); Uri redirectUri = new Uri(AuthSettings.RedirectUrl); Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext context = new Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext(AuthSettings.EndpointUrl + "/" + AuthSettings.Tenant); var uri = await context.GetAuthorizationRequestUrlAsync( resourceId, AuthSettings.ClientId, redirectUri, Microsoft.IdentityModel.Clients.ActiveDirectory.UserIdentifier.AnyUser, "state=" + encodedCookie); return(uri.ToString()); }
public static async Task <OAuth.AuthenticationResult> GetToken(string userUniqueId, OAuth.AuthenticationRequest request) { AuthenticationSettings authenticationSettings = AuthenticationSettings.GetFromAppSettings(); OAuth.AuthenticationResult authenticationResult; var tokenCache = OAuth.TokenCacheFactory.GetTokenCache <ADALTokenCache>(request); Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext context = new Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext(authenticationSettings.EndpointUrl + "/" + authenticationSettings.Tenant, tokenCache); var result = await context.AcquireTokenSilentAsync(request.ResourceId, new Microsoft.IdentityModel.Clients.ActiveDirectory.ClientCredential(authenticationSettings.ClientId, authenticationSettings.ClientSecret), new Microsoft.IdentityModel.Clients.ActiveDirectory.UserIdentifier(userUniqueId, Microsoft.IdentityModel.Clients.ActiveDirectory.UserIdentifierType.UniqueId)); authenticationResult = ConvertAuthenticationResult(result, tokenCache); return(authenticationResult); }
public static async Task <string> GetAuthUrlAsync(ConversationReference conversationReference, string resourceId) { var extraParameters = BuildExtraParameters(conversationReference); Uri redirectUri = new Uri(AuthSettings.RedirectUrl); Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext context = new Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext(AuthSettings.EndpointUrl + "/" + AuthSettings.Tenant); var uri = await context.GetAuthorizationRequestUrlAsync( resourceId, AuthSettings.ClientId, redirectUri, Microsoft.IdentityModel.Clients.ActiveDirectory.UserIdentifier.AnyUser, $"state={extraParameters}"); return(uri.ToString()); }
private ActionResult ProcessUnauthorized(List <TodoItem> itemList, Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext authContext) { var todoTokens = authContext.TokenCache.ReadItems().Where(a => a.Resource == AzureAdOptions.Settings.TodoListResourceId); foreach (Microsoft.IdentityModel.Clients.ActiveDirectory.TokenCacheItem tci in todoTokens) { authContext.TokenCache.DeleteItem(tci); } ViewBag.ErrorMessage = "UnexpectedError"; TodoItem newItem = new TodoItem(); newItem.Title = "(No items in list)"; itemList.Add(newItem); return(View(itemList)); }
public static async Task <string> GetAuthUrlAsync(ResumptionCookie resumptionCookie, string resourceId) { var extraParameters = AuthUtilities.EncodeResumptionCookie(resumptionCookie); AuthenticationSettings authenticationSettings = AuthenticationSettings.GetFromAppSettings(); Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext context = new Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext(authenticationSettings.EndpointUrl + "/" + authenticationSettings.Tenant); Uri redirectUri = new Uri(authenticationSettings.RedirectUrl); var uri = await context.GetAuthorizationRequestUrlAsync( resourceId, authenticationSettings.ClientId, redirectUri, Microsoft.IdentityModel.Clients.ActiveDirectory.UserIdentifier.AnyUser, $"state={extraParameters}&response_mode=form_post"); return(uri.ToString()); }
private async Task RedeemUsernameAndPasswordAsync() { if (string.IsNullOrEmpty(this.AccessToken)) { var creds = new Microsoft.IdentityModel.Clients.ActiveDirectory.UserCredential(this.Username, this.Password); var context = new Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext(this.TokenService); var token = await context.AcquireTokenAsync(this.Resource, this.ClientId, creds); if (null != token) { this.AccessToken = token.AccessToken; } else { throw new OAuthAccountException( string.Format("Failed to convert username + password to access token for account: {0}", this.Name)); } } }
private async Task <string> getTokenAsync() { var tenantName = ConfigurationManager.AppSettings.Get("tenantName"); var aad = ConfigurationManager.AppSettings.Get("aad"); var authority = string.Format(CultureInfo.InvariantCulture, aad, tenantName); var clientId = ConfigurationManager.AppSettings.Get("clientId"); var authContext = new Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext(authority); X509Certificate2 cert = Helper.GetCertificateBySubject(); var certCred = new Microsoft.IdentityModel.Clients.ActiveDirectory.ClientAssertionCertificate(clientId, cert); string token = null; Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationResult result = await authContext.AcquireTokenAsync(_resource, certCred); if (result != null) { token = result.AccessToken; } return(token); }
public static Microsoft.Dynamics.CRM.System GetCdsContext() { var cdsConfig = GetCdsConfig(); var cdsContext = new Microsoft.Dynamics.CRM.System(new Uri($"{cdsConfig.UriString}/api/data/v9.0/")); var authContext = new Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext( "https://login.windows.net/common", false); var result = Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContextIntegratedAuthExtensions.AcquireTokenAsync( authContext, cdsConfig.UriString, cdsConfig.NativeAppId, new Microsoft.IdentityModel.Clients.ActiveDirectory.UserPasswordCredential( cdsConfig.User, cdsConfig.Password)).Result; cdsContext.BuildingRequest += (sender, eventArgs) => { eventArgs.Headers["Authorization"] = "Bearer " + result.AccessToken; }; return(cdsContext); }
/// <summary> /// Obtains an OAuth access token which can then be used to make authorized calls /// to the Direct ID API. /// </summary> /// <remarks> /// <para>The returned value is expected to be included in the authentication header /// of subsequent API requests.</para> /// <para>As the returned value authenticates the application, API calls made using /// this value should only be made using server-side code.</para> /// </remarks> private static string AcquireOAuthAccessToken(CredentialsModel credentials) { TrimCredentialsModel(credentials); var context = new Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext( credentials.Authority); var accessToken = context.AcquireToken( credentials.ResourceID, new Microsoft.IdentityModel.Clients.ActiveDirectory.ClientCredential( credentials.ClientID, credentials.SecretKey)); if (accessToken == null) { throw new InvalidOperationException( "Unable to acquire access token from resource: " + credentials.ResourceID + ". Please check your settings from Direct ID."); } return accessToken.AccessToken; }
/// <summary> /// get the bearer token for adding to authorization header /// </summary> /// <returns></returns> private async static Task <string> GetBearerToken() { try { string authContextURL = "https://login.windows.net/" + tenantId; var authenticationContext = new Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext(authContextURL); var cred = new Microsoft.IdentityModel.Clients.ActiveDirectory.ClientCredential(clientId, clientKey); var result = await authenticationContext.AcquireTokenAsync("https://management.azure.com/", cred); if (result == null) { throw new InvalidOperationException("Failed to obtain the JWT token"); } string token = result.AccessToken; return(token); } catch (Exception ex) { throw ex; } }
public AdalNaiveAuthenticationProvider(string tenantAuthorityMSOnline) { _authenticationContext = new ADAuthenticationContext(tenantAuthorityMSOnline); }
private async Task RedeemUsernameAndPasswordAsync() { if (string.IsNullOrEmpty(this.AccessToken)) { var creds = new Microsoft.IdentityModel.Clients.ActiveDirectory.UserCredential(this.Username, this.Password); var context = new Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext(this.TokenService); var token = await context.AcquireTokenAsync(this.Resource, this.ClientId, creds); if (null != token) { this.AccessToken = token.AccessToken; } else { throw new InvalidOperationException( string.Format("Failed to convert username + password to access token for account: {0}", this.Name)); } } }
private async void UserAuthentication_Click(object sender, RoutedEventArgs e) { string msg = string.Empty; int count = -1; string Token = null; LogMessage("Interactive User Authentication - Azure Tenant: " + azureActiveDirectoryTenantDomain.Text); string authority = "https://login.microsoftonline.com/" + azureActiveDirectoryTenantDomain.Text; Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext ac = new Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext(authority); string resourceUrl = "https://rest.media.azure.net"; string redirectUri = "https://AzureMediaServicesNativeSDK"; Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationResult result = null; try { Microsoft.IdentityModel.Clients.ActiveDirectory.IPlatformParameters param = new Microsoft.IdentityModel.Clients.ActiveDirectory.PlatformParameters(Microsoft.IdentityModel.Clients.ActiveDirectory.PromptBehavior.Always, false);; result = await ac.AcquireTokenAsync(resourceUrl, "d476653d-842c-4f52-862d-397463ada5e7", new Uri(redirectUri), param); } catch (Exception ex) { LogMessage("Interactive User Authentication - Exception: " + ex.Message); } if (result != null) { Token = result.AccessToken; if (!string.IsNullOrEmpty(Token)) { LogMessage("Interactive User Authentication successful"); LogMessage("Token: " + Token); try { LogMessage("Getting Media Objects - Account Name: " + legacyAccountName.Text + " from region " + azureRegion.Text); count += await GetMediaObjectsCount <Asset>(Token, legacyAccountName.Text, azureRegion.Text); count += await GetMediaObjectsCount <MediaProcessor>(Token, legacyAccountName.Text, azureRegion.Text); count += await GetMediaObjectsCount <Channel>(Token, legacyAccountName.Text, azureRegion.Text); count += await GetMediaObjectsCount <AzureMediaServicesREST.Program>(Token, legacyAccountName.Text, azureRegion.Text); count += await GetMediaObjectsCount <StreamingEndpoint>(Token, legacyAccountName.Text, azureRegion.Text); count += await GetMediaObjectsCount <Locator>(Token, legacyAccountName.Text, azureRegion.Text); count += await GetMediaObjectsCount <AccessPolicie>(Token, legacyAccountName.Text, azureRegion.Text); SaveSettings(); } catch (Exception ex) { msg = ex.Message; LogMessage("Getting Media Objects - Exception: " + msg); } if (count >= 0) { Show("Interactive User Authentication successful: " + count.ToString() + " asset(s) found"); } else { Show("Interactive User Authentication failed" + (string.IsNullOrEmpty(msg) ? "" : ": Exception - " + msg)); } } else { Show("Interactive User Authentication failed"); } } else { Show("Interactive User Authentication failed"); } }
public static async Task <string> GetAuthUrlAsync(ResumptionCookie resumptionCookie) { var encodedCookie = UrlToken.Encode(resumptionCookie); Uri redirectUri = new Uri(AuthSettings.RedirectUrl); if (string.Equals(AuthSettings.Mode, "v1", StringComparison.OrdinalIgnoreCase)) { Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext context = new Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext(AuthSettings.EndpointUrl + "/" + AuthSettings.Tenant); var uri = await context.GetAuthorizationRequestUrlAsync( AuthSettings.ResourceId, AuthSettings.ClientId, redirectUri, Microsoft.IdentityModel.Clients.ActiveDirectory.UserIdentifier.AnyUser, "state=" + encodedCookie); return(uri.ToString()); } else if (string.Equals(AuthSettings.Mode, "v2", StringComparison.OrdinalIgnoreCase)) { InMemoryTokenCacheMSAL tokenCache = new InMemoryTokenCacheMSAL(); Microsoft.Identity.Client.ConfidentialClientApplication client = new Microsoft.Identity.Client.ConfidentialClientApplication(AuthSettings.ClientId, redirectUri.ToString(), new Microsoft.Identity.Client.ClientCredential(AuthSettings.ClientSecret), tokenCache); var uri = await client.GetAuthorizationRequestUrlAsync( AuthSettings.Scopes, null, "state=" + encodedCookie); //, // null // clientId.Value, // redirectUri, // Microsoft.Experimental.IdentityModel.Clients.ActiveDirectory.UserIdentifier.AnyUser, // "state=" + encodedCookie); return(uri.ToString()); } else if (string.Equals(AuthSettings.Mode, "b2c", StringComparison.OrdinalIgnoreCase)) { return(null); } return(null); }
private static string GetBearerToken() { string bearerToken = null; string authority = "https://login.microsoftonline.com/common/oauth2/" + "78eff5bb-da38-47f0-a836-294c6d784112"; string clientId = "bca42905-7439-47c7-a349-ef064fa6e8d6"; string clientSecret = "AWq9PpVl-@r_TpHTIoigicsX4?s5yHa4"; string resource = "https://management.core.windows.net/"; Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext authContext = new Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext(authority); Task <Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationResult> authResultTask = authContext.AcquireTokenAsync(resource, new Microsoft.IdentityModel.Clients.ActiveDirectory.ClientCredential(clientId, clientSecret)); bearerToken = authResultTask.Result.AccessToken; return(bearerToken); }
static async Task Setup() { appSettings = new ConfigurationBuilder() .SetBasePath(System.IO.Directory.GetCurrentDirectory()) .AddJsonFile("appSettings.json") .Build() .Get <AppSettings>(); var logger = new Microsoft.Extensions.Logging.LoggerFactory().CreateLogger("DigitalTwins"); httpClient = new HttpClient(new LoggingHttpHandler(logger)) { BaseAddress = new Uri($"{appSettings.BaseUrl}/api/v1.0/"), }; var accessTokenFilename = ".accesstoken"; var accessToken = System.IO.File.Exists(accessTokenFilename) ? System.IO.File.ReadAllText(accessTokenFilename) : null; if (accessToken != null) { httpClient.DefaultRequestHeaders.Add("Authorization", "Bearer " + accessToken); } // just a random query to check if authorized if (!(await httpClient.GetAsync("ontologies")).IsSuccessStatusCode) { var authContext = new Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext(appSettings.Authority); var codeResult = await authContext.AcquireDeviceCodeAsync(appSettings.Resource, appSettings.ClientId); Console.WriteLine(codeResult.Message); accessToken = (await authContext.AcquireTokenByDeviceCodeAsync(codeResult)).AccessToken; System.IO.File.WriteAllText(accessTokenFilename, accessToken); if (httpClient.DefaultRequestHeaders.Contains("Authorization")) { httpClient.DefaultRequestHeaders.Remove("Authorization"); } httpClient.DefaultRequestHeaders.Add("Authorization", "Bearer " + accessToken); } clients = new Clients(httpClient); spaces = clients.SpacesClient.Get(); devices = clients.DevicesClient.Get(); var ids = await clients.SpacesClient.RetrieveAsync(name : "root"); if (ids.Any()) { rootId = ids.First().Id; } else { rootId = await clients.SpacesClient.CreateAsync(new SpaceCreate { Name = "root", TypeId = 59 // Tenant }); } spaceTypes = clients.TypesClient.Get(ExtendedTypeCreateCategory.SpaceType, rootId); deviceTypes = clients.TypesClient.Get(ExtendedTypeCreateCategory.DeviceType, rootId); sensorTypes = clients.TypesClient.Get(ExtendedTypeCreateCategory.SensorType, rootId); sensorDataTypes = clients.TypesClient.Get(ExtendedTypeCreateCategory.SensorDataType, rootId); spaceBlobType = clients.TypesClient.Get(ExtendedTypeCreateCategory.SpaceBlobType, rootId); spaceBlobSubType = clients.TypesClient.Get(ExtendedTypeCreateCategory.SpaceBlobSubtype, rootId); }
public static async Task<string> SendGraphGetRequest(AuthenticationResult authResult, string api, string query, string tenant, string adminClientId, string adminClientSecret) { var authContext = new Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext("https://login.microsoftonline.com/" + tenant); var credential = new Microsoft.IdentityModel.Clients.ActiveDirectory.ClientCredential(adminClientId, adminClientSecret); // Here you ask for a token using the web app's clientId as the scope, since the web app and service share the same clientId. // AcquireTokenSilentAsync will return a token from the token cache, and throw an exception if it cannot do so. //var authContext = new AuthenticationContext(authority, new NaiveSessionCache(userObjectId)); //// We don't care which policy is used to access the TaskService, so let's use the most recent policy //var mostRecentPolicy = authTicket.Identity.FindFirst(AcrClaimType).Value; //var result = await authContext.AcquireTokenSilentAsync(new string[] { clientId }, credential, UserIdentifier.AnyUser, mostRecentPolicy); //// First, use ADAL to acquire a token using the app's identity (the credential) //// The first parameter is the resource we want an access_token for; in this case, the Graph API. var result = authContext.AcquireToken("https://graph.windows.net", credential); // For B2C user managment, be sure to use the beta Graph API version. var http = new HttpClient(); var url = "https://graph.windows.net/" + tenant + api + "?" + "api-version=beta"; if (!string.IsNullOrEmpty(query)) { url += "&" + query; } //Console.ForegroundColor = ConsoleColor.Cyan; //Console.WriteLine("GET " + url); //Console.WriteLine("Authorization: Bearer " + result.AccessToken.Substring(0, 80) + "..."); //Console.WriteLine(""); // Append the access token for the Graph API to the Authorization header of the request, using the Bearer scheme. var request = new HttpRequestMessage(HttpMethod.Get, url); //request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", authResult.Token); request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken); var response = await http.SendAsync(request); if (!response.IsSuccessStatusCode) { string error = await response.Content.ReadAsStringAsync(); object formatted = JsonConvert.DeserializeObject(error); throw new WebException("Error Calling the Graph API: \n" + JsonConvert.SerializeObject(formatted, Formatting.Indented)); } //Console.ForegroundColor = ConsoleColor.Green; //Console.WriteLine((int)response.StatusCode + ": " + response.ReasonPhrase); //Console.WriteLine(""); return await response.Content.ReadAsStringAsync(); }