Authenticating ASP.NET MVC user from a WPF application

后端 未结 2 1669
孤城傲影
孤城傲影 2021-02-06 19:14

How can I authenticate a user (with username and password) of an ASP.NET MVC application? I\'m trying to do this using WebClient, passing NetworkCredentials

2条回答
  •  粉色の甜心
    2021-02-06 19:42

    This code worked for me, using Darin's approach and the WebClientEx class from their link. My WPF form has to authenticate to the MVC app and store the returned authentication cookie's name and value in static properties CookieName and CookieValue. The CreateUser() function is then able to access a secured action in the MVC app.

        //************************************************
        //************************************************
        private void Authenticate(object sender, RoutedEventArgs e)
        {
            using (var client = new WebClientEx())
            {
                var values = new NameValueCollection
                {
                    { "UserName", "xxx" },
                    { "Password", "yyy" },
                };
    
                var byteResponse = client.UploadValues("http://localhost/MyMvcApp/Account/Login", values);
                var responseString = Encoding.ASCII.GetString(byteResponse); //debugging
    
                CookieCollection authCookie = client.CookieContainer.GetCookies(new Uri("http://localhost/"));
                if (authCookie.Count > 0)
                {
                    CookieName = authCookie[0].Name;
                    CookieValue = authCookie[0].Value;
                }
            }
        }
    
        //************************************************
        //************************************************
        private void CreateUser(object sender, RoutedEventArgs e)
        {
            using (var client = new WebClientEx())
            {
                var user = new NameValueCollection
                {
                    {"FirstName" , "Xavier"},
                    {"LastName" , "McLann"},
                    {"EmailAddress" , "xavier@aol.com"},
                    {"Phone" , "234445585"}
                };
    
                if (!String.IsNullOrEmpty(CookieName) && !String.IsNullOrEmpty(CookieValue))
                    client.CookieContainer.Add(new Cookie(CookieName, CookieValue,"/","localhost"));
    
                var byteResponse = client.UploadValues("http://localhost/MyMvcApp/Home/Create", user);
                var responseString = Encoding.ASCII.GetString(byteResponse); //debugging
            }
        }
    

提交回复
热议问题