跨域表单身份验证(使用WebClient和cookie)

时间:2014-02-04 19:07:39

标签: c# asp.net-mvc authentication webclient mobile-application

我有2个站点,第一个站点是基本表单身份验证系统和一些方法,需要对用户进行身份验证。在第二个我使用修改后的WebClient(它可以使用cookie)并发送请求进行身份验证和请求后进行安全操作。第一步都是OK,第一个服务器返回AUTH cookie作为响应并记住它,第二步它发送AUTH cookie的安全操作请求,但在第一个站点,我们的请求未经授权! Request.isauthenticated = false

为什么?此请求的AUTH cookie有效。

这是网站№1WebClient请求的代码。

//Create an instance of your new CookieAware Web Client
var client = new CookieAwareWebClient();

//Authenticate (username and password can be either hard-coded or pulled from a settings area)
var values = new NameValueCollection { { "Name", "name" }, { "Password", "1234" } };

//Perform authentication - after this has been performed the cookie will be stored within the Web Client
client.UploadValues(new Uri("http://localhost:15536/Plugins/ProductListGetter/login"), "POST", values);
var _cookies = client.ResponseHeaders["Set-Cookie"];

client.UploadString(new Uri("http://localhost:15536/Plugins/ProductListGetter/ChangeNameForCurrentUser"), "POST", "Example Message");
client.UploadString(new Uri("http://localhost:15536/Plugins/ProductListGetter/ChangeNameForCurrentUser"), "POST", "Example Message");
client.Dispose();

修改WebClient的代码

public class CookieAwareWebClient : WebClient
{
    //Properties to handle implementing a timeout
    private int? _timeout = null;
    public int? Timeout
    {
        get
        {
            return _timeout;
        }
        set
        {
            _timeout = value;
        }
    }

    //A CookieContainer class to house the Cookie once it is contained within one of the Requests
    public CookieContainer CookieContainer { get; private set; }

    //Constructor
    public CookieAwareWebClient()
    {
        CookieContainer = new CookieContainer();
    }

    //Method to handle setting the optional timeout (in milliseconds)
    public void SetTimeout(int timeout)
    {
        _timeout = timeout;
    }

    //This handles using and storing the Cookie information as well as managing the Request timeout
    protected override WebRequest GetWebRequest(Uri address)
    {
        //Handles the CookieContainer
        var request = (HttpWebRequest)base.GetWebRequest(address);
        request.CookieContainer = CookieContainer;
        //Sets the Timeout if it exists
        if (_timeout.HasValue)
        {
            request.Timeout = _timeout.Value;
        }
        return request;
    }

0 个答案:

没有答案