【问题标题】:Trying to decrypt a FormsAuthentication ticket always unable to validate data尝试解密 FormsAuthentication 票证始终无法验证数据
【发布时间】:2012-04-24 10:09:59
【问题描述】:

我正在使用新的 webapi。

现在我不知道我是否正确执行此操作,但我正在尝试设置我的 api 以在 HttpResponseMessages 标头中返回身份验证 cookie,以便在另一个 mvc 应用程序上使用。

我正在使用 FormsAuthenticationTicket,因为我认为它是我需要使用的

  public HttpResponseMessage Get(LoginModel model)
    {
        if (model.UserName == "bob")
        {
            //  if (Membership.ValidateUser(model.UserName, model.Password))
            // {
            var msg = new HttpResponseMessage(HttpStatusCode.OK);
            var expires = DateTime.Now.AddMinutes(30);
            var auth = new FormsAuthenticationTicket(1, model.UserName, DateTime.Now, expires,
                                                     model.RememberMe,"password",
                                                     FormsAuthentication.FormsCookiePath);
            var cookie = new HttpCookie("user");
            cookie.Value = FormsAuthentication.Encrypt(auth);
            cookie.Domain = "localhost";
            cookie.Expires = expires;
            msg.Headers.Add("result",cookie.Value);
            return msg;
            //   }
        }
        return new HttpResponseMessage(HttpStatusCode.Forbidden);
        //else
        //{
        //    return "The user name or password provided is incorrect.";
        //}
    }

现在在我的 mvc 应用程序的登录控制器中,我调用该服务并从我在 api 控制器中设置的标头中获取数据值。

   string data = response.Headers["result"].ToString();
   FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(data);

每次我尝试运行 FormsAuthentication.Decrypt 时都会遇到错误

无法验证数据。

我认为这是由于 api 加密数据时使用了网站不知道的某种密钥。我说的对吗?

有人可以帮忙吗?

谢谢

【问题讨论】:

  • 这一行string data = response.Headers["result"].ToString();data的值是什么?

标签: asp.net-mvc authentication asp.net-membership asp.net-web-api


【解决方案1】:

我认为这是由于当 api 加密它使用某种类型的数据时 网站不知道的密钥。我说的对吗?

FormsAuthentication.Encrypt 和 Decrypt 方法使用machine key。因此,请确保您为 Web API Web 应用程序和消费 ASP.NET MVC 应用程序配置了相同的密钥。

您还可以查看 following article,它说明了如何将 OAuth 2.0 与 Web API 结合使用。

【讨论】:

  • 知道如何抛出错误,以便我可以清除我的 cookie 并将用户从异常重定向到控制器吗?我的 cookie 持续存在,因此我陷入了重定向循环。当我更新我的密钥时会发生这种情况。 Web API 返回 401 但 MVC 重定向到登录页面,并且登录页面请求再次发回 cookie,从而引发未经授权的响应。陷入恶性循环!
猜你喜欢
  • 1970-01-01
  • 2012-04-18
  • 2013-07-31
  • 2017-03-14
  • 2017-02-10
  • 2021-06-19
  • 1970-01-01
  • 2023-03-29
  • 1970-01-01
相关资源
最近更新 更多