Я пытаюсь получить токен из внешнего API, это работает, когда я пытаюсь войти в веб-приложение и когда я пытаюсь отправить запрос через почтальона.Для этого запроса мне нужно установить тип контента x-www-form-urlencoded
.Я знаю, как это сделать, но всегда кажется, что он возвращает 400 неправильных запросов и говорит мне, что grant_type недействителен.Итак, чтобы начать этот квест, вот код, который работает, который будет вызываться при входе в систему:
Код такой, как показано ниже: -
var _login = function (loginData) {
var data = ["grant_type=password&username=", loginData.userName, "&password=", loginData.password].join('');
var deferred = $q.defer();
$http.post([serviceBase, "token"].join(''), data, { headers: { "Content-Type": "application/x-www-form-urlencoded" } }).success(function (response) {
console.log("login response", response);
localStorageService.set(_keyAuthorizationData, { token: response.access_token, userName: loginData.userName });
_authentication.isAuth = true;
_authentication.userName = loginData.userName;
deferred.resolve(response);
}).error(function (err, status) {
_logOut();
deferred.reject(err);
});
return deferred.promise;
};
loginData будет заполняться данными изформа входа в систему.
и вот мой второй вызов внешнего API, который возвращает неверный запрос 400
var _transferPersoon = function (portal, data) {
var externalAPI = "";
if (portal == "portal1") {
externalAPI = "https://urltoportal/webapi/";
} else if (portal == "portal2") {
externalAPI = "https://urltoportal/webapi/";
} else if (portal == "portal3") {
externalAPI = "https://urltoportal/webapi/";
} else if (portal == "portal4") {
externalAPI = "https://urltoportal/webapi/";
} else {
externalAPI = serviceBase;
}
var tokenData = {
username: "cactustransfer",
password: "bbbbbb",
grant_type: "password"
};
var data = ["grant_type=password&username=", "transferaccount", "&password=", "password"].join('');
$http.post([externalAPI, "token"].join(''), data, { headers: { "Content-Type": "application/x-www-form-urlencoded" } }).success(function (response) {
return response.access_token;
})
}
. Эта ошибка возвращается и отображается в Google Chrome:
{error: "unsupported_grant_type"}
этот запрос отправляется и проходит через это промежуточное ПО аутентификации в моем веб-интерфейсе ASP.NET:
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
Cactus.Business.DataModel.GEBRUIKER gebruiker = null;
context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] {"*"});
var identity = new ClaimsIdentity(context.Options.AuthenticationType);
/*
* Authenticatie methode voor het verplaatsen van personeel
* Deze kan niet uitgevoerd worden als het request IP niet in het lijstje van hosts staat.
* Dit is een extra beveiliging.
*/
if (context.UserName == "cactustransfer")
{
if (!hostVerify.IsValidHost(context.Request.RemoteIpAddress))
{
using (UnitOfWork work = new UnitOfWork())
{
gebruiker = work.GebruikerRepository.ValidateUser("transferaccount", "password");
}
}
}
if (gebruiker == null)
{
using (UnitOfWork work = new UnitOfWork())
{
gebruiker = work.GebruikerRepository.ValidateUser(context.UserName, context.Password);
if (gebruiker == null)
{
context.SetError("invalid_grant",
"The username or password is incorrect, or you have insufficient rights", context.Request.RemoteIpAddress);
return;
}
}
}
identity.AddClaim(new Claim("sub", context.UserName));
identity.AddClaim(new Claim("role", "user"));
identity.AddClaim(new Claim("providerID", gebruiker.gebruikerId.ToString()));
//identity.AddClaim(new Claim("providerID", gebruiker.persoon.ToString()));
context.Validated(identity);
}
и здесьмой запрос, который я тестирую в почтальоне, и его результат:
![enter image description here](https://i.stack.imgur.com/UQ5l7.png)
Я проверил и попробовал следующие решения:
Как отправить данные формы в формате urlencoded с $ http без jQuery?
https://github.com/thephpleague/oauth2-server/issues/261
NOTE имя пользователя, которое я использую в Postman, на самом делетак же, как имя пользователя transferaccount
РЕДАКТИРОВАТЬ:
Вот заголовок запросаВ Google Chrome показано имя пользователя: первый - это логин, который связывается с локальным API, второй - пытается отправить запрос на внешний API ![enter image description here](https://i.stack.imgur.com/YVuJS.png)
![enter image description here](https://i.stack.imgur.com/esZf2.png)
ОБНОВЛЕНИЕ:
Все функции, связанные с обработкой данных с помощью внешних API-интерфейсов, перенесены в локальные веб-API ASP.NET.Таким образом, я знаю, как заставить это работать.Но на самом деле это не решение, а обходной путь.