我遵循本教程学习使用Identity。有益的是,作者在自己的服务器上提供了一个代码的工作示例。我制作了这个控制台应用程序,它可以执行以下操作:
- 注册帐户
- 检索此帐户的令牌
-
使用此令牌检索信息。
using System; using System.Collections.Generic; using System.Net.Http; using System.Net.Http.Headers; namespace IdentityConsoleApp { class Program { static void Main(string[] args) { string userName = "john4"; string password = "Password@123"; var registerResult = Register(userName, password); Console.WriteLine("Registration Status Code: {0}", registerResult); string token = GetToken(userName, password); Console.WriteLine(""); Console.WriteLine("Access Token:"); Console.WriteLine(token); Console.WriteLine(""); Console.WriteLine(GetOrders(token)); Console.Read(); } static string Register(string name, string apassword) { var registerModel = new { userName = name, password = apassword, confirmPassword = apassword }; using (var client = new HttpClient()) { var response = client.PostAsJsonAsync( " http://ngauthenticationapi.azurewebsites.net/api/account/register", registerModel).Result; return response.StatusCode.ToString(); } } 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(" http://ngauthenticationapi.azurewebsites.net/token", content).Result; return response.Content.ReadAsStringAsync().Result; } } static string GetOrders(string token) { using (var client = new HttpClient()) { client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token); var response = client.GetAsync(" http://ngauthenticationapi.azurewebsites.net/api/Orders").Result; return response.Content.ReadAsStringAsync().Result; } } } }
这段代码很容易在VisualStudio中复制并粘贴到新的C#控制台项目中。只需将"John4"替换为任何尚未使用的随机用户名即可。
我得到以下输出:
注册状态代码:OK
访问令牌:{〔访问令牌内容〕}
{"消息":"此请求的授权已被拒绝"}
假设教程作者的软件工作正常,为什么我不能通过bearertoken授权?我传递的代币出了什么问题?
在您的代码中,函数GetToken的响应将返回JSON对象,而不仅仅是access_token属性,因此您应该提取access_token字段,然后将其发送到端点,您当前从GetToken收到的响应如下所示:
{
"access_token": "pXuyMK2GmuffgCTJJrFDBsJ_JqJ0qkIkEePhswVSjIv-A35OB7WoFxiYGg-WdjyCEonEjtmcondVTmdZE97T03WQ0agPbwTizdgxYCVE3rPJ9BmqT84M66Z0XXCrYnMj9OYl5SmmzcJpmlQd7v2jGG5WkRvJeOeqy1Ez2boXByo2QFDp5X7TqSokhz1Pvsusa3ot4-wgmpVkF6DTpctzv_gXFhjAPHs7NHFFsm_zuyRRvWKkekmATKg-4QJPlxlIn84BvDxNSgs9gQFH8nNFl37-P5BV4PJY43IC7otxBsgJymATFxdPFblcXb1aGIsnPuhU_Q",
"token_type": "bearer",
"expires_in": 1799,
"as:client_id": "",
"userName": "Taiseer",
".issued": "Thu, 05 Mar 2015 20:34:16 GMT",
".expires": "Thu, 05 Mar 2015 21:04:16 GMT"
}