如何验证Prestashop API REST客户端



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

$"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(基本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:a1sRefitRequestBuilderImplementation.cs:line 274
--- End of stack trace from previous location where exception was thrown ---

使用重新安装的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));

我仍然收到同样的错误信息。

创建这样的类:

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

我使用了Reform的ConfigureHttpClient函数,但您实际上可以通过创建自己的HttpClient对象并像这样配置DefaultRequestHeaders来实现这一点。

相关内容

  • 没有找到相关文章

最新更新