如何验证Prestashop API REST客户端

我为正在开发的Bot应用程序创建了一个接口,用于使用Refit调用Prestashop API。 为了调用该API,您需要使用我拥有的Prestashop API密钥进行身份验证。要使用浏览器查询,我只需要调用以下格式的网址:

$"https://{ApiKey}@{mypage}.com/api"

它使用@符号前指定的Api密钥进行身份验证。要定义改装HttpClient,请在Startup.cs中使用以下代码:

// This is the ApiUrl from the appsettings.json file
var apiUrl = Configuration.GetSection("PrestashopSettings").GetSection("ApiUrl").Value;

// We add the Api and specify the de/serialization will be XML
services.AddRefitClient<IPrestashopApi>(
    new RefitSettings
    {
        ContentSerializer = new XmlContentSerializer()
    })
    .ConfigureHttpClient(c => c.BaseAddress = new System.Uri(apiUrl));

然后,将API注入到我的一个类中,并调用其功能之一。该URL似乎正确,如果我将完整的URL(基本+ [Get] URL)粘贴到浏览器中,它将正确返回XML。但是当我从应用程序执行此操作时,它将返回异常:

microsoft.Bot.Builder.Integration.AspNet.Core.BotFrameworkHttpAdapter:Error: Exception caught : Refit.ApiException: Response status code does not indicate success: 401 (Unauthorized).
   at Refit.RequestBuilderImplementation.<>c__DisplayClass14_0`2.<<BuildCancellabletaskFuncForMethod>b__0>d.MoveNext() in D:\a\1\s\Refit\RequestBuilderImplementation.cs:line 274
--- End of stack trace from previous location where exception was thrown ---

使用Refit的HttpClient进行身份验证的正确方法是什么?我在做错什么吗?

更新:

所以我尝试了这个:

public class HttpAuthentication : HttpClientHandler
{
    private readonly string Token;
    public HttpAuthentication(string token)
    {
        Token = token ?? throw new ArgumentException(nameof(token));
    }

    protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request,CancellationToken cancellationToken)
    {
        var token = Token;
        request.Headers.Authorization = new AuthenticationHeaderValue("Bearer",token);
        return await base.SendAsync(request,cancellationToken).ConfigureAwait(false);
    }
}

这是我的Startup.cs中的代码:

var apiKey = Configuration.GetSection("PrestashopSettings").GetSection("ApiKey").Value;
var storeUrl = Configuration.GetSection("PrestashopSettings").GetSection("StoreUrl").Value;

// We add the Api and specify the de/serialization will be XML,and we specify the Authentication Client.
services.AddRefitClient<IPrestashopApi>(
    new RefitSettings
    {
        ContentSerializer = new XmlContentSerializer()
    })
    .ConfigureHttpClient((c) => c.BaseAddress = new System.Uri(storeUrl))
    .ConfigureHttpMessageHandlerBuilder((c) => new HttpAuthentication(apiKey));

我仍然收到相同的错误消息。

lzhyq 回答:如何验证Prestashop API REST客户端

创建这样的类:

 public class AuthenticatedHttp : HttpClientHandler
    {
        private readonly string Token;
        public AuthenticatedHttp(string token)
        {
            if (token == null)
            {
                throw new ArgumentNullException(nameof(token));
            }
            this.Token = token;
        }
        protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request,CancellationToken cancellationToken)
        {
            // See if the request has an authorize header
            var token = this.Token;
            request.Headers.Authorization = new AuthenticationHeaderValue("Bearer",token);
            return await base.SendAsync(request,cancellationToken).ConfigureAwait(false);
        }
    }

并将令牌发送给此类:

var token = await GetAccessToken();
            var RestReq = RestService.For<IPerson>(new HttpClient(new AuthenticatedHttp(token)) { BaseAddress = new Uri(Url) });
,

好的,我最终弄清楚了。 首先,我想指出有两种解决方法。

第一个解决方案

您实际上可以使用API​​密钥作为请求参数进行身份验证,其密钥为ws_key,因此您可以像这样发送呼叫:

"https://api.yourapiaddress.com/yourentity?ws_key={API KEY HERE}"

第二个解决方案

这是我选择的,只是添加一个Header参数。发现Prestashop API 1.7使用基本授权并将API密钥用作用户名和空密码,因此我在Startup.cs中构建了这样的标头:

// Encode your Api Key
String encoded = Convert.ToBase64String(System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes(apiKey));

// Add the API to DI in Dialog classes
services.AddRefitClient<IPrestashopApi>(
    new RefitSettings
    {
        ContentSerializer = new XmlContentSerializer()
    })
    .ConfigureHttpClient((c) => c.BaseAddress = new Uri(storeUrl))
    .ConfigureHttpClient((c) => c.DefaultRequestHeaders.Add("Authorization","Basic " + encoded));

我使用了Retrofit的ConfigureHttpClient函数,但是实际上可以通过创建自己的HttpClient对象并像这样配置DefaultRequestHeaders来实现相同目的。

本文链接:https://www.f2er.com/3066692.html

大家都在问