У меня есть устаревшее приложение ASP.NET 4.8 MVC, которое переносится для использования проверки подлинности Azure AD с использованием платформы Microsoft.Owin. Конфигурация приложения отлично работает на моем локальном компьютере. Однако я сталкиваюсь с проблемами при запуске его на рабочем сервере.
Настройка прокси-сервера производственной среды: приложение размещается на сервере IIS за прокси-сервером. SSL завершается на прокси-сервере, а HTTP-запросы перенаправляются на сервер IIS.
Когда я просматриваю защищенные страницы на рабочем сервере, я правильно перенаправляюсь на вход в систему login.microsoftonline.com. страницу и можете успешно войти в систему. Однако после входа в систему файл cookie аутентификации .AspNet.Cookies не устанавливается на рабочем сервере, что приводит к возникновению цикла перенаправления между приложением и конечной точкой Azure AD /authorize.
Я предполагая, что существует проблема с выдачей файла cookie «.AspNet.Cookies», поскольку я не вижу этого в своем браузере. Как это можно подтвердить? или отслеживается?
Вот как это настраивается в классе start.cs. Я следил за какой-то онлайн-статьей, чтобы реализовать это, и у меня все работает нормально.
public void Configuration(IAppBuilder app)
{
// Configure Auth0 parameters
string auth0Domain = ConfigurationManager.AppSettings["auth0:Domain"];
string auth0ClientId = ConfigurationManager.AppSettings["auth0:ClientId"];
string auth0RedirectUri = ConfigurationManager.AppSettings["auth0:RedirectUri"];
string auth0PostLogoutRedirectUri = ConfigurationManager.AppSettings["auth0:PostLogoutRedirectUri"];
// Set Cookies as default authentication type
app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = CookieAuthenticationDefaults.AuthenticationType,
LoginPath = new PathString("/Account/Login"),
CookieSameSite = Microsoft.Owin.SameSiteMode.None,
// More information on why the CookieManager needs to be set can be found here:
// https://github.com/aspnet/AspNetKatana/ ... ion-issues
CookieManager = new SameSiteCookieManager(new SystemWebCookieManager())
});
// Configure Auth0 authentication
app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
{
AuthenticationType = "Auth0",
Authority = auth0Domain,
ClientId = auth0ClientId,
RedirectUri = auth0RedirectUri,
PostLogoutRedirectUri = auth0PostLogoutRedirectUri,
ResponseType = OpenIdConnectResponseType.CodeIdToken,
Scope = "openid profile email",
SignInAsAuthenticationType = CookieAuthenticationDefaults.AuthenticationType,
TokenValidationParameters = new TokenValidationParameters
{
NameClaimType = "name"
},
// More information on why the CookieManager needs to be set can be found here:
// https://docs.microsoft.com/en-us/aspnet ... n-samesite
CookieManager = new SameSiteCookieManager(new SystemWebCookieManager()),
Notifications = new OpenIdConnectAuthenticationNotifications
{
AuthorizationCodeReceived = async n =>
{
var client = new HttpClient();
var tokenResponse = await client.RequestAuthorizationCodeTokenAsync(new AuthorizationCodeTokenRequest
{
Code = n.Code,
Address = "https://login.microsoftonline.com/2d55c ... v2.0/token",
ClientId = auth0ClientId,
ClientSecret = "WLT8Q~KKe2S5k~XrzUsz-XJUiRPdgaiBAx1uYcnr",
RedirectUri = auth0RedirectUri,
});
if (tokenResponse.IsError)
throw new Exception(tokenResponse.Error);
var response = await client.GetUserInfoAsync(new UserInfoRequest
{
Token = tokenResponse.AccessToken,
Address = "https://graph.microsoft.com/oidc/userinfo",
});
if (response.IsError)
throw new Exception(response.Error);
n.AuthenticationTicket.Identity.AddClaims(response.Claims);
},
RedirectToIdentityProvider = notification =>
{
if (notification.ProtocolMessage.RequestType == OpenIdConnectRequestType.Authentication)
{
}
if (notification.ProtocolMessage.RequestType == OpenIdConnectRequestType.Logout)
{
var logoutUri = $"https://{auth0Domain}/v2/logout?client_id={auth0ClientId}";
var postLogoutUri = notification.ProtocolMessage.PostLogoutRedirectUri;
if (!string.IsNullOrEmpty(postLogoutUri))
{
if (postLogoutUri.StartsWith("/"))
{
// transform to absolute
var request = notification.Request;
postLogoutUri = request.Scheme + "://" + request.Host + request.PathBase + postLogoutUri;
}
logoutUri += $"&returnTo={Uri.EscapeDataString(postLogoutUri)}";
}
notification.Response.Redirect(logoutUri);
notification.HandleResponse();
}
return Task.FromResult(0);
}
}
});
}
Как я могу убедиться, что файл cookie .AspNet.Cookies установлен правильно на рабочем сервере?
Нужны ли дополнительные конфигурации для обработки завершения SSL при прокси?
Изменить: добавлен файл web.config
Подробнее здесь: https://stackoverflow.com/questions/785 ... xy-missing
Проблема аутентификации Azure AD с приложением ASP.NET MVC за прокси-сервером: отсутствует файл cookie .AspNet.Cookies ⇐ C#
Место общения программистов C#
1716652054
Anonymous
У меня есть устаревшее приложение ASP.NET 4.8 MVC, которое переносится для использования проверки подлинности Azure AD с использованием платформы Microsoft.Owin. Конфигурация приложения отлично работает на моем локальном компьютере. Однако я сталкиваюсь с проблемами при запуске его на рабочем сервере.
Настройка прокси-сервера производственной среды: приложение размещается на сервере IIS за прокси-сервером. SSL завершается на прокси-сервере, а HTTP-запросы перенаправляются на сервер IIS.
Когда я просматриваю защищенные страницы на рабочем сервере, я правильно перенаправляюсь на вход в систему login.microsoftonline.com. страницу и можете успешно войти в систему. Однако после входа в систему файл cookie аутентификации .AspNet.Cookies не устанавливается на рабочем сервере, что приводит к возникновению цикла перенаправления между приложением и конечной точкой Azure AD /authorize.
Я предполагая, что существует проблема с выдачей файла cookie «.AspNet.Cookies», поскольку я не вижу этого в своем браузере. Как это можно подтвердить? или отслеживается?
Вот как это настраивается в классе start.cs. Я следил за какой-то онлайн-статьей, чтобы реализовать это, и у меня все работает нормально.
public void Configuration(IAppBuilder app)
{
// Configure Auth0 parameters
string auth0Domain = ConfigurationManager.AppSettings["auth0:Domain"];
string auth0ClientId = ConfigurationManager.AppSettings["auth0:ClientId"];
string auth0RedirectUri = ConfigurationManager.AppSettings["auth0:RedirectUri"];
string auth0PostLogoutRedirectUri = ConfigurationManager.AppSettings["auth0:PostLogoutRedirectUri"];
// Set Cookies as default authentication type
app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = CookieAuthenticationDefaults.AuthenticationType,
LoginPath = new PathString("/Account/Login"),
CookieSameSite = Microsoft.Owin.SameSiteMode.None,
// More information on why the CookieManager needs to be set can be found here:
// https://github.com/aspnet/AspNetKatana/wiki/System.Web-response-cookie-integration-issues
CookieManager = new SameSiteCookieManager(new SystemWebCookieManager())
});
// Configure Auth0 authentication
app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
{
AuthenticationType = "Auth0",
Authority = auth0Domain,
ClientId = auth0ClientId,
RedirectUri = auth0RedirectUri,
PostLogoutRedirectUri = auth0PostLogoutRedirectUri,
ResponseType = OpenIdConnectResponseType.CodeIdToken,
Scope = "openid profile email",
SignInAsAuthenticationType = CookieAuthenticationDefaults.AuthenticationType,
TokenValidationParameters = new TokenValidationParameters
{
NameClaimType = "name"
},
// More information on why the CookieManager needs to be set can be found here:
// https://docs.microsoft.com/en-us/aspnet/samesite/owin-samesite
CookieManager = new SameSiteCookieManager(new SystemWebCookieManager()),
Notifications = new OpenIdConnectAuthenticationNotifications
{
AuthorizationCodeReceived = async n =>
{
var client = new HttpClient();
var tokenResponse = await client.RequestAuthorizationCodeTokenAsync(new AuthorizationCodeTokenRequest
{
Code = n.Code,
Address = "https://login.microsoftonline.com/2d55c52b-2865-45c0-b174-fef7eed8e331/oauth2/v2.0/token",
ClientId = auth0ClientId,
ClientSecret = "WLT8Q~KKe2S5k~XrzUsz-XJUiRPdgaiBAx1uYcnr",
RedirectUri = auth0RedirectUri,
});
if (tokenResponse.IsError)
throw new Exception(tokenResponse.Error);
var response = await client.GetUserInfoAsync(new UserInfoRequest
{
Token = tokenResponse.AccessToken,
Address = "https://graph.microsoft.com/oidc/userinfo",
});
if (response.IsError)
throw new Exception(response.Error);
n.AuthenticationTicket.Identity.AddClaims(response.Claims);
},
RedirectToIdentityProvider = notification =>
{
if (notification.ProtocolMessage.RequestType == OpenIdConnectRequestType.Authentication)
{
}
if (notification.ProtocolMessage.RequestType == OpenIdConnectRequestType.Logout)
{
var logoutUri = $"https://{auth0Domain}/v2/logout?client_id={auth0ClientId}";
var postLogoutUri = notification.ProtocolMessage.PostLogoutRedirectUri;
if (!string.IsNullOrEmpty(postLogoutUri))
{
if (postLogoutUri.StartsWith("/"))
{
// transform to absolute
var request = notification.Request;
postLogoutUri = request.Scheme + "://" + request.Host + request.PathBase + postLogoutUri;
}
logoutUri += $"&returnTo={Uri.EscapeDataString(postLogoutUri)}";
}
notification.Response.Redirect(logoutUri);
notification.HandleResponse();
}
return Task.FromResult(0);
}
}
});
}
Как я могу убедиться, что файл cookie .AspNet.Cookies установлен правильно на рабочем сервере?
Нужны ли дополнительные конфигурации для обработки завершения SSL при прокси?
Изменить: добавлен файл web.config
Подробнее здесь: [url]https://stackoverflow.com/questions/78523168/azure-ad-authentication-issue-with-asp-net-mvc-application-behind-proxy-missing[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия