Add a Bearer Token to a Breezejs fetchMetadata Call - breeze

My breeze services works great. But I just moved it behind a WSO2 API Manager. It now needs a Bearer Token for each call.
I have the Bearer Token. But I can't seem to figure out how to add it to the Metadata Call.
I tried something like this. But it did not add a header to the metadata call:
var ajaxAdapter: any = breeze.config.getAdapterInstance('ajax');
ajaxAdapter.defaultSettings = {
headers: {
"X-Test-Header": "foo2"
}
}
Does the fetchMetadata use a different system from the ajax adapter?
How can I add a header to the Fetch Metadata call?

Turns out I was using the Fetch API. So I had to do it that way. Here is what my setup looks like:
setupFetchClient() {
let httpClient = new HttpClient();
httpClient.configure(config => {
config.withDefaults({
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
}
})
.withInterceptor({
request(request: Request) {
let accessToken = getAccessToken();
request.headers.append('Authorization', 'Bearer ' + accessToken);
return request;
},
responseError(error) {
return error;
}
})
.useStandardConfiguration();
});
// Aurelia Specific Code.
Container.instance.registerInstance(HttpClient, httpClient);
}

Related

Getting 400 (Bad Request) on a POST request to Strapi

I am trying to post data to my Strapi project from a Flutter app.
I made sure that the permissions are enabled for unauthenticated users.
What is wrong with my request?
Future saveReview(usrReview, usrRating) async {
const endpoint = 'http://localhost:1337/api/reviews';
var url = Uri.parse(endpoint);
Map<String, String> headers = {
'Content-Type': 'application/json; charset=UTF-8',
};
var reviewObj = jsonEncode({
'review': usrReview,
'rating': usrRating,
});
var response = await http.post(
url,
headers: headers,
body: reviewObj,
);
print(response.statusCode);
}
The problem was that the structure of reviewObj was missing something. I had to include 'data' in it for it to work. Here is what the correct body should look like.
var reviewObj = jsonEncode({
'data': {
'review': usrReview,
'rating': usrRating,
}
});
I think this might fix you're problem! I recently ran into this same error a few days ago!
Basically you have to send the body of the POST request as a string.
Here's what it should look like!
Future saveReview(usrReview, usrRating) async {
const endpoint = 'http://localhost:1337/api/reviews';
var url = Uri.parse(endpoint);
Map<String, String> headers = {
'Content-Type': 'application/json; charset=UTF-8',
};
// Pass the JSON data as a whole string. Then the server should parse it
var reviewObj = '{"review": $usrReview, "rating": $usrRating}';
var response = await http.post(
url,
headers: headers,
body: reviewObj,
);
print(response.statusCode);
}
Give that a try and let me know if that works!

How to POST data to a URL from NestJs code?

I have a login form with username and password. I'm trying to validate these credentials using the Nest Js authentication strategy here. So in the corresponding auth.service.ts file, I'm using "nativescript core modules http" to do a POST request to OAuth URL to validate credentials . But this doesn't work:
import { Injectable } from '#nestjs/common';
import { request } from "tns-core-modules/http";
const OAUTH_URL = 'url';
#Injectable()
export class AuthService {
async validateUser(username: string, password: string): Promise<any> {
let data = new FormData();
data.set('client_id', 'sb-nestjs-app!t36258');
data.set('client_secret', 'XrHuBRhyvuVNYNJNHlWLgcuBIyc=');
data.set('username', username);
data.set('password', password);
data.set('grant_type', 'password');
data.set('response_type', 'token');
request({
url: OAUTH_URL,
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
"Accept": "application/json;charset=utf8"
},
content: data
}).then((response) => {
console.log('response => ' + response + ' statuscode ' + response.statusCode);
if (response.statusCode == 200) {
const token = response.content['access_token'];
//TODO:
// need to send scope also
return token;
}
}, (e) => {
console.log('error' + e);
return null;
});
return null;
}
}
When I run 'nest start' after above code in place, I receive Error: Cannot find module './http-request'
I'm not sure what is going here, I tried "npm install http-request" it didn't work either. Basically, I need to POST credentials to a OAuth url in NestJs. Any guidance? Thank you.
Try with HttpModule from NestJS.
Also you can try request from npm, but they deprecated this package. From what I saw on their discussion, the package still works but you will not have support for it, or anything. Here are some alternatives to it .
I'm not sure you are using the correct request npm module. I'm talking about:
import { request } from "tns-core-modules/http"
Good Luck!

Angular service not hitting the required method in ASP.NET Web API

I am working on project in which I want to add a value to an Oracle database and get value from it. I am using Angular 4 using VSCode and ASP.NET Web API using Visual Studio 2015 for services.
My Angular code is working well but it's not hitting the required method in the ASP.NET Web API while calling.
My Angular service code is
register(userInfo: any) {
debugger;
var url1 = this.baseUrl;
url1 += "api/signUp/SaveCustomer";
return this._http.post(url1,userInfo);
};
here base url is BASE_API_URL: "http://localhost:6705/.
My ASP.NET Web API service method is
[HttpPost]
public IHttpActionResult SaveCustomer( UserInfo user )
{
// int result;
// result = _customerManager.SaveCustomer(user);
// if (result > 0)
// {
// return Ok(result);
// }
// else
// {
// return NotFound();
// }
return null;
}
and its controller constructor is
public signUpController()
{
_customerManager = new CustomerManager();
}
When I run the project, I have put debugger at two places one at constructor and other at method Register. My control comes to constructor but its not hit the required method. I am really worried I am new to this technology. No error is showing on screen.
Use [FromBody] in action like this:
[HttpPost]
public IHttpActionResult SaveCustomer([FromBody] UserInfo user)
{
...
}
If you call Web API post method from Angular 2 type script, don't forget to add following header content and parameter object.
register(userInfo: any) {
var params = new URLSearchParams();
params.set('username', userInfo.username);
params.set('password', userInfo.password);
let headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded' });
var url1 = this.baseUrl;
url1 += "api/signUp/SaveCustomer";
return this._http.post(url1, params.toString(), { headers: headers })
};
Update
register(userInfo: any) {
//let headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded' });
let headers = new Headers({ 'Content-Type': 'application/json' });
var url1 = this.baseUrl;
url1 += "api/signUp";
console.log(url1);
return this._http.post(url1, userInfo, { headers: headers });
};

Angular2 Http post request not binding to ASP.NET 5 controller's action

I am initiating a post request from Angular2 to a ASP.NET 5 controller action. Angular is posting the data correctly and hitting the controller action but it is not being mapped to the parameters defined in controller action, the parameters are null. Meanwhile by inspecting through Request object Request.Form has the correct textual data but not binding to the model.
Angular
let body = JSON.stringify({ firstName: 'Ali' });
let headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded' });
this.http.post(this.url, body, { headers: headers })
.subscribe(
(data) => {
console.log('Response received');
console.log(data);
},
(err) => { console.log('Error'); },
() => console.log('Authentication Complete')
);
ASP.NET
[HttpPost]
public IActionResult DemoAction(string firstName)
{
var req = Request;
return null;
}
Request.Form has data in the form like {\"firstName\":\"Ali\"} but the parameter firstName is null
You try to send a JSON content (created using the JSON.stringify method) with a content type url encoded form.
You should try to use the application/json one:
let body = JSON.stringify({ firstName: 'Ali' });
let headers = new Headers({ 'Content-Type': 'application/json' });
this.http.post(this.url, body, { headers: headers })
Edit
If you want to provide a form content, you could leverage the URLSearchParams class:
var params = new URLSearchParams();
params.set('firstName', 'Ali');
let headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded' });
this.http.post(this.url, params.toString(), { headers: headers })
In this case you don't require to pass the header. look at here. you may try this.
this.http.post('/api/ControllerName/DemoAction?firstName=Ali')
.subscribe(
(data) => {
console.log('Response received');
console.log(data);
},
(err) => { console.log('Error'); },
() => console.log('Authentication Complete')
);
This will surely work.
Edited:
Figured out your problem.
First: When you are receiving paramter(s) at API end , you must use above portion.
second: When you are receiving object at API end, you must use below code.
I'm showing you with my setup as I don't know your object at server side.
let um=JSON.stringify({ Username: "Hello1",Password:"Hello2"});
let headers = new Headers({ 'Content-Type': 'application/json'});
this.http.post(this.url+'/Authentication',um,{ headers: headers })
.subscribe(...);
At server side I have following setup.
public class UserModel
{
public string Username { get; set; }
public string Password { get; set; }
}
[HttpPost]
public IHttpActionResult Authentication(UserModel um) // I m getting value here.
{
if (um.Username == "a" && um.Password == "a")
{
um.Username = um.Username;
um.Password = um.Password;
return Ok(um);
}
return NotFound();
}
Simple solution !! isn't it?
For me it works:
let headers = new Headers({ 'Content-Type': 'application/json' });
this.http.post(this.url, JSON.stringify({ firstName: 'Ali' }), { headers: headers })

WebApi 2 + Owin Use urlencoded body on token request

In my WebAPI2 app I use OAuth authentication through Owin middleware. In order to get token client should use application/x-www-form-urlencoded body in request.
function userAccount($resource, appSettings) {
return {
registration: $resource(appSettings.serverPath + "/api/Account/Register", null,
{
'registerUser' : { method : 'POST'}
}
),
login : $resource(appSettings.serverPath + "/Token", null,
{
'loginUser': {
method: 'POST',
headers: {
'Content-Type' : 'application/x-www-form-urlencoded'
},
transformRequest: function (data, headersGetter) {
var str = [];
for (var d in data) {
str.push(encodeURIComponent(d) + "=" + encodeURIComponent(data[d]));
}
return str.join("&");
}
}
}
)
}
}
But is there any method to override this behaviour to use raw body in json format? Instead of this: "grant_type=password&username=user&password=123456" want to use this: "{ grant_type: "password", username:"user", password="123456" }".
Appreciate any suggests.
You could set up an action in a controller as a "proxy" method that could accept the json in the body and then call the internal method with the url encoded parameters.

Resources