Что это за фигня в URL?После входа в систему я получаю: <a href="http://localhost:1337/%28F%2883mI1fhnT6Sm1XopiPcErGYaqCafgnoSL_hgFJi9u7MwncoR98KOirf8GuqRVFfAbZN9mR1IH6W8LQQIeHTd4NcR5BKHAVvZrmcIoDTGTf01%29%29/" rel="nofollow noreferrer">http://localhost:1337/%28F%2883mI1fhnT6Sm1XopiPcErGYaqCafgnoSL_hgFJi9u7MwncoR98KOirf8GuqRVFfAbZN9mR1IH6W8LQQIeHTd4NcR5BKHAVvZrmcIoDTGTf01%29%29/</a>
При отладке я вижу, что в Global.asax, а также в AccountController мои userRoles / accessLevel правильно обнаруживаются и вставляются как частьаутентификационный билет.Мои атрибуты устанавливают необходимые роли для просмотра действия.GET загружается, и когда я сохраняю POST, запрашивается логин, который постоянно зацикливается.Есть идеи, что происходит?Кроме того, когда я вывожу свой authTicket.UserData, я вижу свои роли (Author | Admin), но HttpContext.User.IsInRole("Author");
&& HttpContext.User.IsInRole("Author");
возвращает 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>