asp.net-mvc – 尝试解密FormsAuthentication票证总是无法验证数据

我正在使用新的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我都会收到错误

Unable to validate data.

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

有人可以帮忙吗?

谢谢

解决方法

I assume its due to when the api encrypts the data it uses some kind
of key that the website doesn’t kNow about. Am I right?

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

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

相关文章

### 创建一个gRPC服务项目(grpc服务端)和一个 webapi项目(...
一、SiganlR 使用的协议类型 1.websocket即时通讯协议 2.Ser...
.Net 6 WebApi 项目 在Linux系统上 打包成Docker镜像,发布为...
一、 PD简介PowerDesigner 是一个集所有现代建模技术于一身的...
一、存储过程 存储过程就像数据库中运行的方法(函数) 优点:...
一、Ueditor的下载 1、百度编辑器下载地址:http://ueditor....