asp.net上的承载令牌身份验证失败
我正在尝试在web api上发出GET请求。我构建客户端。问题似乎在于使用承载令牌进行身份验证。我已经看过很多帖子了,但是都没用 这是我的密码:asp.net上的承载令牌身份验证失败,asp.net,authentication,get,client,bearer-token,Asp.net,Authentication,Get,Client,Bearer Token,我正在尝试在web api上发出GET请求。我构建客户端。问题似乎在于使用承载令牌进行身份验证。我已经看过很多帖子了,但是都没用 这是我的密码: using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Threading.Tasks; namesp
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
namespace AuthUsingBearerToken
{
class Program
{
static void Main(string[] args)
{
RunClient();
Console.ReadLine();
}
static void RunClient()
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("uri");//address of web api
client.DefaultRequestHeaders.Accept.Clear();//removes all entries from system.net.http.headers...
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));//adds an entry to system in json format
//First Method i tried
//client.DefaultRequestHeaders.Accept.Add(new AuthenticationHeaderValue("Bearer ", "token from web api));
//Second method
// var token = "token from web api";
// client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
//Third Method
//client.DefaultRequestHeaders.Add("Authorization", "Bearer " + token);
GetPatient(client, "1").Wait();
}
}
public static async Task GetPatient(HttpClient client, string id)
{
try
{
HttpResponseMessage response = await client.GetAsync(""+id);
response.EnsureSuccessStatusCode();
Patient patient = await response.Content.ReadAsAsync<Patient>();
Console.WriteLine("Id: {0}\tName: {1}", patient.id, patient.patient_name);
}
catch (HttpRequestException e)
{
Console.WriteLine("{0}", e.Message);
throw;
}
}
}
我的问题是:
如何使用令牌身份验证创建承载?
还是我做得不对
谢谢大家! 您需要向web api授权端点发送有效请求,例如带有以下http正文键值对的\token:用户名、密码、客户端\u id和授权\u type=password。确保遵循请求标题的内容类型 对于该用途,请等待client.PostAsynctoken,content 如果授权成功,您将收到一个带有access_令牌的响应。您可以使用令牌对象反序列化为apitonk=await JsonConvert.DeserializeObjectresponse.Content.ReadAsStringAsync 将该令牌添加到需要验证的任何后续请求的头中:Authorization:Bearer{acces\u token\u value} client.DefaultRequestHeaders.Authorization=新的AuthenticationHeaderValueBearner,ApiToken.ToString 关于这个主题有很多资源,我最感兴趣的是: