Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to decrypt a FormsAuthentication ticket always unable to validate data

I am using the new webapi.

Now I don't know if I am doing this correctly but I am trying to setup my api to return an authentication cookie within the HttpResponseMessages header to use on another an mvc application.

I am using the FormsAuthenticationTicket as I think its what I need to use like

  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.";
        //}
    }

now within my login controller on my mvc application I call the service and get the data value from the header I set in the api controller.

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

Everytime I try running the FormsAuthentication.Decrypt I keep getting an error

Unable to validate data.

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?

Can someone help out?

Thank you

like image 756
Diver Dan Avatar asked Apr 12 '12 04:04

Diver Dan


1 Answers

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 and Decrypt methods use the machine key. So make sure you have configured the same key for both your Web API web application and the consuming ASP.NET MVC application.

You could also take a look at the following article which illustrates how you could use OAuth 2.0 with the Web API.

like image 173
Darin Dimitrov Avatar answered Oct 09 '22 06:10

Darin Dimitrov