在HttpAuthenticationContext设置的Cookie值IAuthenticationFilter [英] Setting Cookie values in HttpAuthenticationContext for IAuthenticationFilter

查看:313
本文介绍了在HttpAuthenticationContext设置的Cookie值IAuthenticationFilter的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有必要在一个管道的WebAPI的认证步骤读/写饼干。我创建了一个自定义过滤器这一点。

在试图遵守自托管的概念,什么是访问和写入的cookie到客户端安全的方式? <一href=\"http://weblog.west-wind.com/posts/2013/Apr/15/WebAPI-Getting-Headers-QueryString-and-Cookie-Values\"相对=nofollow>里克·斯特劳的评论说,如果我们使用 HttpContext.Current.Response.Cookies.Add(),和我的应用程序是自托管,上下文可能/将不存在。

所以,我怎么会写一个cookie到客户端使用 HttpAuthenticationContext ,仍然是自托管的安全?


解决方案

  HttpAuthenticationContext authContext;
authContext.ActionContext.Response.Headers.AddCookies(/ *饼干* /);

EDIT2

  HttpAuthenticationContext authContext;
VAR的myCookie =新CookieHeaderValue(键,值)
authContext.ActionContext.Response.Headers.Add(设置Cookie,myCookie.ToString());

修改

的addCookie是位于System.Net.Http.Formatting.dll扩展方法(如版本v5.2.2.0的),并且延伸方法由静态类型Htt presponseHeadersExtensions,位于命名系统声明。 Net.Http。


  • 如果您找不到扩展方法,试图找到的Htt presponseHeadersExtensions类。


  • 如果您找不到的Htt presponseHeadersExtensions类,尽量提升网页API 2库。提升每一个项​​目的WebApi2所有的Nu​​Get包(对于那些谁恨升级的NuGet包像我)的最有效方式,是做一个全球性的搜索/的短期版=XXXtargetFramework =net45的.config文件替换'(其中xxx是一个旧版本替换为'版本=5.2.2targetFramework =net45


  • 在最坏的情况下,如果你的老板或你的妈妈不会让你升级的NuGet包,可以随时采取反叛的态度和反编译包含的addCookie的code,它看起来是这样的:

     使用系统;
        使用System.Collections.Generic;
        使用System.ComponentModel;
        使用System.Net.Http.Headers;
        使用System.Net.Http.Properties;
        使用System.Web.Http;
        命名空间System.Net.Http
        {
            ///&LT;总结&gt;提供的&lt推广方法;见CREF =T:System.Net.Http.Headers.Htt presponseHeaders/&GT;类。 &LT; /总结&gt;
            [EditorBrowsable(EditorBrowsableState.Never)
            公共静态类的Htt presponseHeadersExtensions
            {
                私人常量字符串的setcookie =设置Cookie
                ///&LT;总结&gt;添加Cookie来响应。每个设置Cookie头重新psented如吲$ P $;见CREF =T:System.Net.Http.Headers.CookieHeaderValue/&GT;实例。 A&LT;见CREF =T:System.Net.Http.Headers.CookieHeaderValue/&GT;包含域,路径和其它cookie信息,以及信息的一个或以上&lt;见CREF =T:System.Net.Http.Headers.CookieState/&GT;实例。每个&LT;见CREF =T:System.Net.Http.Headers.CookieState/&GT;实例包含一个cookie名称和任何Cookie状态是联想这个名字。该州是一个&LT的形式;见CREF =T:System.Collections.Specialized.NameValueCollection/&GT;其中上线为连接$ C $光盘作为HTML表单URL-CN codeD数据。这将重新presentation允许多个相关的曲奇要在同一个Cookie头内进行,同时还提供每个Cookie状态之间的分离。样本Cookie头如下所示。在本实施例中,有两个与下;参见CREF =T:System.Net.Http.Headers.CookieState/&GT;分别的名称和STATE1 STATE2。此外,每个Cookie状态包含两个名称/值对(名1 / value1和NAME2 /值2)和(NAME3 / VALUE3和NAME4 / VALUE4)。 &放大器; LT; code&放; GT;设置Cookie:STATE1:名1 =值1&放大器;放大器;放大器; 2 =值2; STATE2:NAME3 = VALUE3&放大器;放大器;放大器; NAME4 =值4;域=域1; PATH = PATH1; &放大器; LT; / code&放; GT;&LT; /总结&gt;
                ///&LT; PARAM NAME =头&gt;在响应头&LT; /参数&GT;
                ///&LT; PARAM NAME =曲奇&gt;该Cookie值添加到响应&LT; /参数&GT;
                公共静态无效AddCookies(这Htt的presponseHeaders头,IEnumerable的&LT; CookieHeaderValue&GT;饼干)
                {
                    如果(头== NULL)
                    {
                        扔Error.ArgumentNull(头);
                    }
                    如果(饼干== NULL)
                    {
                        扔Error.ArgumentNull(曲奇);
                    }
                    的foreach(在cookie中CookieHeaderValue电流)
                    {
                        如果(当前== NULL)
                        {
                            扔Error.Argument(曲奇,Resources.CookieNull,新的对象[0]​​);
                        }
                        headers.TryAddWithoutValidation(设置Cookie,current.ToString());
                    }
                }
            }
        }


    • 在最后,你觉得有点愚蠢花这么多时间去寻找一个扩展方法,当你意识到,在加入webapi2一个cookie以线code的做法仅仅是:



  

headers.TryAddWithoutValidation(设置Cookie,新的CookieHeaderValue(键,值)); //其中头部是一个Htt的presponseHeaders


I have a need to read/write cookies during the authentication step of a WebAPI pipeline. I have created a custom filter for this.

In an attempt to comply with self-hosting concepts, what would be a safe way to access and write cookies out to the client? Rick Strahl commented that if we use HttpContext.Current.Response.Cookies.Add(), and my application is self-hosted, the context may/will not exist.

So how would I write a cookie out to the client using HttpAuthenticationContext and still be self-host safe?

解决方案

HttpAuthenticationContext authContext;
authContext.ActionContext.Response.Headers.AddCookies(/*cookies */);

edit2

HttpAuthenticationContext authContext;
var myCookie = new CookieHeaderValue("key", "value")
authContext.ActionContext.Response.Headers.Add("Set-Cookie", myCookie.ToString());

edit

AddCookie is an extension method located in System.Net.Http.Formatting.dll (as of version v5.2.2.0), and the extension method is declared by static class HttpResponseHeadersExtensions, located in namespace System.Net.Http.

  • If you cannot find the extension method, try locate HttpResponseHeadersExtensions class.

  • If you cannot find HttpResponseHeadersExtensions class, try upgrade Web Api 2 libraries. The most efficient way to upgrade all nuget packages of WebApi2 of every projects (for those who hate upgrading nuget packages like me), is to do a global search/replace on .config files of term 'version="x.x.x" targetFramework="net45"' (where x.x.x is an older version replaced by 'version="5.2.2" targetFramework="net45"'

  • In worst case scenario if your boss or your mom won't let you upgrade the nuget packages, you can always adopt a rebel attitude and decompile the code containing AddCookie, it appear to look like this:

        using System;
        using System.Collections.Generic;
        using System.ComponentModel;
        using System.Net.Http.Headers;
        using System.Net.Http.Properties;
        using System.Web.Http;
        namespace System.Net.Http
        {
            /// <summary> Provides extension methods for the <see cref="T:System.Net.Http.Headers.HttpResponseHeaders" /> class. </summary>
            [EditorBrowsable(EditorBrowsableState.Never)]
            public static class HttpResponseHeadersExtensions
            {
                private const string SetCookie = "Set-Cookie";
                /// <summary> Adds cookies to a response. Each Set-Cookie header is  represented as one <see cref="T:System.Net.Http.Headers.CookieHeaderValue" /> instance. A <see cref="T:System.Net.Http.Headers.CookieHeaderValue" /> contains information about the domain, path, and other cookie information as well as one or more <see cref="T:System.Net.Http.Headers.CookieState" /> instances. Each <see cref="T:System.Net.Http.Headers.CookieState" /> instance contains a cookie name and whatever cookie state is associate with that name. The state is in the form of a  <see cref="T:System.Collections.Specialized.NameValueCollection" /> which on the wire is encoded as HTML Form URL-encoded data.  This representation allows for multiple related "cookies" to be carried within the same Cookie header while still providing separation between each cookie state. A sample Cookie header is shown below. In this example, there are two <see cref="T:System.Net.Http.Headers.CookieState" /> with names state1 and state2 respectively. Further, each cookie state contains two name/value pairs (name1/value1 and name2/value2) and (name3/value3 and name4/value4). &lt;code&gt; Set-Cookie: state1:name1=value1&amp;amp;name2=value2; state2:name3=value3&amp;amp;name4=value4; domain=domain1; path=path1; &lt;/code&gt;</summary>
                /// <param name="headers">The response headers</param>
                /// <param name="cookies">The cookie values to add to the response.</param>
                public static void AddCookies(this HttpResponseHeaders headers, IEnumerable<CookieHeaderValue> cookies)
                {
                    if (headers == null)
                    {
                        throw Error.ArgumentNull("headers");
                    }
                    if (cookies == null)
                    {
                        throw Error.ArgumentNull("cookies");
                    }
                    foreach (CookieHeaderValue current in cookies)
                    {
                        if (current == null)
                        {
                            throw Error.Argument("cookies", Resources.CookieNull, new object[0]);
                        }
                        headers.TryAddWithoutValidation("Set-Cookie", current.ToString());
                    }
                }
            }
        }
    

    • In the end you feel a little stupid spending so much time looking for an extension method, when you realize that adding a cookie in webapi2 is simply done in a line of code:

headers.TryAddWithoutValidation("Set-Cookie", new CookieHeaderValue("key", "value")); //where headers is a HttpResponseHeaders

这篇关于在HttpAuthenticationContext设置的Cookie值IAuthenticationFilter的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆