public async Task <IActionResult> AuthenticateMicrosoft(MicrosoftAuthentication microsoftAuthentication) { var url = $"{_authenticationConfiguration.Microsoft.GraphBaseEndpoint}/v1.0/me"; var client = new HttpClient(); var defaultRequestHeaders = client.DefaultRequestHeaders; if (defaultRequestHeaders.Accept == null || !defaultRequestHeaders.Accept.Any(m => m.MediaType == "application/json")) { client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); } defaultRequestHeaders.Authorization = new AuthenticationHeaderValue("bearer", microsoftAuthentication.accessToken); HttpResponseMessage response = await client.GetAsync(url); if (response.IsSuccessStatusCode) { string json = await response.Content.ReadAsStringAsync(); JObject result = JsonConvert.DeserializeObject(json) as JObject; var firstName = result["givenName"].Value <string>(); var lastName = result["surname"].Value <string>(); var email = result["mail"].Value <string>(); if (string.IsNullOrEmpty(email)) { email = result["userPrincipalName"].Value <string>(); } var user = await _userRepository.GetUser(email); if (user == null) { user = new User() { Email = email, FirstName = firstName, LastName = lastName, AllowEmailNotifications = true, UsesMicrosoftAuth = true }; await _userRepository.InsertUser(user); } else if (!user.UsesMicrosoftAuth) { user.UsesMicrosoftAuth = true; await _userRepository.UpdateUser(user); } Response.SendNewToken(await _authenticationService.IssueJwtToUser(user.Id)); return(Ok()); } else { return(Forbid()); } }
/// <summary> /// Sprawdza czy provider Microsoft zapisuje się i wczytuje, po czym go usuwa /// </summary> public void SaveProvider_SavesProvider_MicrosoftLoadsCorectly() { //Arrange AuthenticationProvider provider = AuthenticationProvider.Microsoft; MicrosoftAuthentication authentication = new MicrosoftAuthentication(); SettingsManager settingsManager = new SettingsManager(); //Act settingsManager.SaveProvider(provider); //Assert Assert.AreEqual(settingsManager.LoadProvider(), provider.ToString()); //Cleanup settingsManager.DeleteProvider(); }
public async System.Threading.Tasks.Task MicrosoftAuthentication_GetAccessTokenAsync_NoInteraction_ThrowsException() { const string authority = "https://login.microsoftonline.com/common"; const string clientId = "C9E8FDA6-1D46-484C-917C-3DBD518F27C3"; Uri redirectUri = new Uri("https://localhost"); const string resource = "https://graph.microsoft.com"; Uri remoteUri = new Uri("https://example.com"); const string userName = null; // No user to ensure we do not use an existing token var context = new TestCommandContext { Settings = { IsInteractionAllowed = false }, }; var msAuth = new MicrosoftAuthentication(context); await Assert.ThrowsAsync <InvalidOperationException>( () => msAuth.GetAccessTokenAsync(authority, clientId, redirectUri, resource, remoteUri, userName)); }
public static void Main(string[] args) { string appPath = ApplicationBase.GetEntryApplicationPath(); using (var context = new CommandContext(appPath)) using (var app = new Application(context)) { // Workaround for https://github.com/AzureAD/microsoft-authentication-library-for-dotnet/issues/2560 if (MicrosoftAuthentication.CanUseBroker(context)) { try { MicrosoftAuthentication.InitializeBroker(); } catch (Exception ex) { context.Streams.Error.WriteLine( "warning: broker initialization failed{0}{1}", Environment.NewLine, ex.Message ); } } // Register all supported host providers at the normal priority. // The generic provider should never win against a more specific one, so register it with low priority. app.RegisterProvider(new AzureReposHostProvider(context), HostProviderPriority.Normal); app.RegisterProvider(new BitbucketHostProvider(context), HostProviderPriority.Normal); app.RegisterProvider(new GitHubHostProvider(context), HostProviderPriority.Normal); app.RegisterProvider(new GitLabHostProvider(context), HostProviderPriority.Normal); app.RegisterProvider(new GenericHostProvider(context), HostProviderPriority.Low); int exitCode = app.RunAsync(args) .ConfigureAwait(false) .GetAwaiter() .GetResult(); Environment.Exit(exitCode); } }
protected override async Task <bool> RunInternalAsync(StringBuilder log, IList <string> additionalFiles) { if (MicrosoftAuthentication.CanUseBroker(_context)) { log.Append("Checking broker initialization state..."); if (MicrosoftAuthentication.IsBrokerInitialized) { log.AppendLine(" Initialized"); } else { log.AppendLine(" Not initialized"); log.Append("Initializing broker..."); MicrosoftAuthentication.InitializeBroker(); log.AppendLine("OK"); } } else { log.AppendLine("Broker not supported."); } var msAuth = new MicrosoftAuthentication(_context); log.AppendLine($"Flow type is: {msAuth.GetFlowType()}"); log.Append("Gathering MSAL token cache data..."); StorageCreationProperties cacheProps = msAuth.CreateTokenCacheProps(true); log.AppendLine(" OK"); log.AppendLine($"CacheDirectory: {cacheProps.CacheDirectory}"); log.AppendLine($"CacheFileName: {cacheProps.CacheFileName}"); log.AppendLine($"CacheFilePath: {cacheProps.CacheFilePath}"); if (PlatformUtils.IsMacOS()) { log.AppendLine($"MacKeyChainAccountName: {cacheProps.MacKeyChainAccountName}"); log.AppendLine($"MacKeyChainServiceName: {cacheProps.MacKeyChainServiceName}"); } else if (PlatformUtils.IsLinux()) { log.AppendLine($"KeyringCollection: {cacheProps.KeyringCollection}"); log.AppendLine($"KeyringSchemaName: {cacheProps.KeyringSchemaName}"); log.AppendLine($"KeyringSecretLabel: {cacheProps.KeyringSecretLabel}"); log.AppendLine($"KeyringAttribute1: ({cacheProps.KeyringAttribute1.Key},{cacheProps.KeyringAttribute1.Value})"); log.AppendLine($"KeyringAttribute2: ({cacheProps.KeyringAttribute2.Key},{cacheProps.KeyringAttribute2.Value})"); } log.Append("Creating cache helper..."); var cacheHelper = await MsalCacheHelper.CreateAsync(cacheProps); log.AppendLine(" OK"); try { log.Append("Verifying MSAL token cache persistence..."); cacheHelper.VerifyPersistence(); log.AppendLine(" OK"); } catch (Exception) { log.AppendLine(" Failed"); throw; } return(true); }
public App() { MSAuth = new MicrosoftAuthentication(AuthSettings); }