我正在学习使用Identity this教程。有用的是,作者在他自己的服务器上提供了他的代码的工作示例。我已经使这个控制台应用程序执行以下操作:
使用此令牌检索信息。
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;
}
}
}
}
此代码很容易复制并粘贴到Visual Studio中的新C#控制台项目中。只需更换&#34; John4&#34;任何尚未使用的随机用户名。
我得到以下输出:
注册状态代码:确定
访问令牌: {[访问令牌内容]}
{&#34; message&#34;:&#34;此请求已拒绝授权&#34;}
假设教程作者的软件工作正常,为什么我无法通过bearertoken授权?我传递的令牌有什么问题?
答案 0 :(得分:2)
在您的代码中,函数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"
}