2010-08-03 3 views
0
  1. Что это за мусор в URL? После входа в систему я направлен на: http://localhost:1337/%28F%2883mI1fhnT6Sm1XopiPcErGYaqCafgnoSL_hgFJi9u7MwncoR98KOirf8GuqRVFfAbZN9mR1IH6W8LQQIeHTd4NcR5BKHAVvZrmcIoDTGTf01%29%29/FormsAuthentication and Roles problem

  2. Когда я отладки я вижу, что в Global.asax, а также AccountController мои UserRoles/AccessLevel правильно был найден и включен в качестве части билета проверки подлинности. Мои атрибуты задавали требуемые роли для просмотра действия. GET загружает и когда я сохраняю подсказки POST для входа, который постоянно петли. Любая идея, что происходит? Кроме того, когда я выводю свой authTicket.UserData, я вижу свои роли (Author | Admin) еще HttpContext.User.IsInRole("Author"); & & HttpContext.User.IsInRole("Author"); return false. Нужен ли мне роль roleManager в web.config? И что я установил, чтобы я поставил эту информацию в билет?

SpotlightsController.cs:

// GET: /Spotlights/Edit/5 
[Authorize(Roles="Author,Admin")] 
public ActionResult Edit(int id) 
{ 
    Spotlight spotlight = spotlightRepository.GetSpotlight(id); 

    return View(new SpotlightFormViewModel(spotlight)); 
} 

// 
// POST: /Spotlights/Edit/5 

[Authorize(Roles="Author,Admin"), HttpPost] 
public ActionResult Edit(int id, FormCollection collection) 
{ 
    Spotlight spotlight = spotlightRepository.GetSpotlight(id); 

    try 
    { 
     spotlight.ModifiedDate = DateTimeOffset.Now; 
     UpdateModel(spotlight); 

     spotlightRepository.Save(); 

     return RedirectToAction("Details", new { id = spotlight.SpotlightID }); 
    } 
    catch 
    { 
     ModelState.AddRuleViolations(spotlight.GetRuleViolations()); 

     return View(new SpotlightFormViewModel(spotlight)); 
    } 
} 

Global.asax.cs:

protected void Application_AuthenticateRequest(Object sender, EventArgs e) 
{ 
    //Fires upon attempting to authenticate the use 
    if (!(HttpContext.Current.User == null) && 
     HttpContext.Current.User.Identity.IsAuthenticated && 
     HttpContext.Current.User.Identity.GetType() == typeof(FormsIdentity)) 
    { 
     HttpCookie authCookie = Context.Request.Cookies[FormsAuthentication.FormsCookieName]; 
     FormsIdentity userIdentity = (FormsIdentity)HttpContext.Current.User.Identity; 
     FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value); 

     String[] userRoles = authTicket.UserData.Split('|'); 
     HttpContext.Current.User = new GenericPrincipal(userIdentity, userRoles); 
    } 
} 

AccountController.cs:

[HttpPost] 
public ActionResult LogOn(LogOnModel model, string returnUrl) 
{ 
    if (ModelState.IsValid) 
    { 
     if (MembershipService.ValidateUser(model.UserName, model.Password)) 
     { 
      //string accessLevel = userRepository.FindUserByCWID(model.UserName).AccessLevel.LevelName; 
      string accessLevel = userRepository.FindUserByCWID(model.UserName).Roles; 

      FormsAuthenticationTicket authTicket = new 
        FormsAuthenticationTicket(1, //version 
        model.UserName, // user name 
        DateTime.Now,    //creation 
        DateTime.Now.AddMinutes(30), //Expiration 
        model.RememberMe, //Persistent 
        accessLevel); // add roles? 

      string encTicket = FormsAuthentication.Encrypt(authTicket); 
      this.Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, encTicket)); 

      FormsService.SignIn(model.UserName, model.RememberMe); 

      if (!String.IsNullOrEmpty(returnUrl)) 
      { 
       return Redirect(returnUrl); 
      } 
      else 
      { 
       return RedirectToAction("Index", "Home"); 
      } 
     } 
     else 
     { 
      ModelState.AddModelError("", "The user name or password provided is incorrect."); 
     } 
    } 

    // If we got this far, something failed, redisplay form 
    return View(model); 
} 

Web.config:

<?xml version="1.0"?> 

<configuration> 
    <connectionStrings> 
    <add name="ApplicationServices" connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true" 
     providerName="System.Data.SqlClient" /> 
    <add name="devConnectionString" snip" 
     providerName="System.Data.SqlClient" /> 
    <add name="ADConnectionString" connectionString="LDAP://my.domain/DC=my,DC=domain"/> 
    </connectionStrings> 

    <system.web> 
    <compilation debug="true" targetFramework="4.0"> 
     <assemblies> 
     <add assembly="System.Web.Abstractions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" /> 
     <add assembly="System.Web.Routing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" /> 
     <add assembly="System.Web.Mvc, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" /> 
     </assemblies> 
    </compilation> 

    <authentication mode="Forms"> 
     <forms loginUrl="~/Account/LogOn" timeout="2880" /> 
    </authentication> 

    <membership defaultProvider="MyADMembershipProvider"> 
     <providers> 
     <clear/> 
     <add name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider" connectionStringName="ApplicationServices" 
      enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false" 
      maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" 
      applicationName="/" /> 
     <add name="MyADMembershipProvider" 
      type="System.Web.Security.ActiveDirectoryMembershipProvider" connectionStringName="ADConnectionString" 
      attributeMapUsername="sAMAccountName" connectionProtection="Secure" 
      enablePasswordReset="false" maxInvalidPasswordAttempts="1" passwordAttemptWindow="15" 
      passwordAnswerAttemptLockoutDuration="1" minRequiredNonalphanumericCharacters="0" attributeMapEmail="mail" 
      /> 

     </providers> 
    </membership> 

    <profile> 
     <providers> 
     <clear/> 
     <add name="AspNetSqlProfileProvider" type="System.Web.Profile.SqlProfileProvider" connectionStringName="ApplicationServices" applicationName="/" /> 
     </providers> 
    </profile> 

    <roleManager enabled="false" defaultProvider="MySqlRoleProvider"> 
     <providers> 
     <clear/> 
     <add name="MySqlRoleProvider" type="System.Web.Security.SqlRoleProvider" connectionStringName="ApplicationServices" applicationName="myApp" /> 
     <add name="AspNetWindowsTokenRoleProvider" type="System.Web.Security.WindowsTokenRoleProvider" applicationName="/" /> 
     </providers> 
    </roleManager> 

    <pages> 
     <namespaces> 
     <add namespace="System.Web.Mvc" /> 
     <add namespace="System.Web.Mvc.Ajax" /> 
     <add namespace="System.Web.Mvc.Html" /> 
     <add namespace="System.Web.Routing" /> 
     </namespaces> 
    </pages> 
    </system.web> 

    <system.webServer> 
    <validation validateIntegratedModeConfiguration="false"/> 
    <modules runAllManagedModulesForAllRequests="true"/> 
    </system.webServer> 

    <runtime> 
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"> 
     <dependentAssembly> 
     <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" /> 
     <bindingRedirect oldVersion="1.0.0.0" newVersion="2.0.0.0" /> 
     </dependentAssembly> 
    </assemblyBinding> 
    </runtime> 
</configuration> 
+0

Почему у вас есть 'if (condition1) {if (condition2) {...' вместо 'if (condition1 && condition2) {.. . 'когда нет' else'? – NullUserException

+0

Действительная точка. Читаемость я полагаю, я не писал, что, хотя я нашел это в качестве примера – ryan

+0

С точки зрения удобочитаемости, было бы лучше объединить их в одно условие IMO. – James

ответ

0

Куки-файлы не использовались по какой-либо причине. Установите cookieless = «UseCookies» в web.config и все работает :)