asp.net mvc azure AAD 身份验证死循环
asp.net mvc azure AAD authentication infinite loop
我有一个带有 azure AAD 登录的 asp.net mvc 应用程序。
当我按 f5 调试应用程序时,应用程序转到 azure 以在 AAD 中进行身份验证,然后它返回应用程序到控制器,然后再次重定向回 azure。
我知道这一点,因为如果我在登录控制器上放置一个断点,它就会被无限命中
这是我的路由配置
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
//routes.IgnoreRoute("");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Dashboards", action = "Dashboard_1", id = UrlParameter.Optional }
);
}
这是我的仪表板控制器,已授权
[Authorize]
public class DashboardsController : Controller
{
public ActionResult Dashboard_1()
{
return View();
}
这是我的登录和签名帐户控制器操作
public class AccountController : Controller
{
public void SignIn()
{
if (!Request.IsAuthenticated)
{
HttpContext.GetOwinContext().Authentication.Challenge(
new AuthenticationProperties { RedirectUri = "/" },
OpenIdConnectAuthenticationDefaults.AuthenticationType);
}
}
public void SignOut()
{
// Remove all cache entries for this user and send an OpenID Connect sign-out request.
string usrObjectId = ClaimsPrincipal.Current.FindFirst(SettingsHelper.ClaimTypeObjectIdentifier).Value;
AuthenticationContext authContext = new AuthenticationContext(SettingsHelper.AzureADAuthority, new EfAdalTokenCache(usrObjectId));
authContext.TokenCache.Clear();
HttpContext.GetOwinContext().Authentication.SignOut(
OpenIdConnectAuthenticationDefaults.AuthenticationType, CookieAuthenticationDefaults.AuthenticationType);
}
public ActionResult ConsentApp()
{
string strResource = Request.QueryString["resource"];
string strRedirectController = Request.QueryString["redirect"];
string authorizationRequest = String.Format(
"{0}oauth2/authorize?response_type=code&client_id={1}&resource={2}&redirect_uri={3}",
Uri.EscapeDataString(SettingsHelper.AzureADAuthority),
Uri.EscapeDataString(SettingsHelper.ClientId),
Uri.EscapeDataString(strResource),
Uri.EscapeDataString(String.Format("{0}/{1}", this.Request.Url.GetLeftPart(UriPartial.Authority), strRedirectController))
);
return new RedirectResult(authorizationRequest);
}
public ActionResult AdminConsentApp()
{
string strResource = Request.QueryString["resource"];
string strRedirectController = Request.QueryString["redirect"];
string authorizationRequest = String.Format(
"{0}oauth2/authorize?response_type=code&client_id={1}&resource={2}&redirect_uri={3}&prompt={4}",
Uri.EscapeDataString(SettingsHelper.AzureADAuthority),
Uri.EscapeDataString(SettingsHelper.ClientId),
Uri.EscapeDataString(strResource),
Uri.EscapeDataString(String.Format("{0}/{1}", this.Request.Url.GetLeftPart(UriPartial.Authority), strRedirectController)),
Uri.EscapeDataString("admin_consent")
);
return new RedirectResult(authorizationRequest);
}
public void RefreshSession()
{
string strRedirectController = Request.QueryString["redirect"];
HttpContext.GetOwinContext().Authentication.Challenge(new AuthenticationProperties { RedirectUri = String.Format("/{0}", strRedirectController) }, OpenIdConnectAuthenticationDefaults.AuthenticationType);
}
}
这是我的 startup.auth.cs
public void ConfigureAuth(IAppBuilder app)
{
// configure the authentication type & settings
app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
app.UseCookieAuthentication(new CookieAuthenticationOptions());
// configure the OWIN OpenId Connect options
app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
{
ClientId = SettingsHelper.ClientId,
Authority = SettingsHelper.AzureADAuthority,
Notifications = new OpenIdConnectAuthenticationNotifications()
{
// when an auth code is received...
AuthorizationCodeReceived = (context) => {
// get the OpenID Connect code passed from Azure AD on successful auth
string code = context.Code;
// create the app credentials & get reference to the user
ClientCredential creds = new ClientCredential(SettingsHelper.ClientId, SettingsHelper.ClientSecret);
string userObjectId = context.AuthenticationTicket.Identity.FindFirst(System.IdentityModel.Claims.ClaimTypes.NameIdentifier).Value;
// use the ADAL to obtain access token & refresh token...
// save those in a persistent store...
EfAdalTokenCache sampleCache = new EfAdalTokenCache(userObjectId);
AuthenticationContext authContext = new AuthenticationContext(SettingsHelper.AzureADAuthority, sampleCache);
// obtain access token for the AzureAD graph
Uri redirectUri = new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path));
AuthenticationResult authResult = authContext.AcquireTokenByAuthorizationCode(code, redirectUri, creds, SettingsHelper.AzureAdGraphResourceId);
// successful auth
return Task.FromResult(0);
},
AuthenticationFailed = (context) => {
context.HandleResponse();
return Task.FromResult(0);
}
},
TokenValidationParameters = new System.IdentityModel.Tokens.TokenValidationParameters
{
ValidateIssuer = false
}
});
}
我们 运行 遇到了同样的问题,并通过安装 Kentor cookie 保护程序解决了这个问题。有关详细信息,请参阅 https://github.com/KentorIT/owin-cookie-saver。
要解决此问题: 您可以升级您的应用程序以使用 ASP.NET 核心。如果您必须继续停留在 ASP.NET,请执行以下操作:
更新您的应用程序的 Microsoft.Owin.Host.SystemWeb 包至少是版本并修改您的代码以使用新的 cookie 管理器之一 类,例如如下所示:
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = "Cookies",
CookieManager = new Microsoft.Owin.Host.SystemWeb.SystemWebChunkingCookieManager()
});
我有一个带有 azure AAD 登录的 asp.net mvc 应用程序。 当我按 f5 调试应用程序时,应用程序转到 azure 以在 AAD 中进行身份验证,然后它返回应用程序到控制器,然后再次重定向回 azure。
我知道这一点,因为如果我在登录控制器上放置一个断点,它就会被无限命中
这是我的路由配置
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
//routes.IgnoreRoute("");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Dashboards", action = "Dashboard_1", id = UrlParameter.Optional }
);
}
这是我的仪表板控制器,已授权
[Authorize]
public class DashboardsController : Controller
{
public ActionResult Dashboard_1()
{
return View();
}
这是我的登录和签名帐户控制器操作
public class AccountController : Controller
{
public void SignIn()
{
if (!Request.IsAuthenticated)
{
HttpContext.GetOwinContext().Authentication.Challenge(
new AuthenticationProperties { RedirectUri = "/" },
OpenIdConnectAuthenticationDefaults.AuthenticationType);
}
}
public void SignOut()
{
// Remove all cache entries for this user and send an OpenID Connect sign-out request.
string usrObjectId = ClaimsPrincipal.Current.FindFirst(SettingsHelper.ClaimTypeObjectIdentifier).Value;
AuthenticationContext authContext = new AuthenticationContext(SettingsHelper.AzureADAuthority, new EfAdalTokenCache(usrObjectId));
authContext.TokenCache.Clear();
HttpContext.GetOwinContext().Authentication.SignOut(
OpenIdConnectAuthenticationDefaults.AuthenticationType, CookieAuthenticationDefaults.AuthenticationType);
}
public ActionResult ConsentApp()
{
string strResource = Request.QueryString["resource"];
string strRedirectController = Request.QueryString["redirect"];
string authorizationRequest = String.Format(
"{0}oauth2/authorize?response_type=code&client_id={1}&resource={2}&redirect_uri={3}",
Uri.EscapeDataString(SettingsHelper.AzureADAuthority),
Uri.EscapeDataString(SettingsHelper.ClientId),
Uri.EscapeDataString(strResource),
Uri.EscapeDataString(String.Format("{0}/{1}", this.Request.Url.GetLeftPart(UriPartial.Authority), strRedirectController))
);
return new RedirectResult(authorizationRequest);
}
public ActionResult AdminConsentApp()
{
string strResource = Request.QueryString["resource"];
string strRedirectController = Request.QueryString["redirect"];
string authorizationRequest = String.Format(
"{0}oauth2/authorize?response_type=code&client_id={1}&resource={2}&redirect_uri={3}&prompt={4}",
Uri.EscapeDataString(SettingsHelper.AzureADAuthority),
Uri.EscapeDataString(SettingsHelper.ClientId),
Uri.EscapeDataString(strResource),
Uri.EscapeDataString(String.Format("{0}/{1}", this.Request.Url.GetLeftPart(UriPartial.Authority), strRedirectController)),
Uri.EscapeDataString("admin_consent")
);
return new RedirectResult(authorizationRequest);
}
public void RefreshSession()
{
string strRedirectController = Request.QueryString["redirect"];
HttpContext.GetOwinContext().Authentication.Challenge(new AuthenticationProperties { RedirectUri = String.Format("/{0}", strRedirectController) }, OpenIdConnectAuthenticationDefaults.AuthenticationType);
}
}
这是我的 startup.auth.cs
public void ConfigureAuth(IAppBuilder app)
{
// configure the authentication type & settings
app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
app.UseCookieAuthentication(new CookieAuthenticationOptions());
// configure the OWIN OpenId Connect options
app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
{
ClientId = SettingsHelper.ClientId,
Authority = SettingsHelper.AzureADAuthority,
Notifications = new OpenIdConnectAuthenticationNotifications()
{
// when an auth code is received...
AuthorizationCodeReceived = (context) => {
// get the OpenID Connect code passed from Azure AD on successful auth
string code = context.Code;
// create the app credentials & get reference to the user
ClientCredential creds = new ClientCredential(SettingsHelper.ClientId, SettingsHelper.ClientSecret);
string userObjectId = context.AuthenticationTicket.Identity.FindFirst(System.IdentityModel.Claims.ClaimTypes.NameIdentifier).Value;
// use the ADAL to obtain access token & refresh token...
// save those in a persistent store...
EfAdalTokenCache sampleCache = new EfAdalTokenCache(userObjectId);
AuthenticationContext authContext = new AuthenticationContext(SettingsHelper.AzureADAuthority, sampleCache);
// obtain access token for the AzureAD graph
Uri redirectUri = new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path));
AuthenticationResult authResult = authContext.AcquireTokenByAuthorizationCode(code, redirectUri, creds, SettingsHelper.AzureAdGraphResourceId);
// successful auth
return Task.FromResult(0);
},
AuthenticationFailed = (context) => {
context.HandleResponse();
return Task.FromResult(0);
}
},
TokenValidationParameters = new System.IdentityModel.Tokens.TokenValidationParameters
{
ValidateIssuer = false
}
});
}
我们 运行 遇到了同样的问题,并通过安装 Kentor cookie 保护程序解决了这个问题。有关详细信息,请参阅 https://github.com/KentorIT/owin-cookie-saver。
要解决此问题: 您可以升级您的应用程序以使用 ASP.NET 核心。如果您必须继续停留在 ASP.NET,请执行以下操作: 更新您的应用程序的 Microsoft.Owin.Host.SystemWeb 包至少是版本并修改您的代码以使用新的 cookie 管理器之一 类,例如如下所示:
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = "Cookies",
CookieManager = new Microsoft.Owin.Host.SystemWeb.SystemWebChunkingCookieManager()
});