Search code examples
asp.net-mvcauthorizationforms-authenticationhttpcookie

MVC external authentication with the [Authorize] attribute


A site authorizes through a separate system. Once the user is authorized, I want to store some additional information with their Auth cookie. I am able to do this using the code below.

var settings = new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() };
var serialized = JsonConvert.SerializeObject(accountNumber, Formatting.None, settings);
var authTicket = new FormsAuthenticationTicket(1, "MyAuthTicket", DateTime.Now, DateTime.Now.AddMinutes(15),
    false, serialized);
var encTicket = FormsAuthentication.Encrypt(authTicket);
var faCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket)
{
    HttpOnly = true,
};
Response.Cookies.Add(faCookie);

However, when I try to hit a WebAPI method marked with [Authorize], I get a 401 Unauthorized error. What am I missing?


Solution

  • The following needs added to web.config:

    <system.web>
        <authentication mode="Forms">
        </authentication>
        <!-- other stuff -->
    <system.web>