尝试解密FormsAuthentication票证始终无法验证数据

Div*_*Dan 5 authentication asp.net-mvc asp.net-membership asp.net-web-api

我正在使用新的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.";
        //}
    }
Run Code Online (Sandbox Code Playgroud)

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

   string data = response.Headers["result"].ToString();
   FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(data);
Run Code Online (Sandbox Code Playgroud)

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

无法验证数据.

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

有人可以帮忙吗?

谢谢

Dar*_*rov 8

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

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

您还可以查看以下文章,该文章说明了如何将OAuth 2.0与Web API结合使用.