public static async Task Main() { #region Snippet:AuthenticationRecord_TokenCachePersistenceOptions const string TOKEN_CACHE_NAME = "MyTokenCache"; InteractiveBrowserCredential credential; AuthenticationRecord authRecord; // Check if an AuthenticationRecord exists on disk. // If it does not exist, get one and serialize it to disk. // If it does exist, load it from disk and deserialize it. if (!File.Exists(AUTH_RECORD_PATH)) { // Construct a credential with TokenCachePersistenceOptions specified to ensure that the token cache is persisted to disk. // We can also optionally specify a name for the cache to avoid having it cleared by other applications. credential = new InteractiveBrowserCredential( new InteractiveBrowserCredentialOptions { TokenCachePersistenceOptions = new TokenCachePersistenceOptions { Name = TOKEN_CACHE_NAME } }); // Call AuthenticateAsync to fetch a new AuthenticationRecord. authRecord = await credential.AuthenticateAsync(); // Serialize the AuthenticationRecord to disk so that it can be re-used across executions of this initialization code. using var authRecordStream = new FileStream(AUTH_RECORD_PATH, FileMode.Create, FileAccess.Write); await authRecord.SerializeAsync(authRecordStream); } else { // Load the previously serialized AuthenticationRecord from disk and deserialize it. using var authRecordStream = new FileStream(AUTH_RECORD_PATH, FileMode.Open, FileAccess.Read); authRecord = await AuthenticationRecord.DeserializeAsync(authRecordStream); // Construct a new client with our TokenCachePersistenceOptions with the addition of the AuthenticationRecord property. // This tells the credential to use the same token cache in addition to which account to try and fetch from cache when GetToken is called. credential = new InteractiveBrowserCredential( new InteractiveBrowserCredentialOptions { TokenCachePersistenceOptions = new TokenCachePersistenceOptions { Name = TOKEN_CACHE_NAME }, AuthenticationRecord = authRecord }); } // Construct our client with the credential which is connected to the token cache // with the capability of silent authentication for the account specified in the AuthenticationRecord. var client = new SecretClient(new Uri("https://myvault.vault.azure.net/"), credential); #endregion }
public void DeserializesWithVersion() { var version = "1.0"; var jsonWithVersion = $"{{\"username\":\"2012c4ff-e82f-40de-ab6e-0afa51a1700d\",\"authority\":\"f5313742-e9ea-49fe-8864-910911375241\",\"homeAccountId\":\"309958ce-97c3-4c0e-8047-ba3931aef15f\",\"tenantId\":\"5d083b4e-4d2e-431c-adb7-fec97397a359\",\"clientId\":\"387f4ada-ea9b-4773-b5c3-ea5f54991738\",\"version\":\"{version}\"}}"; var buff = Encoding.UTF8.GetBytes(jsonWithVersion); var stream = new MemoryStream(buff, 0, buff.Length); var actRecord = AuthenticationRecord.Deserialize(stream); Assert.AreEqual(actRecord.Version, version); }
public void SerializeCancellationTokenCancelled() { CancellationTokenSource cts = new CancellationTokenSource(); cts.Cancel(); var expRecord = new AuthenticationRecord(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), Guid.NewGuid().ToString()); var stream = new MemoryStream(TestBufferSize); Assert.CatchAsync <OperationCanceledException>(async() => await expRecord.SerializeAsync(stream, cts.Token)); }
public UserMethod(HttpClient httpClient2) { _httpClient = httpClient2; _authenticationToken = new AuthenticationToken(_httpClient); Record = new AuthenticationRecord(); string directoryName = System.IO.Path.GetDirectoryName(FileAuthenticationRecord); if (!System.IO.Directory.Exists(directoryName)) { System.IO.Directory.CreateDirectory(directoryName); } }
public void AuthenticationRecordConstructor() { var record = new AuthenticationRecord(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), $"{Guid.NewGuid()}.{Guid.NewGuid()}", Guid.NewGuid().ToString(), Guid.NewGuid().ToString()); IAccount account = (AuthenticationAccount)record; Assert.NotNull(account.Username); Assert.NotNull(account.Environment); Assert.NotNull(account.HomeAccountId.Identifier); Assert.NotNull(account.HomeAccountId.ObjectId); Assert.NotNull(account.HomeAccountId.TenantId); }
private bool Authenticate(AuthenticationRecord authData) { User user; if (_unitOfWork.UsersRepository.CheckForUserByEmail(authData.Email) == false) { return(false); } else { user = _unitOfWork.UsersRepository.GetUserByEmail(authData.Email); } return(authData.PasswordHash == user.PasswordHash); }
public static async Task <TokenCredential> GetUserCredentialAsync() { if (!File.Exists(AUTH_RECORD_PATH)) { #region Snippet:Identity_ClientSideUserAuthentication_Persist_TokenCache var credential = new InteractiveBrowserCredential( new InteractiveBrowserCredentialOptions { TokenCachePersistenceOptions = new TokenCachePersistenceOptions() }); #endregion #region Snippet:Identity_ClientSideUserAuthentication_Persist_AuthRecord AuthenticationRecord authRecord = await credential.AuthenticateAsync(); using (var authRecordStream = new FileStream(AUTH_RECORD_PATH, FileMode.Create, FileAccess.Write)) { await authRecord.SerializeAsync(authRecordStream); } #endregion return(credential); } else { #region Snippet:Identity_ClientSideUserAuthentication_Persist_SilentAuth AuthenticationRecord authRecord; using (var authRecordStream = new FileStream(AUTH_RECORD_PATH, FileMode.Open, FileAccess.Read)) { authRecord = await AuthenticationRecord.DeserializeAsync(authRecordStream); } var credential = new InteractiveBrowserCredential( new InteractiveBrowserCredentialOptions { TokenCachePersistenceOptions = new TokenCachePersistenceOptions(), AuthenticationRecord = authRecord }); #endregion return(credential); } }
public async Task AuthenticateNoContext() { var tenantId = TestEnvironment.IdentityTenantId; var username = TestEnvironment.Username; var password = TestEnvironment.TestPassword; var options = Recording.InstrumentClientOptions(new TokenCredentialOptions()); var cred = InstrumentClient(new UsernamePasswordCredential(username, password, tenantId, ClientId, options)); AuthenticationRecord record = await cred.AuthenticateAsync(); Assert.IsNotNull(record); Assert.AreEqual(username, record.Username); Assert.AreEqual(tenantId, record.TenantId); }
protected override ValueTask <AuthenticationResult> AcquireTokenSilentCoreAsync( string[] scopes, string claims, AuthenticationRecord record, string tenantId, bool async, CancellationToken cancellationToken) { Func <string[], string, AuthenticationResult> factory = SilentAuthFactory ?? AuthFactory; if (factory != null) { return(new ValueTask <AuthenticationResult>(factory(scopes, tenantId))); } throw new NotImplementedException(); }
public SingleNoteWindowViewModel(Action <object> closeAction, Note note) { methods = new UserMethod(ConnectionApi.HttpClient); methods.PreparedAuthenticationRecord(); _authenticationRecord = methods.Record; Note = note; EditNoteCmd = new CommandHandler(EditNote); SaveNoteCmd = new CommandHandler(SaveNote); IsSaveButtonVisible = Visibility.Hidden; IsEditButtonVisible = Visibility.Visible; IsReadOnly = true; OnPropertyChanged(nameof(IsReadOnly)); OnPropertyChanged(nameof(IsSaveButtonVisible)); OnPropertyChanged(nameof(IsEditButtonVisible)); }
public async Task AuthenticateWithContext() { var tenantId = TestEnvironment.IdentityTenantId; var username = TestEnvironment.Username; var password = TestEnvironment.TestPassword; var options = InstrumentClientOptions(new TokenCredentialOptions()); var cred = InstrumentClient(new UsernamePasswordCredential(username, password, tenantId, ClientId, options)); AuthenticationRecord record = await cred.AuthenticateAsync(new TokenRequestContext(new[] { "https://vault.azure.net/.default" })); Assert.IsNotNull(record); Assert.AreEqual(username, record.Username); Assert.AreEqual(tenantId, record.TenantId); }
public async Task AuthenticateWithSharedTokenCacheAsync() { var cred = new InteractiveBrowserCredential(new InteractiveBrowserCredentialOptions { TokenCache = new PersistentTokenCache() }); // this should pop browser AuthenticationRecord record = await cred.AuthenticateAsync(); var cred2 = new InteractiveBrowserCredential(new InteractiveBrowserCredentialOptions { TokenCache = new PersistentTokenCache(), AuthenticationRecord = record }); // this should not pop browser AccessToken token = await cred2.GetTokenAsync(new TokenRequestContext(new string[] { "https://vault.azure.net/.default" })).ConfigureAwait(false); Assert.NotNull(token.Token); }
public void SerializeDeserialize() { var expRecord = new AuthenticationRecord(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), Guid.NewGuid().ToString()); byte[] buff = new byte[TestBufferSize]; var stream = new MemoryStream(buff); expRecord.Serialize(stream); stream = new MemoryStream(buff, 0, (int)stream.Position); var actRecord = AuthenticationRecord.Deserialize(stream); Assert.AreEqual(expRecord.Username, actRecord.Username); Assert.AreEqual(expRecord.Authority, actRecord.Authority); Assert.AreEqual(expRecord.HomeAccountId, actRecord.HomeAccountId); Assert.AreEqual(expRecord.TenantId, actRecord.TenantId); }
public static async Task Main() { InteractiveBrowserCredential credential; if (!File.Exists(AUTH_RECORD_PATH)) { credential = new InteractiveBrowserCredential( new InteractiveBrowserCredentialOptions { TokenCachePersistenceOptions = new TokenCachePersistenceOptions() }); AuthenticationRecord authRecord = await credential.AuthenticateAsync(); using (var authRecordStream = new FileStream(AUTH_RECORD_PATH, FileMode.Create, FileAccess.Write)) { await authRecord.SerializeAsync(authRecordStream); } } else { AuthenticationRecord authRecord; using (var authRecordStream = new FileStream(AUTH_RECORD_PATH, FileMode.Open, FileAccess.Read)) { authRecord = await AuthenticationRecord.DeserializeAsync(authRecordStream); } credential = new InteractiveBrowserCredential( new InteractiveBrowserCredentialOptions { TokenCachePersistenceOptions = new TokenCachePersistenceOptions(), AuthenticationRecord = authRecord }); } var client = new SecretClient(new Uri("https://myvault.azure.vaults.net/"), credential); }
/// <exception cref="WebApiClientException"></exception> public string GetAuthToken(AuthenticationRecord record) { return(GetAsyncTaskImpl(record)); }
public NoteApi(AuthenticationRecord authenticationRecord, string userId) { _authenticationRecord = authenticationRecord; _userId = userId; _noteMethod = new NoteMethod(ConnectionApi.HttpClient); }
public override ValueTask <AuthenticationResult> AcquireTokenSilentAsync(string[] scopes, AuthenticationRecord record, bool async, CancellationToken cancellationToken) { Func <string[], AuthenticationResult> factory = SilentAuthFactory ?? AuthFactory; if (factory != null) { return(new ValueTask <AuthenticationResult>(factory(scopes))); } throw new NotImplementedException(); }
public AndroidNoteApi(AuthenticationRecord authenticationRecord, string userId) { this._authenticationRecord = authenticationRecord; this._userId = userId; _androidNoteMethod = new NoteMethod(ConnectionApi.HttpClient); // TODO Change to android api }
static async Task Main(string[] args) { // var cred = new DefaultAzureCredential(); // var token = cred.GetTokenAsync( // new TokenRequestContext(scopes: new string[] { "your scope here" }) { } // ); // 1. Create TokenCredential object with TokenCachePersistenceOptions set var credentialOne = new InteractiveBrowserCredential( new InteractiveBrowserCredentialOptions { TokenCachePersistenceOptions = new TokenCachePersistenceOptions() { Name = "AuthenticationRecord.cache" } }); // 2. Prompt user to authenticate AuthenticationRecord authRecordWrite = await credentialOne.AuthenticateAsync(); // 3. Save AuthenticationRecord to disk using (var authRecordStreamWrite = new FileStream("AuthRecord.json", FileMode.Create, FileAccess.Write)) { await authRecordWrite.SerializeAsync(authRecordStreamWrite); } // A future user session where we want to silent auth with TokenCache and AuthenticationRecord // 4. Read the AuthenticationRecord from disk AuthenticationRecord authRecordRead; using (var authRecordStreamRead = new FileStream("AuthRecord.json", FileMode.Open, FileAccess.Read)) { authRecordRead = await AuthenticationRecord.DeserializeAsync(authRecordStreamRead); } // 5. Create TokenCredential object with TokenCache and use persisted AuthenticationRecord var credentialTwo = new InteractiveBrowserCredential( new InteractiveBrowserCredentialOptions { TokenCachePersistenceOptions = new TokenCachePersistenceOptions() { Name = "AuthenticationRecord.cache" }, AuthenticationRecord = authRecordRead }); // 5.1 Same as above but with DisableAutomaticAuthentication set to true // var credentialTwo = new InteractiveBrowserCredential( // new InteractiveBrowserCredentialOptions // { // TokenCachePersistenceOptions = new TokenCachePersistenceOptions() // { // Name = "AuthenticationRecord.cache" // }, // AuthenticationRecord = authRecordRead, // DisableAutomaticAuthentication = true // }); // 6. Use the new TokenCredential object. User will not be prompted to re-authenticate if token has expired. var client = new SecretClient(new Uri("https://memealyzerdevkv.vault.azure.net/"), credentialTwo); try { var secret = await client.GetSecretAsync("CosmosKey"); Console.WriteLine(secret.Value.Value); } catch (AuthenticationRequiredException ex) { Console.WriteLine("You set InteractiveBrowserCredentialOptions.DisableAutomaticAuthentication to true and the user token has expired or has been revoked."); Console.WriteLine(ex.ToString()); } }