在asp.net上,承载令牌认证失败

时间:2018-01-18 18:04:46

标签: asp.net authentication get client bearer-token

我正在尝试在网络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;

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;
        }
    }


}

我的问题是: enter image description here

如何使用令牌身份验证制作承载? 或者是其他一些我不能正确做到的事情?

谢谢!

1 个答案:

答案 0 :(得分:1)

您需要使用以下http正文密钥值对向您的web api授权终端发送有效请求(例如&#34; username, password, client_id and grant_type=password&#34;):await client.PostAsync("token", content);。 (请务必遵循您的请求的内容类型标题)

用于该用途ApiToken = await JsonConvert.DeserializeObject<Token>(response.Content.ReadAsStringAsync());

如果授权成功,您将收到包含access_token的响应。您可以使用令牌对象反序列化为(client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", ApiToken.ToString());

在您需要进行身份验证的任何后续请求的标头中添加该令牌:授权:Bearer {acces_token_value}

li

关于这个话题有很多资源,对我来说最有趣的是: http://bitoftech.net/2014/06/01/token-based-authentication-asp-net-web-api-2-owin-asp-net-identity/