Compare commits

...
3 Commits
Author SHA1 Message Date
serega404 2c4fccb22d feat: улучшил обработку загрузки страницы
Create and publish a Docker image / Publish image (push) Successful in 10s
2026-10-12 14:13:51 +03:00
serega404 f5d5b0f68f feat: обновил Dockerfile и добавил проверку для работы в контейнере
Create and publish a Docker image / Publish image (push) Successful in 2m48s
2026-10-12 13:46:08 +03:00
serega404 7e27b0742b feat: обновил зависимости и улучшил поддержку MFA в MicrosoftLoginHelper
Create and publish a Docker image / Publish image (push) Successful in 5m27s
2026-10-12 13:35:51 +03:00
6 changed files with 100 additions and 25 deletions

No files matched your search

+15
View File
@@ -0,0 +1,15 @@
# Default ignored files
/shelf/
/workspace.xml
# Editor-based HTTP Client requests
/httpRequests/
# Rider ignored files
/modules.xml
/contentModel.xml
/projectSettingsUpdater.xml
/.idea.ModeusSchedule.MSAuth.iml
# Ignored default folder with query files
/queries/
# Datasource local storage ignored files
/dataSources/
/dataSources.local.xml
+1 -1
View File
@@ -1,7 +1,7 @@
# Макросервис авторизации в Modeus через Microsoft
[![MIT License](https://img.shields.io/badge/License-MIT-green.svg)](LICENSE)
[![.NET](https://img.shields.io/badge/.NET-9.0-blue.svg)](https://dotnet.microsoft.com/download/dotnet/9.0)
[![.NET](https://img.shields.io/badge/.NET-10.0-blue.svg)](https://dotnet.microsoft.com/download/dotnet/10.0)
## Зачем нужен этот сервис
+31 -5
View File
@@ -1,5 +1,4 @@
using System.Text.RegularExpressions;
using Microsoft.Extensions.Logging;
using Microsoft.Playwright;
namespace ModeusSchedule.MSAuth.BrowserScripts;
@@ -17,11 +16,14 @@ public static class MicrosoftLoginHelper
{
logger.LogInformation("Начало входа в Microsoft. Url: {LoginUrl}, пользователь: {Username}", loginUrl, username);
await page.GotoAsync(loginUrl, new PageGotoOptions { WaitUntil = WaitUntilState.DOMContentLoaded });
// Готовность формы проверяем ниже по полям: сторонние скрипты могут задерживать DOMContentLoaded.
await page.GotoAsync(loginUrl, new PageGotoOptions { WaitUntil = WaitUntilState.Commit });
logger.LogDebug("Страница логина загружена, ожидаем переход на домен Microsoft.");
logger.LogDebug("Началась загрузка страницы логина, ожидаем переход на домен Microsoft.");
await page.WaitForURLAsync(new Regex("login\\.(microsoftonline|live)\\.com", RegexOptions.IgnoreCase), new PageWaitForURLOptions { Timeout = 60_000 });
// WaitForURL при уже совпавшем URL дополнительно ожидает событие загрузки страницы.
await page.WaitForFunctionAsync(@"() => /^login\.(microsoftonline|live)\.com$/i.test(location.hostname)",
options: new PageWaitForFunctionOptions { Timeout = 60_000 });
var useAnotherAccount = page.Locator("div#otherTile, #otherTileText, div[data-test-id='useAnotherAccount']").First;
try
@@ -36,7 +38,7 @@ public static class MicrosoftLoginHelper
}
var emailInput = page.Locator("input[name='loginfmt'], input#i0116");
await emailInput.WaitForAsync(new LocatorWaitForOptions { State = WaitForSelectorState.Visible, Timeout = 30_000 });
await emailInput.WaitForAsync(new LocatorWaitForOptions { State = WaitForSelectorState.Visible, Timeout = 60_000 });
logger.LogDebug("Поле ввода email найдено, вводим логин.");
await emailInput.FillAsync(username);
@@ -122,6 +124,30 @@ public static class MicrosoftLoginHelper
#endregion
// Microsoft может предложить добавить еще один способ проверки после успешного MFA.
// Ссылка определяется по адресу, чтобы обработка не зависела от языка страницы.
var skipMfaRegistration = page.Locator("a[href*='skipmfaregistration=1']").First;
var canSkipMfaRegistration = false;
try
{
await skipMfaRegistration.WaitForAsync(new()
{
State = WaitForSelectorState.Visible,
Timeout = 8_000
});
canSkipMfaRegistration = true;
}
catch (TimeoutException)
{
logger.LogDebug("Предложение настроить дополнительный способ MFA не появилось — пропускаем шаг.");
}
if (canSkipMfaRegistration)
{
logger.LogInformation("Откладываем настройку дополнительного способа MFA.");
await skipMfaRegistration.ClickAsync();
}
await page.WaitForSelectorAsync("button, input[type='submit'], a", new PageWaitForSelectorOptions { Timeout = 8000 });
var locator = page.Locator("#idSIButton9, #idBtn_Back").First;
+21 -16
View File
@@ -1,24 +1,29 @@
FROM mcr.microsoft.com/dotnet/sdk:9.0-alpine3.22 AS build
ARG BUILD_CONFIGURATION=Release
FROM mcr.microsoft.com/dotnet/sdk:10.0-noble AS restore
WORKDIR /src
COPY . .
RUN dotnet restore "ModeusSchedule.MSAuth.csproj"
RUN dotnet publish "ModeusSchedule.MSAuth.csproj" -c $BUILD_CONFIGURATION -o /app/publish /p:UseAppHost=false
COPY ModeusSchedule.MSAuth.csproj .
RUN dotnet restore "ModeusSchedule.MSAuth.csproj" && \
set -- /root/.nuget/packages/microsoft.playwright/*/.playwright && \
test "$#" -eq 1 && \
mkdir -p /opt/playwright/node && \
cp -a "$1/package" /opt/playwright/ && \
cp -a "$1/node/linux-x64" /opt/playwright/node/ && \
cp -a "$1/node/LICENSE" /opt/playwright/node/ && \
chmod +x /opt/playwright/node/linux-x64/node
FROM mcr.microsoft.com/dotnet/aspnet:9.0 AS final
FROM restore AS build
ARG BUILD_CONFIGURATION=Release
COPY . .
RUN dotnet publish "ModeusSchedule.MSAuth.csproj" -c "$BUILD_CONFIGURATION" --no-restore -o /app/publish /p:UseAppHost=false && \
rm -rf /app/publish/.playwright /app/publish/playwright.ps1
FROM mcr.microsoft.com/dotnet/aspnet:10.0-noble AS final
EXPOSE 8080
WORKDIR /app
RUN apt-get update && \
apt-get install -y --no-install-recommends wget && \
wget -q https://github.com/PowerShell/PowerShell/releases/download/v7.5.2/powershell_7.5.2-1.deb_amd64.deb && \
apt-get install -y ./powershell_7.5.2-1.deb_amd64.deb && \
rm -f powershell_7.5.2-1.deb_amd64.deb && \
rm -rf /var/lib/apt/lists/*
ENV PLAYWRIGHT_BROWSERS_PATH=/ms-playwright
COPY --from=build /app/publish .
RUN pwsh ./playwright.ps1 install --with-deps chromium
COPY --from=restore /opt/playwright ./.playwright
RUN ./.playwright/node/linux-x64/node ./.playwright/package/cli.js install --with-deps --only-shell chromium && \
rm -rf /var/lib/apt/lists/*
COPY --from=build /app/publish .
ENTRYPOINT ["dotnet", "ModeusSchedule.MSAuth.dll"]
+2 -2
View File
@@ -1,13 +1,13 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net9.0</TargetFramework>
<TargetFramework>net10.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Playwright" Version="1.48.0" />
<PackageReference Include="Microsoft.Playwright" Version="1.63.0" />
</ItemGroup>
</Project>
+30 -1
View File
@@ -1,3 +1,4 @@
using System.Collections.Concurrent;
using System.Diagnostics;
using System.Text.Json;
using Microsoft.Playwright;
@@ -50,6 +51,19 @@ public class MicrosoftAuthService(ILogger<MicrosoftAuthService> logger, IConfigu
ViewportSize = null
});
var page = await context.NewPageAsync();
var pendingRequests = new ConcurrentDictionary<IRequest, byte>();
EventHandler<IRequest> requestStarted = (_, request) => pendingRequests.TryAdd(request, 0);
EventHandler<IRequest> requestFinished = (sender, request) => pendingRequests.TryRemove(request, out _);
EventHandler<IRequest> requestFailed = (sender, request) =>
{
pendingRequests.TryRemove(request, out _);
if (request.Failure == "net::ERR_ABORTED") return;
logger.LogWarning("Ошибка загрузки ресурса браузером. Домен: {Host}, тип: {ResourceType}, причина: {Failure}",
new Uri(request.Url).Host, request.ResourceType, request.Failure);
};
page.Request += requestStarted;
page.RequestFinished += requestFinished;
page.RequestFailed += requestFailed;
try
{
@@ -80,11 +94,20 @@ public class MicrosoftAuthService(ILogger<MicrosoftAuthService> logger, IConfigu
}
catch (Exception ex) when (ex is not MicrosoftAuthInProgressException)
{
logger.LogError(ex, "Ошибка при получении JWT через Microsoft авторизацию");
logger.LogError(ex, "Ошибка при получении JWT через Microsoft авторизацию. Текущий домен браузера: {Host}",
page.Url == "about:blank" ? "about:blank" : new Uri(page.Url).Host);
if (!pendingRequests.IsEmpty)
{
var resources = pendingRequests.Keys.Select(request => $"{new Uri(request.Url).Host} ({request.ResourceType})").Distinct();
logger.LogWarning("Незавершенные запросы браузера: {Resources}", string.Join(", ", resources));
}
throw;
}
finally
{
page.Request -= requestStarted;
page.RequestFinished -= requestFinished;
page.RequestFailed -= requestFailed;
await context.CloseAsync();
await browser.CloseAsync();
@@ -123,6 +146,12 @@ public class MicrosoftAuthService(ILogger<MicrosoftAuthService> logger, IConfigu
try
{
if (_browsersEnsured) return;
if (string.Equals(Environment.GetEnvironmentVariable("DOTNET_RUNNING_IN_CONTAINER"), "true", StringComparison.OrdinalIgnoreCase))
{
// В Docker браузер и его зависимости уже установлены при сборке образа.
_browsersEnsured = true;
return;
}
try
{
// Устанавливаем Chromium, если не установлен