У меня есть устаревшее приложение 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#
-
- Похожие темы
- Ответы
- Просмотры
- Последнее сообщение