How do I stop ASP.net forms authentication / session from renewing in setInterval ajax web service call?

眉间皱痕 提交于 2019-12-05 02:47:03

I'm working on different approaches to this as well. One way I'm doing it is by adding this to the Ajax service endpoint:

// Hide the cookie so this call doesn't extend the user's ticket
HttpContext ctx = HttpContext.Current;
ctx.Response.Cookies.Remove(FormsAuthentication.FormsCookieName);

This way you can negate an Auth Ticket renewal, sine the updated cookie will never make it back to the client.

If you have multiple Ajax endpoints that you want to exclude, a module can be implemented to identify those endpoints and include the code to remove the cookie from the response.

@RyanW provided the answer I needed so here's my implementation for MVC using an attribute just to keep things DRY.

using System.Web.Mvc;
using System.Web.Security;

namespace Your.Web.Attributes
{
    public class RemoveAuthCookieAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            filterContext.HttpContext.Response.Cookies.Remove(FormsAuthentication.FormsCookieName);
            base.OnActionExecuted(filterContext);
        }
    }
}

Implementation:

[RemoveAuthCookie]
public ActionResult PollMe()
{
    return View();
}

You could exclude your webservice from forms authentication:

<location path="yourwebservice.asmx">
    <system.web>
        <authorization>
            <allow users="?"/>
        <authorization>
    </system.web>
</location>  

But you probably need the information about the user, so you could configure the webservice to use forms authentication, but deactivate SlidingExpiration:

<location path="yourwebservice.asmx">
    <system.web>
        <authentication mode="Forms">
            <forms slidingExpiration="false"></forms>
        </authentication>
    </system.web>
</location>  

Be sure to test what happens if the forms cookie is expired. Maybe you'll have to redefine the loginurl, too.

Could you put your webservice asmx file into its own separate project/solution/application?

That way it should use a different session id to your main application.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!