Remove Cookie from API 2 Web Interface

I am trying to execute an authenticated web api request that does not reset the authentication cookie timeout. In the MVC world, I would accomplish this by removing the FormsAuthenification cookie from the answer:

 Response.Cookies.Remove(System.Web.Security.FormsAuthentication.FormsCookieName);

In Web API 2, I wrote a custom IHttpActionResult, and I remove the Set-Cookie header from the response. This, however, is not a header removal, as I still see the Set-Cookie header when the auth cookie is updated for requests that use this result of the action.

Here is the custom IHttpActionResult:

public class NonAuthResetResult<T> : IHttpActionResult where T: class
{
    private HttpRequestMessage _request;
    private T _body;

    public NonAuthResetResult(HttpRequestMessage request, T body)
    {
        _request = request;
        _body = body;
    }

    public string Message { get; private set; }

    public HttpRequestMessage Request { get; private set; }

    public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
    {
        var msg = _request.CreateResponse(_body);
        msg.Headers.Remove("Set-Cookie");
        return Task.FromResult(msg);
    }
}

How to edit the response header in Web API 2 because it does not work.

+4
source share
2 answers

Global.asax cookie Application_EndRequest. , Application_EndRequest.

1. , Context.Items:

public class NoResponseCookieAttribute : ActionFilterAttribute
{
    public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
    {
        System.Web.HttpContext.Current.Items.Add("remove-auth-cookie", "true");
    }
}

2. Application_EndRequest global.asax. 1 , cookie.

protected void Application_EndRequest()
{
    if (HttpContext.Current.Items["remove-auth-cookie"] != null)
    {
        Context.Response.Cookies.Remove(System.Web.Security.FormsAuthentication.FormsCookieName);
    }
}

3. api :

[NoResponseCookie]
public IHttpActionResult GetTypes()
{
    // your code here
}
+7

Web API 2, , , OWIN Cookie. , , , cookie auth.

-API App_Start/Startup.Auth.cs. ...

app.UseCookieAuthentication(new CookieAuthenticationOptions());

cookie. , - ...

app.UseCookieAuthentication(new CookieAuthenticationOptions
{
    SlidingExpiration = false,
    ExpireTimeSpan = new TimeSpan(1, 0, 0) // 1 hour
});
+1

Source: https://habr.com/ru/post/1525806/


All Articles