簡體   English   中英

如何在.Net控制台應用程序中獲取承載令牌?

[英]how do i get a bearer token in a .Net console application?

我正在按照教程講解如何授權和從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"];
    }

有人可以幫助我確定我在做什么錯嗎? 還是我應該使用其他方法來獲取身份驗證令牌?

FormUrlEncodedContent在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頭中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM