我在使用 .Net MVC 5 应用程序配置 ADFS 时遇到问题。
我已经在 VS 2015 中配置了我的项目以使用声明并且它工作正常,但是我有一个问题。
我可以登录,使用 ADFS,我可以检查用户角色等。当我尝试使用时出现问题
[Authorize(Roles="somenonExistingRole")]
尽管我已经通过身份验证,但我被重定向到 ADFS 页面,当身份验证再次发生时,我被重定向到我的页面,在那里发生循环。页面将我发送到 ADFS 门户,ADFS 将我重定向到门户,经过几次尝试后,我收到了来自 ADFS 的错误(对许多请求)
我是否必须自己实现角色提供者之类的东西?或者我需要配置一些额外的东西。也许我可以限制尝试次数?当我的角色已经准备好时,为什么我会重定向到 ADFS?
代码中没有太多可显示的内容,请按要求显示:
我正在测试的 Controller :
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
[Authorize]
public ActionResult About()
{
var u = HttpContext.User;
if (u.IsInRole("/"))
{
ViewBag.Message = "User is in role.";
}
else
{
ViewBag.Message = "User is NOT in role.";
}
return View();
}
[Authorize(Roles = "/nonexistingRole")]
public ActionResult Contact()
{
ViewBag.Message = "Your contact page.";
return View();
}
}
和配置身份验证部分
public void ConfigureAuth(IAppBuilder app)
{
app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
app.UseCookieAuthentication(new CookieAuthenticationOptions());
app.UseWsFederationAuthentication(
new WsFederationAuthenticationOptions
{
Wtrealm = realm,
MetadataAddress = adfsMetadata,
});
}
最佳答案
要解决循环问题,您应该覆盖 AuthorizeAttribute
.
默认情况下,当用户的角色不符合 AuthorizeAttribute
时,MVC 会返回 401 Unauthorized要求。这将初始化对身份提供者的重新验证请求。由于用户已经登录,AAD 返回到同一页面,然后发出另一个 401,创建重定向循环 .在这里,我们覆盖 AuthorizeAttribute 的 HandleUnauthorizedRequest 方法以显示在我们的应用程序上下文中有意义的内容。
此类是在使用 VS 2015 创建新 MVC 项目时生成的:
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)]
public class AuthorizeAttribute : System.Web.Mvc.AuthorizeAttribute
{
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
if (filterContext.HttpContext.Request.IsAuthenticated)
{
//One Strategy:
//filterContext.Result = new System.Web.Mvc.HttpStatusCodeResult((int)System.Net.HttpStatusCode.Forbidden);
//Another Strategy:
filterContext.Result = new RedirectToRouteResult(
new RouteValueDictionary(
new
{
controller = "Error",
action = "ShowError",
errorMessage = "You do not have sufficient priviliges to view this page."
})
);
}
else
{
base.HandleUnauthorizedRequest(filterContext);
}
}
}
关于.net - 带有 ADFS 声明的 .Net MVC 授权属性的重定向循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34941877/