2016-01-22 89 views
10

我在配置我的.Net MVC应用5 ADFS的一个问题。重定向循环与.net MVC授权与ADFS属性索赔

我已经在VS 2015中配置了我的项目来使用声明,它工作正常,但我有一个问题。

我可以登录,尤斯ADFS,我可以检查用户角色等问题occures当我尝试使用

[Authorize(Roles="somenonExistingRole")] 

尽管我已经验证我重定向到ADFS页面,当身份验证再次发生,我被重定向到我的页面,在那里循环发生。页送我去ADFS门户,ADFS重定向我对门户网站,试了几次后,我从ADFS错误(很多请求)

我必须由我自己来实现类似角色的供应商?或者我需要配置一些额外的东西。也许我可以只限制尝试次数?为什么我有我的角色allready时,我重定向到ADFS?

没有太多的代码中actualy显示,UT的要求: 控制器,即时通讯测试:

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(); 
     } 
    } 

和配置AUTH部分

public void ConfigureAuth(IAppBuilder app) 
{ 
    app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType); 

    app.UseCookieAuthentication(new CookieAuthenticationOptions()); 

    app.UseWsFederationAuthentication(
     new WsFederationAuthenticationOptions 
     { 
      Wtrealm = realm, 
      MetadataAddress = adfsMetadata, 

     }); 
} 
+0

你是什么AuthenticateAttribute:

该类创建使用VS 2015年一个新的MVC项目时产生?能否请您告诉我们的代码 – Thomas

+0

索里 - 从内存中写入授权offcourse :) – bunny1985

+0

你是否有配置AUTHENT一个Startup.Auth类? – Thomas

回答

11

要解决环路问题,您应该覆盖AuthorizeAttribute

默认情况下,MVC返回401未经授权当用户的角色不符合AuthorizeAttribute要求。这将重新认证请求初始化给身份提供者。由于用户已经登录,AD返回到相同的页面,然后发出另一个401,创建重定向循环。在这里,我们重写AuthorizeAttribute的HandleUnauthorizedRequest方法,以显示在我们的应用程序上下文中有意义的内容。

[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); 
     } 
    } 
} 
+0

但它在用户有角色时起作用。只有当用户不在角色中时,问题才会发生。 – bunny1985

+0

我编辑了我的帖子 – Thomas

+0

非常感谢 – bunny1985