如何在Web API MessageHandler中获取和解密authenticatin cookie

时间:2015-03-18 15:57:43

标签: asp.net-web-api forms-authentication

我想编写一个MessageHandler,它从HttpRequestMessage中提取身份验证cookie,并在odrer中解密它以获取经过身份验证的用户的用户名。我可以设法抓住cookie,但后来我被卡住了。我知道存在FormsAuthentication.Decrypt()方法,但我不知道在这里使用它。

public class FormsAuthenticationHandler : DelegatingHandler
{
    protected override async Task<HttpResponseMessage> SendAsync(
        HttpRequestMessage request, CancellationToken cancellationToken)
    {
        var formsCookieName = FormsAuthentication.FormsCookieName;
        var authCookie = request.Headers.GetCookies(formsCookieName).FirstOrDefault();
        if (authCookie != null)
        {
            string username = ???

            // further processing
        }

        var response = await base.SendAsync(request, cancellationToken);
        return response;
    }
}

1 个答案:

答案 0 :(得分:3)

这似乎有效:

public class FormsAuthenticationHandler : DelegatingHandler
{
    protected override async Task<HttpResponseMessage> SendAsync(
        HttpRequestMessage request, CancellationToken cancellationToken)
    {
        var authCookieName = FormsAuthentication.FormsCookieName;

        var authCookies = request.Headers.GetCookies(authCookieName).FirstOrDefault();
        if (authCookies != null && authCookies[authCookieName] != null)
        {
            var authCookieValue = authCookies[authCookieName].Value;
            var ticket = FormsAuthentication.Decrypt(authCookieValue);
            if (ticket != null)
            {
                var username = ticket.Name;

                // further processing
            }                    
        }

        var response = await base.SendAsync(request, cancellationToken);
        return response;
    }
}