加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

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

发布时间:2020-12-16 07:16:36 所属栏目:asp.Net 来源:网络整理
导读:我正在使用新的webapi. 现在我不知道我是否正确地执行此操作但是我正在尝试设置我的api以在HttpResponseMessages标头内返回身份验证cookie以在另一个mvc应用程序上使用. 我正在使用FormsAuthenticationTicket,因为我认为它需要使用它 public HttpResponseMes
我正在使用新的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结合使用.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读