Exemplo n.º 1
0
        public void SaveApp(AzureApp app)
        {
            var targetApp = azureAppDbContext.AzureApps.Include(_app => _app.tokenRequests).FirstOrDefault(_app => _app.ClientId == app.ClientId);

            targetApp.AppName     = app.AppName;
            targetApp.RedirectURL = app.RedirectURL;
            if (app is ServerAzureApp)
            {
                ((ServerAzureApp)targetApp).Secret = ((ServerAzureApp)app).Secret;
            }

            foreach (var req in app.tokenRequests)
            {
                var tagetRequest = targetApp.tokenRequests.FirstOrDefault(_req => _req.Resource == req.Resource && _req.SignInUserName == req.SignInUserName);
                if (tagetRequest == null)
                {
                    req.App = null;
                    targetApp.tokenRequests.Add(req);
                }
                else
                {
                    if (!tagetRequest.AccessToken.Equals(req.AccessToken))
                    {
                        tagetRequest.AccessToken = req.AccessToken;
                    }
                    if (!tagetRequest.RefreshToken.Equals(req.RefreshToken))
                    {
                        tagetRequest.RefreshToken = req.RefreshToken;
                    }
                }
            }

            azureAppDbContext.SaveChanges();
        }
Exemplo n.º 2
0
        public async Task TestRegAppAsync()
        {
            string          testResultPath  = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "ApiResults", "ValidApplicationResult.json");
            string          json            = File.ReadAllText(testResultPath);
            var             mocks           = Utils.CreateDefaultGraphApiMock(json);
            BotDbContext    db              = Utils.CreateMemoryDbContext();
            DefaultGraphApi defaultGraphApi = new DefaultGraphApi(db, mocks.Item1, mocks.Item2);

            BindHandler bindHandler = new BindHandler(db, defaultGraphApi);

            long   userId       = 123456;
            string userName     = "******";
            string email        = "*****@*****.**";
            Guid   clientId     = Guid.NewGuid();
            string clientSecret = "741852963";
            string appName      = "app1";

            await bindHandler.RegAppAsync(userId, userName, email, clientId.ToString(), clientSecret, appName);

            await db.DisposeAsync();

            db = Utils.CreateMemoryDbContext();
            AzureApp azureApp = await db.AzureApps.Include(azureApp => azureApp.TelegramUser).FirstAsync();

            Assert.AreEqual(userId, azureApp.TelegramUserId);
            Assert.AreEqual(userName, azureApp.TelegramUser.UserName);
            Assert.AreEqual(email, azureApp.Email);
            Assert.AreEqual(clientId, azureApp.Id);
            Assert.AreEqual(clientSecret, azureApp.Secrets);
            Assert.AreEqual(appName, azureApp.Name);
        }
Exemplo n.º 3
0
        private void StartConsentFlow(string loginEndPoint, AzureApp azureApp, string redirectUri, string token, HttpClient httpClient, PSObject record, CmdletMessageWriter messageWriter, List <PermissionScope> scopes)
        {
            Host.UI.WriteLine(ConsoleColor.Yellow, Host.UI.RawUI.BackgroundColor, $"Starting consent flow.");

            var resource = scopes.FirstOrDefault(s => s.resourceAppId == PermissionScopes.ResourceAppId_Graph) != null ? "https://graph.microsoft.com/.default" : "https://microsoft.sharepoint-df.com/.default";

            var consentUrl = $"{loginEndPoint}/{Tenant}/v2.0/adminconsent?client_id={azureApp.AppId}&scope={resource}&redirect_uri={redirectUri}";


            if (OperatingSystem.IsWindows() && !NoPopup)
            {
                var waitTime = 60;
                CmdletMessageWriter.WriteFormattedWarning(this, $"Waiting {waitTime} seconds to launch the consent flow in a popup window.\n\nThis wait is required to make sure that Azure AD is able to initialize all required artifacts. You can always navigate to the consent page manually:\n\n{consentUrl}");

                for (var i = 0; i < waitTime; i++)
                {
                    if (Convert.ToDouble(i) % Convert.ToDouble(10) > 0)
                    {
                        Host.UI.Write(ConsoleColor.Yellow, Host.UI.RawUI.BackgroundColor, "-");
                    }
                    else
                    {
                        Host.UI.Write(ConsoleColor.Yellow, Host.UI.RawUI.BackgroundColor, $"[{i}]");
                    }
                    System.Threading.Thread.Sleep(1000);

                    // Check if CTRL+C has been pressed and if so, abort the wait
                    if (Stopping)
                    {
                        break;
                    }
                }

                if (!Stopping)
                {
                    Host.UI.WriteLine(ConsoleColor.Yellow, Host.UI.RawUI.BackgroundColor, $"[{waitTime}]");

                    Host.UI.WriteLine();

                    if (ParameterSpecified(nameof(Interactive)))
                    {
                        using (var authManager = AuthenticationManager.CreateWithInteractiveLogin(azureApp.AppId, (url, port) =>
                        {
                            BrowserHelper.OpenBrowserForInteractiveLogin(url, port, true, cancellationTokenSource);
                        }, Tenant, "You successfully provided consent", "You failed to provide consent.", AzureEnvironment))
                        {
                            authManager.GetAccessToken(resource, Microsoft.Identity.Client.Prompt.Consent);
                        }
                    }
                    else
                    {
                        BrowserHelper.GetWebBrowserPopup(consentUrl, "Please provide consent", new[] { ("https://pnp.github.io/powershell/consent.html", BrowserHelper.UrlMatchType.StartsWith) }, cancellationTokenSource: cancellationTokenSource, cancelOnClose: false);
Exemplo n.º 4
0
        //private void btnModifyApp_Click(object sender, EventArgs e)
        //{
        //    string clientId = ((AzureApp)listApps.SelectedItem).ClientId;
        //    AppsEdit formEdit = new AppsEdit(clientId);
        //    ShowFormBeside(this, formEdit);

        //}

        private void btnDelegateToken_Click(object sender, EventArgs e)
        {
            string           clientId         = ((AzureApp)listApps.SelectedItem).ClientId;
            AzureApp         app              = dataService.GetApp(clientId);
            TokenRequest     tokenRequest     = new TokenRequest(app, lstResrouce.Text, lstUsers.Text);
            TokenRequestHelp tokenRequestHelp = new TokenRequestHelp(tokenRequest);

            tokenRequestHelp.Send("https://login.microsoftonline.com");
            dataService.SaveApp(app);

            RefreshTokenControlUI();
            MessageBox.Show(tokenRequest.AccessToken);
        }
Exemplo n.º 5
0
        public void DeleteApp(string clientId)
        {
            AzureApp findApp = null;

            foreach (var app in apps)
            {
                if (app.ClientId.Equals(clientId))
                {
                    findApp = app;
                }
            }
            if (findApp == null)
            {
                throw new Exception("No app found!");
            }
            else
            {
                apps.Remove(findApp);
                SaveChanges();
            }
        }
Exemplo n.º 6
0
        public void SaveApp(AzureApp app)
        {
            foreach (var oldApp in apps)
            {
                if (oldApp.ClientId == app.ClientId)
                {
                    oldApp.AppName     = app.AppName;
                    oldApp.RedirectURL = app.RedirectURL;
                    if (oldApp.Type == app.Type && (app is ServerAzureApp))
                    {
                        ((ServerAzureApp)oldApp).Secret = ((ServerAzureApp)app).Secret;
                    }
                    else
                    {
                        DeleteApp(app.ClientId);
                        AddApp(app);
                    }
                }
            }

            SaveChanges();
        }
Exemplo n.º 7
0
        /// <summary>
        /// 查詢已註冊的 azure 應用程式
        ///
        /// 列出應用程式詳細訊息
        /// </summary>
        /// <param name="callbackQuery"> Telegram callbackQuery object </param>
        /// <returns></returns>
        private async Task QueryAppCallback(CallbackQuery callbackQuery)
        {
            AzureApp app = await telegramHandler.GetAppInfoAsync(callbackQuery.Data);

            string text = "查無此應用程式";

            if (app != null)
            {
                string[] infos = new string[] {
                    $"應用程式 (用戶端) 識別碼: {app.Id}",
                    $"應用程式別名: {app.Name}",
                    $"Client secrets: {app.Secrets}",
                    $"註冊應用程式使用的信箱: {app.Email}",
                    $"註冊應用程式時間: {app.RegTime}"
                };

                text = string.Join('\n', infos);
            }

            await botClient.SendTextMessageAsync(
                chatId : callbackQuery.From.Id,
                text : text);
        }
Exemplo n.º 8
0
        private void StartConsentFlow(string loginEndPoint, AzureApp azureApp, string redirectUri, string token, HttpClient httpClient, PSObject record)
        {
            var consentUrl = $"{loginEndPoint}/{Tenant}/v2.0/adminconsent?client_id={azureApp.AppId}&scope=https://microsoft.sharepoint-df.com/.default&redirect_uri={redirectUri}";


            if (OperatingSystem.IsWindows() && !NoPopup)
            {
                var waitTime = 60;
                CmdletMessageWriter.WriteFormattedWarning(this, $"Waiting {waitTime} seconds to launch consent flow in a popup window.\n\nThis wait is required to make sure that Azure AD is able to initialize all required artifacts. You can always navigate to the consent page manually:\n\n{consentUrl}");

                for (var i = 0; i < waitTime; i++)
                {
                    if (Convert.ToDouble(i) % Convert.ToDouble(10) > 0)
                    {
                        Host.UI.Write(ConsoleColor.Yellow, Host.UI.RawUI.BackgroundColor, "-");
                    }
                    else
                    {
                        Host.UI.Write(ConsoleColor.Yellow, Host.UI.RawUI.BackgroundColor, $"[{i}]");
                    }
                    System.Threading.Thread.Sleep(1000);

                    // Check if CTRL+C has been pressed and if so, abort the wait
                    if (Stopping)
                    {
                        break;
                    }
                }

                if (!Stopping)
                {
                    Host.UI.WriteLine(ConsoleColor.Yellow, Host.UI.RawUI.BackgroundColor, $"[{waitTime}]");

                    Host.UI.WriteLine();

                    BrowserHelper.GetWebBrowserPopup(consentUrl, "Please provide consent", new[] { (redirectUri, BrowserHelper.UrlMatchType.StartsWith) });
Exemplo n.º 9
0
        public AppsEdit(string clientId)
        {
            InitializeComponent();

            AzureApp app = dataService.GetApp(clientId);

            comboType.DataSource = Enum.GetValues(typeof(AzureAppType)).Cast <AzureAppType>();

            txtAppName.Text     = app.AppName;
            txtClientId.Text    = app.ClientId;
            txtRedirectURL.Text = app.RedirectURL;

            if (app.Type == AzureAppType.client)
            {
                lblSecret.Visible      = false;
                txtSecret.Visible      = false;
                comboType.SelectedItem = AzureAppType.client;
            }
            else
            {
                comboType.SelectedItem = AzureAppType.Server;
                txtSecret.Text         = ((ServerAzureApp)app).Secret;
            }
        }
 public GraphServiceClientProvider(IOptions <AppSettings> settings)
 {
     _azureAppSettings = settings.Value.AzureApp;
 }
Exemplo n.º 11
0
 public Authorize(IOptions <AppSettings> settings)
 {
     _settings = settings.Value.AzureApp;
 }
 public OAuthMessageHandler(AzureApp azureAppSettings, HttpMessageHandler innerHandler) : base(innerHandler)
 {
     _azureAppSettings = azureAppSettings;
 }
 public HttpClientProvider(IOptions <AppSettings> settings)
 {
     _azureAppSettings = settings.Value.AzureApp;
 }
Exemplo n.º 14
0
 public void AddApp(AzureApp app)
 {
     azureAppDbContext.AzureApps.Add(app);
     azureAppDbContext.SaveChanges();
 }
Exemplo n.º 15
0
        public void AddApp(AzureApp app)
        {
            apps.Add(app);

            SaveChanges();
        }