public override Task <IAccessToken> Authenticate(AuthenticationParameters parameters, CancellationToken cancellationToken) { var deviceCodeParameters = parameters as DeviceCodeParameters; var tokenCacheProvider = parameters.TokenCacheProvider; var onPremise = parameters.Environment.OnPremise; //null instead of "organizations" should be passed to Azure.Identity to support MSA account var tenantId = onPremise ? AdfsTenant : (string.Equals(parameters.TenantId, OrganizationsTenant, StringComparison.OrdinalIgnoreCase) ? null : parameters.TenantId); var resource = parameters.Environment.GetEndpoint(parameters.ResourceId) ?? parameters.ResourceId; var scopes = AuthenticationHelpers.GetScope(onPremise, resource); var clientId = AuthenticationHelpers.PowerShellClientId; var authority = parameters.Environment.ActiveDirectoryAuthority; var requestContext = new TokenRequestContext(scopes); AzureSession.Instance.TryGetComponent(nameof(PowerShellTokenCache), out PowerShellTokenCache tokenCache); DeviceCodeCredentialOptions options = new DeviceCodeCredentialOptions() { DeviceCodeCallback = DeviceCodeFunc, AuthorityHost = new Uri(authority), ClientId = clientId, TenantId = onPremise ? tenantId : null, TokenCache = tokenCache.TokenCache, }; var codeCredential = new DeviceCodeCredential(options); var authTask = codeCredential.AuthenticateAsync(requestContext, cancellationToken); return(MsalAccessToken.GetAccessTokenAsync( authTask, codeCredential, requestContext, cancellationToken)); }
public override Task <IAccessToken> Authenticate(AuthenticationParameters parameters, CancellationToken cancellationToken) { var deviceCodeParameters = parameters as DeviceCodeParameters; var tokenCacheProvider = parameters.TokenCacheProvider; var onPremise = parameters.Environment.OnPremise; //null instead of "organizations" should be passed to Azure.Identity to support MSA account var tenantId = onPremise ? AdfsTenant : (string.Equals(parameters.TenantId, OrganizationsTenant, StringComparison.OrdinalIgnoreCase) ? null : parameters.TenantId); var resource = parameters.Environment.GetEndpoint(parameters.ResourceId) ?? parameters.ResourceId; var scopes = AuthenticationHelpers.GetScope(onPremise, resource); var clientId = AuthenticationHelpers.PowerShellClientId; var authority = parameters.Environment.ActiveDirectoryAuthority; var requestContext = new TokenRequestContext(scopes); DeviceCodeCredentialOptions options = new DeviceCodeCredentialOptions() { DeviceCodeCallback = DeviceCodeFunc, AuthorityHost = new Uri(authority), ClientId = clientId, TenantId = tenantId, TokenCachePersistenceOptions = tokenCacheProvider.GetTokenCachePersistenceOptions(), }; var codeCredential = new DeviceCodeCredential(options); TracingAdapter.Information($"{DateTime.Now:T} - [DeviceCodeAuthenticator] Calling DeviceCodeCredential.AuthenticateAsync - TenantId:'{options.TenantId}', Scopes:'{string.Join(",", scopes)}', AuthorityHost:'{options.AuthorityHost}'"); var authTask = codeCredential.AuthenticateAsync(requestContext, cancellationToken); return(MsalAccessToken.GetAccessTokenAsync( authTask, codeCredential, requestContext, cancellationToken)); }
public async Task AuthenticateWithDeviceCodeNoCallback() { var capturedOut = new StringBuilder(); var capturedOutWriter = new StringWriter(capturedOut); var stdOut = Console.Out; Console.SetOut(capturedOutWriter); try { var client = new DeviceCodeCredential { Client = mockPublicMsalClient }; var cred = InstrumentClient(client); AccessToken token = await cred.GetTokenAsync(new TokenRequestContext(new[] { Scope })); Assert.AreEqual(token.Token, expectedToken); Assert.AreEqual(mockPublicMsalClient.DeviceCodeResult.Message + Environment.NewLine, capturedOut.ToString()); token = await cred.GetTokenAsync(new TokenRequestContext(new[] { Scope })); Assert.AreEqual(token.Token, expectedToken); Assert.AreEqual(mockPublicMsalClient.DeviceCodeResult.Message + Environment.NewLine, capturedOut.ToString()); } finally { Console.SetOut(stdOut); } }
public void GetTokenUsingDeviceCodeCredential() { string tenantId = TestEnvironment.TenantId; string clientId = TestEnvironment.ClientId; string mixedRealityAccountDomain = TestEnvironment.AccountDomain; string mixedRealityAccountId = TestEnvironment.AccountId; #region Snippet:GetTokenUsingDefaultAzureCredential string authority = $"https://login.microsoftonline.com/{tenantId}"; Task deviceCodeCallback(DeviceCodeInfo deviceCodeInfo, CancellationToken cancellationToken) { Debug.WriteLine(deviceCodeInfo.Message); Console.WriteLine(deviceCodeInfo.Message); return(Task.FromResult(0)); } TokenCredential deviceCodeCredential = new DeviceCodeCredential(deviceCodeCallback, tenantId, clientId, new TokenCredentialOptions { AuthorityHost = new Uri(authority), }); MixedRealityStsClient client = new MixedRealityStsClient(mixedRealityAccountId, mixedRealityAccountDomain, deviceCodeCredential); AccessToken token = client.GetToken(); Console.WriteLine($"My access token ({token.Token}) expires on {token.ExpiresOn}."); #endregion Snippet:GetTokenUsingDefaultAzureCredential }
public async Task AuthenticateWithDeviceCodeMockVerifyCallbackCancellationAsync() { var expectedCode = Guid.NewGuid().ToString(); var expectedToken = Guid.NewGuid().ToString(); var mockTransport = new MockTransport(request => ProcessMockRequest(request, expectedCode, expectedToken)); var options = new IdentityClientOptions() { Transport = mockTransport }; var cancelSource = new CancellationTokenSource(1000); DeviceCodeCredential cred = InstrumentClient(new DeviceCodeCredential(ClientId, VerifyDeviceCodeCallbackCancellationToken, options)); Task <AccessToken> getTokenTask = cred.GetTokenAsync(new string[] { "https://vault.azure.net/.default" }, cancelSource.Token); try { AccessToken token = await getTokenTask; Assert.Fail(); } catch (TaskCanceledException) { } }
public void ValidateConstructorOverload3() { // tests the DeviceCodeCredential constructor overload // public DeviceCodeCredential(Func<DeviceCodeInfo, CancellationToken, Task> deviceCodeCallback, string tenantId, string clientId, TokenCredentialOptions options = default) var options = new DeviceCodeCredentialOptions { ClientId = Guid.NewGuid().ToString(), TenantId = Guid.NewGuid().ToString(), DeviceCodeCallback = DummyCallback, }; // deviceCodeCallback null Assert.Throws <ArgumentNullException>(() => new DeviceCodeCredential(null, options.TenantId, options.ClientId)); // clientId null Assert.Throws <ArgumentNullException>(() => new DeviceCodeCredential(options.DeviceCodeCallback, options.TenantId, (string)null)); // without options var credential = new DeviceCodeCredential(options.DeviceCodeCallback, options.TenantId, options.ClientId); AssertOptionsHonored(options, credential); // with options options.AuthorityHost = new Uri("https://login.myauthority.com/"); credential = new DeviceCodeCredential(options.DeviceCodeCallback, options.TenantId, options.ClientId, new TokenCredentialOptions { AuthorityHost = options.AuthorityHost }); AssertOptionsHonored(options, credential); }
public void ValidateConstructorOverload1() { // tests the DeviceCodeCredential constructor overload // public DeviceCodeCredential(DeviceCodeCredentialOptions options) // null var credential = new DeviceCodeCredential(null); AssertOptionsHonored(new DeviceCodeCredentialOptions(), credential); // with options // with options var options = new DeviceCodeCredentialOptions { ClientId = Guid.NewGuid().ToString(), TenantId = Guid.NewGuid().ToString(), AuthorityHost = new Uri("https://login.myauthority.com/"), DisableAutomaticAuthentication = true, TokenCache = new TokenCache(), AuthenticationRecord = new AuthenticationRecord(), DeviceCodeCallback = DummyCallback, }; credential = new DeviceCodeCredential(options); AssertOptionsHonored(options, credential); }
private RemoteRenderingClient GetClientWithDeviceCode() { Guid accountId = new Guid(TestEnvironment.AccountId); string accountDomain = TestEnvironment.AccountDomain; string tenantId = TestEnvironment.TenantId; string clientId = TestEnvironment.ClientId; Uri remoteRenderingEndpoint = new Uri(TestEnvironment.ServiceEndpoint); #region Snippet:CreateAClientWithDeviceCode RemoteRenderingAccount account = new RemoteRenderingAccount(accountId, accountDomain); Task deviceCodeCallback(DeviceCodeInfo deviceCodeInfo, CancellationToken cancellationToken) { Console.WriteLine(deviceCodeInfo.Message); return(Task.FromResult(0)); } TokenCredential credential = new DeviceCodeCredential(deviceCodeCallback, tenantId, clientId, new TokenCredentialOptions { AuthorityHost = new Uri($"https://login.microsoftonline.com/{tenantId}"), }); RemoteRenderingClient client = new RemoteRenderingClient(remoteRenderingEndpoint, account, credential); #endregion Snippet:CreateAClientWithDeviceCode return(client); }
public void Identity_ClientSideUserAuthentication_SimpleDeviceCode() { #region Snippet:Identity_ClientSideUserAuthentication_SimpleDeviceCode var credential = new DeviceCodeCredential(); var client = new BlobClient(new Uri("https://myaccount.blob.core.windows.net/mycontainer/myblob"), credential); #endregion }
public void DeviceCodeCredentialCtorNullTenantId() { var clientId = Guid.NewGuid().ToString(); // validate no exception is thrown when setting TenantId to null var cred = new DeviceCodeCredential(DeviceCodeCredential.DefaultDeviceCodeHandler, null, clientId); cred = new DeviceCodeCredential(DeviceCodeCredential.DefaultDeviceCodeHandler, null, clientId, new TokenCredentialOptions()); }
public void RespectsIsPIILoggingEnabled([Values(true, false)] bool isLoggingPIIEnabled) { var credential = new DeviceCodeCredential(new DeviceCodeCredentialOptions { IsLoggingPIIEnabled = isLoggingPIIEnabled }); Assert.NotNull(credential.Client); Assert.AreEqual(isLoggingPIIEnabled, credential.Client.IsPiiLoggingEnabled); }
public void AssertOptionsHonored(DeviceCodeCredentialOptions options, DeviceCodeCredential credential) { Assert.AreEqual(options.ClientId, credential.ClientId); Assert.AreEqual(options.TenantId, credential.Client.TenantId); Assert.AreEqual(options.AuthorityHost, credential.Pipeline.AuthorityHost); Assert.AreEqual(options.DisableAutomaticAuthentication, credential.DisableAutomaticAuthentication); Assert.AreEqual(options.AuthenticationRecord, credential.Record); AssertCallbacksEqual(options.DeviceCodeCallback ?? DeviceCodeCredential.DefaultDeviceCodeHandler, credential.DeviceCodeCallback); }
static void Main(string[] args) { string powerShellClientId = "1950a258-227b-4e31-a9cf-717495945fc2"; CancellationToken cancellationToken = new CancellationToken(); DeviceCodeCredential codeCredential = new DeviceCodeCredential(DeviceCodeFunc, "organizations", powerShellClientId); AuthenticationRecord record = codeCredential.Authenticate(cancellationToken); var scopes = new[] { "https://management.core.windows.net//.default" }; TokenRequestContext requestContext = new TokenRequestContext(scopes); var token = codeCredential.GetToken(requestContext, cancellationToken); }
public async Task AuthenticateWithDeviceCodeMockAsync2() { var expectedCode = Guid.NewGuid().ToString(); var expectedToken = Guid.NewGuid().ToString(); var mockTransport = new MockTransport(request => ProcessMockRequest(request, expectedCode, expectedToken)); var options = new IdentityClientOptions() { Transport = mockTransport }; DeviceCodeCredential cred = InstrumentClient(new DeviceCodeCredential(ClientId, (code, cancelToken) => VerifyDeviceCode(code, expectedCode), options)); AccessToken token = await cred.GetTokenAsync(new string[] { "https://vault.azure.net/.default" }); Assert.AreEqual(token.Token, expectedToken); }
public void AuthenticateWithDeviceCodeCallbackThrowsAsync() { var expectedCode = Guid.NewGuid().ToString(); var expectedToken = Guid.NewGuid().ToString(); var cancelSource = new CancellationTokenSource(); var mockTransport = new MockTransport(request => ProcessMockRequest(request, expectedCode, expectedToken)); var options = new IdentityClientOptions() { Transport = mockTransport }; DeviceCodeCredential cred = InstrumentClient(new DeviceCodeCredential(ClientId, ThrowingDeviceCodeCallback, options)); Assert.ThrowsAsync <MockException>(async() => await cred.GetTokenAsync(new string[] { "https://vault.azure.net/.default" }, cancelSource.Token)); }
private static async Task GetDeviceCodeCredential() { string[] scopes = new[] { "User.Read" }; string clientId = "cdc858be-9aaa-4339-94e1-86414d05a056"; string expectedCode = "This is a test"; DeviceCodeCredential deviceCodeCredential = new DeviceCodeCredential((code, cancelToken) => VerifyDeviceCode(code, expectedCode), "9cacb64e-358b-418b-967a-3cabc2a0ea95", clientId); TokenCredentialAuthProvider tokenCredentialAuthProvider = new TokenCredentialAuthProvider(deviceCodeCredential, scopes); //Try to get something from the Graph!! HttpClient httpClient = GraphClientFactory.Create(tokenCredentialAuthProvider); HttpRequestMessage requestMessage = new HttpRequestMessage(HttpMethod.Get, "https://graph.microsoft.com/v1.0/me/"); HttpResponseMessage response = await httpClient.SendAsync(requestMessage); //Print out the response :) string jsonResponse = await response.Content.ReadAsStringAsync(); Console.WriteLine(jsonResponse); }
public void ValidateDefaultConstructor() { var credential = new DeviceCodeCredential(); AssertOptionsHonored(new DeviceCodeCredentialOptions(), credential); }
static async Task ConsumeGraphAsync() { // Define the permission scopes that you need string[] scopes = { "User.Read", "Files.Read.All", "Group.Read.All" }; // Using Azure.Identity library, configure a set of credential options DeviceCodeCredentialOptions deviceCodeCredentialOptions = new DeviceCodeCredentialOptions() { ClientId = "<client-id>", TenantId = "<tenant-id>", DeviceCodeCallback = async(deviceCodeInfo, cancellationToken) => { // Write the Device Code in the Output window System.Diagnostics.Process.Start( new System.Diagnostics.ProcessStartInfo { FileName = $"PowerShell.exe", Arguments = $"-Command \"'{ deviceCodeInfo.UserCode }' | clip\"", UseShellExecute = true, WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden }); // Start the browser to input the Device Code System.Diagnostics.Process.Start( new System.Diagnostics.ProcessStartInfo { FileName = deviceCodeInfo.VerificationUri.ToString(), UseShellExecute = true }); // OR //Console.WriteLine($"Please go to {deviceCodeInfo.VerificationUri} and provide the following device code: {deviceCodeInfo.UserCode}"); //Console.ReadLine(); } }; // And a TokenCredential implementation DeviceCodeCredential deviceCodeCredentialCredential = new DeviceCodeCredential(deviceCodeCredentialOptions); // GraphServiceClient now supports as TokenCredential input var graphClient = new GraphServiceClient(deviceCodeCredentialCredential, scopes); // Use regular Graph SDK fluent syntax var me = await graphClient.Me.Request().GetAsync(); Console.WriteLine(me.DisplayName); // Or you can also use the new GetResponseAsync method var meResponse = await graphClient.Me.Request().GetResponseAsync(); // And process the response at HTTP level with status code Console.WriteLine($"HTTP Status code: {meResponse.StatusCode}"); // with response headers foreach (var h in meResponse.HttpHeaders) { var values = h.Value.Aggregate(string.Empty, (s, v) => ($"{s},{v}")).TrimStart(','); Console.WriteLine($"{h.Key}: {values}"); } // with response content as string var meString = await meResponse.Content.ReadAsStringAsync(); Console.WriteLine(meString); // or still with fully typed response me = await meResponse.GetResponseObjectAsync(); Console.WriteLine(me.DisplayName); }