如何在.net控制台应用程序中获得承载令牌

本文关键字:令牌 应用程序 net 控制台 | 更新日期: 2023-09-27 18:13:43

我正在学习如何从web-api服务器授权和获取承载令牌。通过fiddler执行的任务非常简单,但是,当我试图从控制台应用程序执行相同的任务时,400 Bad Request Error的请求失败了。下面是向服务器发出请求的代码:

var request = WebRequest.Create("http://localhost:12698/token") as HttpWebRequest;
    request.Method = "POST";
    request.ContentType = "application/x-www-form-urlencoded";
    request.CookieContainer = new CookieContainer();         
    var authCredentials = "userName=" + user + "&password=" + password;
    byte[] bytes = System.Text.Encoding.UTF8.GetBytes(authCredentials);
    request.ContentLength = bytes.Length;
    using (var requestStream = request.GetRequestStream()){
        requestStream.Write(bytes, 0, bytes.Length);
    }
    using (var response = request.GetResponse() as HttpWebResponse){
        authCookie = response.Cookies["access_token"];
    }

有人能帮我确定我在这里做错了什么吗?或者我应该使用其他方法来获取身份验证令牌?

如何在.net控制台应用程序中获得承载令牌

FormUrlEncodedContent is in System.Net.Http

        static string GetToken(string userName, string password)
        {
            var pairs = new List<KeyValuePair<string, string>>
                        {
                            new KeyValuePair<string, string>( "grant_type", "password" ), 
                            new KeyValuePair<string, string>( "userName", userName ), 
                            new KeyValuePair<string, string> ( "password", password )
                        };
            var content = new FormUrlEncodedContent(pairs);
            using (var client = new HttpClient())
            {
                var response = 
                    client.PostAsync("https://localhost:12698/Token", content).Result;
                return response.Content.ReadAsStringAsync().Result;
            }
        }

我现在无法自己测试,但我认为你在authCredentials中遗漏了一些文本。它应该看起来像这样:

var authCredentials = "grant_type=password&userName=" + user + "&password=" + password;

请注意我在开头添加的附加:grant_type=password&。这个更新的整个字符串authCredentials应该是你的请求体中唯一的东西。

假设请求成功并且没有因为其他原因而失败,例如您的用户名或密码无效,那么您应该能够找回您的令牌数据。

此外,响应将在其主体中以json格式的字符串包含access_token,而不是在您读取它的cookie头中。