ASP.NET MVC 4 cookie disappears

2019-07-02 05:53发布

I have an ASP.NET application that sends an authentication cookie to an ASP.NET MVC application, used as an back office application.

I've added a global filter that checks every controller action for the authentication cookie. If the cookie exists, it allows the user to enter the page.

The code looks like this:

 public class SecurityFilter : FilterAttribute, IAuthorizationFilter
    {
        public void OnAuthorization(AuthorizationContext filterContext)
        {
            // TODO: For some reason .AUTHCookie cookie isn't exist in request context of filter,

                           HttpCookie cookie = filterContext.RequestContext.HttpContext.Request.Cookies[".AUTHCookie "];


            if (cookie != null)                 {

From the other side I can see the cookie sent from the ASP.NET application in Application_BeginRequest event in the Global.asax file.

Where and why the cookie disappeared? In what part of the MVC Request-Handling pipeline was the cookie thrown away?

  protected void Application_BeginRequest(object sender, EventArgs e)
        {
            var cookies = HttpContext.Current.Request.Cookies;
            // HERE I CAN SEE BOTH cookies. In filter action only one cookie was found. The authentication cookie is thrown somewhere ...
        }  

1条回答
兄弟一词,经得起流年.
2楼-- · 2019-07-02 06:31

I found a solution for my scenario. I've added a compatibilityMode="Framework45" into the machinekey in both applications and it's all working perfectly.

Note: If one of your applications is using an older versions of the .NET framework, you must explicitly configure your .NET 4.5 apps to use the earlier machine compatibility modes, or they will not be able to encrypt/decrypt the forms authentication ticket.

Just to remind you my scenario:

WebForms ASP.NET 4.5

<machineKey compatibilityMode="Framework45" decryption="AES" validation="SHA1" decryptionKey="your_key1" validationKey="your_keu2" />
  <authentication mode="Forms">
    <forms name="_authcookie" domain=".domain.com" loginUrl="Default.aspx?View=1" defaultUrl="Default.aspx?View=1" timeout="30" path="/" protection="All" slidingExpiration="true" enableCrossAppRedirects="true" />
  </authentication>

MVC 4
<machineKey compatibilityMode="Framework45" decryption="AES" validation="SHA1" decryptionKey="your_key1" validationKey="your_keu2" />
   <authentication mode="Forms">
     <forms name="_authcookie" domain=".domain.com" defaultUrl="~/" timeout="30" path="/" protection="All" slidingExpiration="true" enableCrossAppRedirects="true" />
    </authentication>

Possible values for the compatibility mode:

http://msdn.microsoft.com/en-us/library/system.web.configuration.machinekeysection.compatibilitymode.aspx

查看更多
登录 后发表回答