代码之家  ›  专栏  ›  技术社区  ›  ryan

形式认证和角色问题

  •  0
  • ryan  · 技术社区  · 16 年前
    1. http://localhost:1337/%28F%2883mI1fhnT6Sm1XopiPcErGYaqCafgnoSL_hgFJi9u7MwncoR98KOirf8GuqRVFfAbZN9mR1IH6W8LQQIeHTd4NcR5BKHAVvZrmcIoDTGTf01%29%29/

    2. 当我调试时,我看到在Global.asax和AccountController中,我的userRoles/accessLevel被正确地找到并作为身份验证票证的一部分插入。我的属性设置了查看操作所需的角色。获取加载,当我保存登录提示后,它会不断循环。知道怎么回事吗?另外,当我输出authTicket.UserData时,我看到了我的角色(Author | Admin) HttpContext.User.IsInRole("Author"); && HttpContext.User.IsInRole(“作者”);

    spotlights控制器.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));
        }
    }
    

    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>
    
    1 回复  |  直到 16 年前
        1
  •  0
  •   ryan    16 年前

    出于某种原因,没有使用Cookies。在web.config中设置cookieless=“UseCookies”,一切正常:)