[英]how do i get a bearer token in a .Net console application?
I was following this tutorial about how to authorize and get a bearer token from a web-api server. 我正在按照本教程讲解如何授权和从Web-api服务器获取承载令牌。 The tasks performed there through fiddler are pretty simple, but, when I tried to do the same from a console application the request fails with a 400 Bad Request Error
. 通过fiddler在那里执行的任务非常简单,但是,当我尝试从控制台应用程序执行相同任务时,请求失败,并显示400 Bad Request Error
。 Here is the code that makes the request to the server: 这是向服务器发出请求的代码:
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"];
}
can someone help me in determining what I am doing wrong here? 有人可以帮助我确定我在做什么错吗? or is there some other approach I should use to get the authentication token? 还是我应该使用其他方法来获取身份验证令牌?
FormUrlEncodedContent is in System.Net.Http 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;
}
}
I'm not able to test this myself right now, but I think you've missed out some text in your authCredentials
. 我现在无法自己对此进行测试,但是我认为您已经错过了authCredentials
一些文本。 It should look like this: 它看起来应该像这样:
var authCredentials = "grant_type=password&userName=" + user + "&password=" + password;
Note the additional: grant_type=password& that I added at the beginning. 请注意我在开头添加的其他内容: grant_type = password& 。 This updated whole string authCredentials
should be the only thing in your request body. 更新后的整个字符串authCredentials
应该是您请求正文中的唯一内容。
Assuming the request succeeds and it doesn't fail for other reasons, eg your username or password is not valid, then you should be able to get back your token data. 假设请求成功并且由于其他原因(例如您的用户名或密码无效)而不会失败,那么您应该能够取回令牌数据。
Also, the response will contain the access_token
in a json-formatted string in its body, not in a cookie header where you're reading it from. 同样,响应将在主体中以json格式的字符串包含access_token
,而不是从中读取它的cookie头中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.