views:

70

answers:

1
  1. What is this garbage in the URL? After login I am directed to: http://localhost:1337/%28F%2883mI1fhnT6Sm1XopiPcErGYaqCafgnoSL_hgFJi9u7MwncoR98KOirf8GuqRVFfAbZN9mR1IH6W8LQQIeHTd4NcR5BKHAVvZrmcIoDTGTf01%29%29/

  2. When I debug I see that in Global.asax as well as AccountController my userRoles/accessLevel are correctly being found and inserted as part of the authentication ticket. My attributes set required roles to view the action. GET loads and when I save POST prompts for login which continually loops. Any idea what's goin on? Also, when I output my authTicket.UserData I see my roles (Author|Admin) yet HttpContext.User.IsInRole("Author"); && HttpContext.User.IsInRole("Author"); return false. Do I need roleManager enabled in web.config? And what do I set it to given me placing this info in the ticket?

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>
A: 

Cookies were not being used for some reason. Set cookieless="UseCookies" in web.config and all is working :)

ryan