【问题标题】:FormsAuthentication is I'm not passing user but I amFormsAuthentication 是我没有通过用户,但我是
【发布时间】:2012-11-20 20:45:23
【问题描述】:

我有这个登录方式:

   // POST: /Account/LogOn
    [HttpPost]
    public ActionResult LogOn(LogOnModel model, string returnUrl, string corpid)
    {
      var sb = new StringBuilder();
      sb.AppendLine("Logon HttpPost start");
      sb.AppendLine(string.Format("returnUrl: {0}", returnUrl));
      sb.AppendLine(string.Format("corpid: {0}", corpid));
      sb.AppendLine(string.Format("model.UserName: {0}", model.UserName));
      sb.AppendLine(string.Format("model.Password: {0}", model.Password));

      try
      {
        sb.AppendLine(string.Format("ModelState.IsValid: {0}", ModelState.IsValid));
        if (ModelState.IsValid)
        {
          if (Membership.ValidateUser(model.UserName, model.Password))
          {
            sb.AppendLine("Validated User");
            FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
            if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1
                && returnUrl.StartsWith("/")
                && !returnUrl.StartsWith("//")
                && !returnUrl.StartsWith("/\\"))
            {
              sb.AppendLine("Redirect(returnUrl)");
              return Redirect(returnUrl);
            }

            // need to decide whether to display the CustomerSummary, AccountScreen, or AddCustomer view
            // AccountScreen if they only have 1 account tied to this logon
            // AddCustomer if they do not havfe any tied to this logon
            // CustomerSummary if they have more than 1 tied to this logon

            var customers = _client.RequestCustomersForAccount(model.UserName);
            if (!customers.Any())
            {
              // no accounts tied to this logon
              sb.AppendLine("No accounts found for this login.");
              sb.AppendLine("RedirectToAction(AddCustomer, Customer)");
              return RedirectToAction("AddCustomer", "Customer");
            }

            if (customers.Count() == 1)
            {
              sb.AppendLine("1 accounts found for this login.");
              sb.AppendLine("RedirectToAction(AccountScreen, Customer)");
              model.AccountId = customers[0].AccountId;
              sb.AppendLine(string.Format("customers[0].AccountId: {0}", customers[0].AccountId));
              // only 1 account tied to this logon
              return RedirectToAction("AccountScreen", "Customer", model);
            }

            if (customers.Count() > 1)
            {
              sb.AppendLine(string.Format("{0} accounts found for this login.", customers.Count()));
              sb.AppendLine("RedirectToAction(CustomerSummary, Customer)");
              // no accounts tied to this logon
              return RedirectToAction("CustomerSummary", "Customer");
            }

          }
          else
          {
            var msg = "The user name or password provided is incorrect.";
            sb.AppendLine(msg);
            ModelState.AddModelError("", msg);
          }
        }

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

      }
      catch (Exception ex)
      {
        sb.AppendLine(string.Format("An error occured: {0}", ex));
        WebPortalLogging.Logging.LogException("The following error occured: ", ex, _asName);
        return null;
      }
      finally
      {
        WebPortalLogging.Logging.LogInfo(sb.ToString(), _asName);
      }
    }

当我到达FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe); 行时,我收到了这个错误:

System.InvalidOperationException:未提供用户名。 在 ClientCredentials 中指定用户名。

服务器堆栈跟踪:在 System.ServiceModel.ClientCredentialsSecurityTokenManager.CreateSecurityTokenProvider(SecurityTokenRequirement tokenRequirement,布尔禁用信息卡)在 System.ServiceModel.Channels.HttpChannelFactory.CreateAndOpenTokenProvider(时间跨度 超时,AuthenticationSchemes authenticationScheme,EndpointAddress 目标,Uri 通过,ChannelParameterCollection 通道参数)在 System.ServiceModel.Channels.HttpChannelFactory.CreateAndOpenTokenProvidersCore(端点地址 to, Uri via, ChannelParameterCollection channelParameters, TimeSpan 超时,SecurityTokenProviderContainer& tokenProvider, SecurityTokenProviderContainer& proxyTokenProvider) 在 System.ServiceModel.Channels.HttpChannelFactory.HttpRequestChannel.CreateAndOpenTokenProviders(时间跨度 超时)在 System.ServiceModel.Channels.HttpsChannelFactory.HttpsRequestChannel.OnOpen(时间跨度 超时)在 System.ServiceModel.Channels.CommunicationObject.Open(时间跨度 超时)在 System.ServiceModel.Channels.ServiceChannel.OnOpen(TimeSpan 超时)
在 System.ServiceModel.Channels.CommunicationObject.Open(时间跨度 超时)在 System.ServiceModel.Channels.ServiceChannel.CallOnceManager.CallOnce(时间跨度 超时,CallOnceManager 级联)在 System.ServiceModel.Channels.ServiceChannel.EnsureOpened(时间跨度 超时)在 System.ServiceModel.Channels.ServiceChannel.Call(字符串 action, Boolean oneway, ProxyOperationRuntime 操作, Object[] ins, Object[] 出局,TimeSpan 超时)在 System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall,ProxyOperationRuntime 操作)在 System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage 留言)

在 [0] 处重新抛出异常:在 System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg,IMessage retMsg)在 System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(消息数据& msgData,Int32 类型)在 SuburbanCustPortal.SuburbanService.ISuburbanService.RequestCustomersForAccount(字符串 客户登录名)在 SuburbanCustPortal.Controllers.AccountController.LogOn(LogOnModel C:\work2\Doozer 中的模型、字符串 returnUrl、字符串 corpid) 软件\Suburban\SuburbanCustPortal\Controllers\AccountController.cs:line 112

这段代码一次就可以正常工作,我回过头来将它与它工作时的代码进行了比较,除了日志记录发生了变化,我没有看到任何其他内容。

这是我添加的日志记录:

Logon HttpPost start
returnUrl: 
corpid: 
model.UserName: user
model.Password: password
ModelState.IsValid: True
Validated User
An error occured: System.InvalidOperationException: The username is not provided. Specify username in ClientCredentials.

Server stack trace: 
   at System.ServiceModel.ClientCredentialsSecurityTokenManager.CreateSecurityTokenProvider(SecurityTokenRequirement tokenRequirement, Boolean disableInfoCard)
   at System.ServiceModel.Channels.HttpChannelFactory.CreateAndOpenTokenProvider(TimeSpan timeout, AuthenticationSchemes authenticationScheme, EndpointAddress target, Uri via, ChannelParameterCollection channelParameters)
   at System.ServiceModel.Channels.HttpChannelFactory.CreateAndOpenTokenProvidersCore(EndpointAddress to, Uri via, ChannelParameterCollection channelParameters, TimeSpan timeout, SecurityTokenProviderContainer& tokenProvider, SecurityTokenProviderContainer& proxyTokenProvider)
   at System.ServiceModel.Channels.HttpChannelFactory.HttpRequestChannel.CreateAndOpenTokenProviders(TimeSpan timeout)
   at System.ServiceModel.Channels.HttpsChannelFactory.HttpsRequestChannel.OnOpen(TimeSpan timeout)
   at System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout)
   at System.ServiceModel.Channels.ServiceChannel.OnOpen(TimeSpan timeout)
   at System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout)
   at System.ServiceModel.Channels.ServiceChannel.CallOnceManager.CallOnce(TimeSpan timeout, CallOnceManager cascade)
   at System.ServiceModel.Channels.ServiceChannel.EnsureOpened(TimeSpan timeout)
   at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout)
   at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation)
   at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message)

Exception rethrown at [0]: 
   at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
   at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
   at SuburbanCustPortal.SuburbanService.ISuburbanService.RequestCustomersForAccount(String customerloginname)
   at SuburbanCustPortal.Controllers.AccountController.LogOn(LogOnModel model, String returnUrl, String corpid) in C:\work2\Doozer Software\Suburban\SuburbanCustPortal\Controllers\AccountController.cs:line 112

从日志中可以看出,自从我通过了这个检查后,我就用一个用户登录了:

 if (Membership.ValidateUser(model.UserName, model.Password))

此外,我可以在本地计算机上运行此代码,并且不会出错。这一切都针对同一个数据库,本地并发布。

有人知道我的问题是什么吗?

【问题讨论】:

    标签: c# membership formsauthentication


    【解决方案1】:

    当我到达 FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);我收到此错误:

    您的堆栈跟踪显示异常是由以下行引发的:

    var customers = _client.RequestCustomersForAccount(model.UserName);
    

    推测此调用失败是因为您的Thread.CurrentPrincipal 尚未设置为经过身份验证的用户(您设置了 FormsAuthentication cookie,但在下一个请求之前不会处理它)。

    我不知道你为什么要在验证用户身份后做额外的工作,我建议你立即重定向,例如:

    if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1
                && returnUrl.StartsWith("/")
                && !returnUrl.StartsWith("//")
                && !returnUrl.StartsWith("/\\"))
    {
       sb.AppendLine("Redirect(returnUrl)");
       return Redirect(returnUrl);
    }
    
    Redirect(Request.UrlReferrer.ToString()); // Or wherever you want to redirect to
    

    【讨论】:

    • 我正在检查他们经过身份验证后的指向。待处理的帐户数量会影响接下来显示的页面。
    • 你是对的,错误在 _client.RequestCustomersForAccount 虽然它是由于它没有收到服务的凭据。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-31
    • 2018-08-07
    • 2017-06-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多