简体   繁体   English

如何在.Net控制台应用程序中获取承载令牌?

[英]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.

相关问题 如何通过桌面/控制台应用程序使用带有不记名令牌的 ASP.NET Web API 2.0 - How to consume ASP.NET Web API 2.0 with bearer token via a desktop/console application 我如何获取AD用户名,以便使用angular-js SPA / ASP.NET-MCV启动承载令牌身份验证 - How do I get the AD username in order to initiate bearer token authentication with angular-js SPA / ASP.NET-MCV 在控制台应用程序中验证Azure AD承载令牌 - Validation of an Azure AD Bearer Token in a Console Application 如何从asp.net获取承载令牌作为http响应 - How to get bearer token as http response from asp.net 如何从 Azure 获取受保护的 .net 核心 API 的不记名令牌 - How to get bearer token from Azure for protected .net core API 如何使用 B2C 和 Blazor 获取 JWT 不记名令牌 - How Do I Get the JWT Bearer Token Using B2C and Blazor 如何在HTTP请求的标头中添加承载令牌? - How do I add a Bearer Token to the header of a HTTP request? 如何从浏览器获取 OAuth2 不记名令牌? - How can I get an OAuth2 bearer token from the browser? 如何在 .NET 控制台应用程序中获取应用程序的路径? - How can I get the application's path in a .NET console application? 使用RestSharp,如何使用oAuth2 Bearer令牌执行对ASP.NET Web API的POST请求? - Using RestSharp, how do I execute a POST request to my ASP.NET Web API with an oAuth2 Bearer token?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM