Querying graphql from Ionic via Native Http - ionic-framework

I'm migrating some services from Rest to Graphql in an Ionic App. I use the Ionic/Cordova native http plugin in order to make requests to my server, in the following way:
import {HTTP} from '#ionic-native/http/ngx'
#Injectable()
export class ApiProvider {
private server = "https://api.myserver.com/'
constructor(
private nativeHttp:HTTP
)
{}
getData(path:string,params = "")
{
const url = this.server + path + params
return this.nativeHttp.get(url,{},{
'Content-Type':'application/json'
})
}
}
My question is: How can I pass a graphql query in it? I've tried making the full url look like this https://api.myserver.com/graphql?query={people{id,name}} but I got the following error from graphql:
{
"errors": [
{
"message": "Unknown operation named \"IntrospectionQuery\"."
}
]
}
which differs from the successful result that I get in Postman for the exact same url.
How can I make this query using the http plugin?
Thank you in beforehand!

Related

How to retrieve auth0 access token inside Axios Config file?

hope you’re all well and safe!
I'm currently working on a Vue 3 application with Pinia as my store, Auth0 Vue SDK for authentication/authorization and Axios to call my backend API.
In Auth0 docs, they recommend an access token be retrieved using the getAccessTokenSilently() method everytime I want to call my backend API:
const { getAccessTokenSilently } = useAuth0();
const accessToken = await getAccessTokenSilently();
The problem is I have to type this whenever I use axios in my component files to call my backend API with the access token.
Since I have too many endpoints, my plan is to pass the access token once in an axios request interceptor and use Pinia actions to call my APIs.
I’ve created a /config/axios.js file in my application that contains the following:
//Import Axios Library and Auth0
import axios from 'axios';
import { useAuth0 } from "#auth0/auth0-vue"
//Create instance of axios
const instance = axios.create({
baseURL: 'http://localhost:5000/api/v1'
});
// Create a request interceptor for my instance and get accessToken on the fly
instance.interceptors.request.use(async (config) => {
const { getAccessTokenSilently } = useAuth0();
const accessToken = await getAccessTokenSilently();
config.headers['Authorization'] = accessToken;
return config;
}, (error) => {
return Promise.reject(error)
});
export default instance;
Simple enough, just create a baseURL and intercept requests to add the authorization header with the access token.
Now in Pinia, I've created a user store that'll fetch users with the axios config as seen below:
//Import the Pinia Library
import { defineStore } from 'pinia'
//Import the Axios Library for API calls
import axiosConfig from "#/config/axios.js"
export const useUserStore = defineStore('user', {
state: () => ({
user:{}
}),
getters: {
getUser(state){
return state.user
}
},
actions: {
async fetchUser(){
try {
const data = await axiosConfig.get('/profile')
this.user = data.data
} catch (error) {
console.log("User Pinia error: " + error)
}
}
},
})
And lastly in my component file, I just import the store and call the Pinia action fetchUsers.
When trying an axios call, I get the following error!
TypeError: auth0_auth0_vue__WEBPACK_IMPORTED_MODULE_5_.useAuth0() is undefined
I can't figure out how to retrieve the access token from auth0 library in my interceptor function.
A similar question was raised as an issue on auth0-vue github:
https://github.com/auth0/auth0-vue/issues/99
The above link describes numerous approaches. I went for the plugin approach that is described in this PR, namely:
https://github.com/auth0-samples/auth0-vue-samples/commit/997f262dabbab355291e5710c51d8056a5b142cf
But the issue was officially resolved by offering a mechanism to allow the sdk from outside a vue component:
https://github.com/auth0/auth0-vue/issues/99#issuecomment-1099704276

NestJS in conjunction with Axios

I have a NestJS application that acts as a BFF (Backend for Frontend) which exposes a certain endpoint. That endpoint uses Axios to send multiple requests to my backend. Some of these requests to the backend can return different status codes, which I want to propagate back to the caller. However, I don't want to catch every request manually. Currently, it throws 500 if any Axios request fails in the pipeline.
I thought about implementing a global exception filter for Axios exceptions, that will check the returned status code from Axios and throw an appropriate HttpException exception that NestJS will catch (e.g. if any Axios request failed and returned 401, throw an UnauthorizedException which NestJS will catch and return back to the client, instead of 500).
Is it a possible approach, or is there anything else I can do?
If you want, you can use Exception filters
So first you need to create a file for the exception filter.
// axios.exception-filter.ts
import { ArgumentsHost, Catch, ExceptionFilter } from '#nestjs/common';
import { Request, Response } from 'express';
import { AxiosError } from 'axios';
#Catch(AxiosError)
export class HttpExceptionFilter implements ExceptionFilter {
catch(exception: AxiosError, host: ArgumentsHost) {
const ctx = host.switchToHttp();
const response = ctx.getResponse<Response>();
const request = ctx.getRequest<Request>();
console.log(exception);
response.status(400).json({
statusCode: 400,
timestamp: new Date().toISOString(),
path: request.url,
});
}
}
And in your main.ts add this
app.useGlobalFilters(new HttpExceptionFilter());
And now in response.status(400).json({}) you can add everything you want in your body. Like the error message of Axios.

Vapor: sending post requests

I am trying to send an HTTP request using Vapor, to verify a recaptcha
Google's Captcha api is defined as follows:
URL: https://www.google.com/recaptcha/api/siteverify METHOD: POST
POST Parameter
Description
secret
Required. The shared key between your site and reCAPTCHA.
response
 Required. The user response token provided by the reCAPTCHA client-side integration on your site. 
remoteip
Optional. The user's IP address. 
So I need to make a POST request with 2 parameters (secret and response).
In Swift i have:
func routes(_ app: Application throws {
app.on(.POST, "website_form") { req -> EventLoopFuture<View> in
var form: FromRequest = /*initial values*/
/*decode form data*/
do {
req.client.post("https://www.google.com/recaptcha/api/siteverify") { auth_req in
try auth_req.content.encode(CaptchaRequestBody(secret: "6Lfoo98dAAAAALRlUoTH9LhZukUHRPzO__2L0k3y", response: form.recaptcha_response), as: .formData)
auth_req.headers = ["Content-Type": "application/x-www-form-urlencoded"]
}.whenSuccess { resp_val in
print("Response: \(resp_val)")
}
}
}
/* More code */
}
struct CaptchaRequestBody: Content {
let secret: String
let response: String
}
After running the post request, I get following error code:
{
"success": false,
"error-codes": [
"missing-input-secret"
]
}
I can not find any solution that works, even the official Vapor docs were of no use, could someone please help me?
The Google API requires requests to be URL-encoded forms. By using the .formData setting, you are enforcing MultiPart.
Change the setting to .urlEncodedForm, which ensures the request conforms to the Google API requirement.
As Nick stated: the problem was that instead of .formData, I needed to use .urlEncodedForm.

POST data ionic 3 and backend API restful laravel

I have an issue about POST data at add student page. I'm using ionic 3 and backend API restful laravel, I tried this POST in postman and it's works, but I got an error message "invalid token or token not provided" after click Add button (refer the first picture). I'm not sure how to write method with auth token.
You can refer my provider (second image) ,addstudent.ts (third image), button html (forth image) for reference
Thanks in advance.
Suppose you stored your token in a storage (e.g localStorage or sessionStorage), you can do the following:
Step1: Add Auth provider and extend BaseRequestOptions
import { BaseRequestOptions, RequestOptions, RequestOptionsArgs } from '#angular/http';
import { Injectable } from '#angular/core';
#Injectable()
export class AuthProvider extends BaseRequestOptions {
constructor() {
super();
this.headers.set('Content-Type', 'application/json');
}
merge(options?: RequestOptionsArgs): RequestOptions {
let newOptions = super.merge(options);
let accessToken = localStorage.getItem('accessToken');
if (accessToken !== null && accessToken !== undefined) {
let token: AcessTokenResponse = JSON.parse(accessToken);
newOptions.headers.set('Authorization', token.token_type + ' ' + token.access_token);
}
return newOptions;
}
}
Step2: Add AuthProvider under providers in app.module.ts file
As per my exprience you need to add RequestOptions in your POST call like below:
let options = new RequestOptions({
headers: headers
});
this.http.post(this.apiUrl+'/addstudent', addStudent, options)
As in your code you are creating Header but not passing it into post request.
Try above code Hope this will help you to get your API work.

.Net Core: Validate Anti Forgery Token with Ionic front end

I have looked all over and have found similar solutions, but nothing that matches exactly what I'm working on.
We have a .net core MVC website with an API Controller for handling requests from an ionic mobile app which we are also developing.
In most cases, adding [ValidateAntiForgeryToken] to the API controller actions works. I have gone through the process of generating the token, passing it to Ionic, and storing it in the request headers for validation.
Here is the code I am using to fetch and store the token:
static XSRF_TOKEN_KEY: string = "X-XSRF-TOKEN";
static XSRF_TOKEN_NAME_KEY: string = "X-XSRF-TOKEN-NAME";
constructor(){}
static getXsrfToken(http: HTTP) : {tokenName: string, token: string} {
let tokenName: string = window.sessionStorage.getItem(ValidationManager.XSRF_TOKEN_NAME_KEY);
let token: string = window.sessionStorage.getItem(ValidationManager.XSRF_TOKEN_KEY);
if(!tokenName || !token){
this.fetchXsrfToken(http);
tokenName= window.sessionStorage.getItem(ValidationManager.XSRF_TOKEN_NAME_KEY);
token = window.sessionStorage.getItem(ValidationManager.XSRF_TOKEN_KEY);
}
return {
tokenName: tokenName,
token: token
};
}
private static setXsrfToken({ token, tokenName }: { token: string, tokenName: string }) {
window.sessionStorage.setItem(ValidationManager.XSRF_TOKEN_KEY, token);
window.sessionStorage.setItem(ValidationManager.XSRF_TOKEN_NAME_KEY, tokenName);
}
private static fetchXsrfToken(http: HTTP) {
let token: string = window.sessionStorage.getItem(ValidationManager.XSRF_TOKEN_KEY);
let tokenName: string = window.sessionStorage.getItem(ValidationManager.XSRF_TOKEN_NAME_KEY);
if (!token || !tokenName) {
let apiUrl: string = AppConfig.apiUrl + "/GetAntiforgeryToken";
http.get(apiUrl, {}, {})
.then(r => this.setXsrfToken(JSON.parse(r.data)))
.catch(r => console.error("Could not fetch XSRFTOKEN", r));
} else {
this.setXsrfToken({ token: token, tokenName: tokenName });
}
}
Here is the action in my controller that serves anti forgery tokens:
[HttpGet]
public override IActionResult GetAntiforgeryToken()
{
var tokens = _antiforgery.GetAndStoreTokens(HttpContext);
return new ObjectResult(new
{
token = tokens.RequestToken,
tokenName = tokens.HeaderName
});
}
I set the headers of the http plugin by calling this function from the view's associated typescript file:
initializeHttp() {
let token = ValidationManager.getXsrfToken(this.http);
this.http.setHeader(token.tokenName, token.token);
console.log("Http Initialized: ", token);
}
then any request I make with the http plugin is validated properly in the controller's action:
this.http.post(apiUrl, {}, {}).then(response => {
that.navCtrl.setRoot(HomePage);
});
Up to this point, everything works great. The problem arises when I try to use XmlHttpRequest to for a POST instead of the built-in http plugin:
let file = {
name: e.srcElement.files[0].name,
file: e.srcElement.files[0],
};
let formData: FormData = new FormData();
formData.append('file', file.file);
let xhr: XMLHttpRequest = new XMLHttpRequest();
xhr.open('POST', apiUrl, true);
console.log("setting request header: ", tokenVal); //verify that tokenVal is correct
xhr.setRequestHeader("X-XSRF-TOKEN", tokenVal);
xhr.send(formData);
If I remove the [ValidateAntiForgeryToken] attribute from the controller's action, the file is posted properly. However, nothing I have tried has worked with the attribute being included.
I believe the issue has something to do with the validation tokens being added to a cookie automatically by Ionic, and the cookie is passed along with the request from the http plugin. However, XMLHttpRequest does not pass the cookie along (and is unable to do so?).
I have read up on the subject quite a bit over the past few days but I admit that this validation is still mostly a black box to me. Is there a way to validate the request in my action using only the token which is passed up in the header?
The reason I am running into this problem is that I need to upload a file, which I was unable to do using the http plugin. There are solutions for uploading images using Ionic's file-transfer plugin, but it has been deprecated and the release notes suggest using XmlHttpRequest instead.
Other things I have tried:
I have found solutions for .net standard which use System.Web.Helpers.AntiForgery for custom validation on the server, but this namespace is not included in .net core and I could not find an equivalent.
I tried many different ways to post the file using the http plugin (since it has no issues validating the antiForgery token). Everything I tried resulted in the action being hit but the file being posted was always null. A solution which uploads a file using the http plugin would also be acceptable.
Why is it that I was able to spend two full days on this problem, but as soon as I post a question about it, I find the answer? Sometimes I think the internet gods are just messing with me.
As it turns out, the native http plugin has an uploadFile() function that I never saw mentioned anywhere else. Here's what the solution does:
Use the fileChooser plugin to select a file from the phone's storage
Use the filePath plugin to resolve the native filesystem path of the image.
Use http.uploadFile() instead of http.post()
This works because as mentioned above, I was able to properly set the validation token in the http plugin's header to be accepted by the controller.
And here is the code:
let apiUrl: string = AppConfig.apiUrl + "/UploadImage/";
this.fileChooser.open().then(
uri => {
this.filePath.resolveNativePath(uri).then(resolvedPath => {
loader.present();
this.http.uploadFile(apiUrl,{ },{ },resolvedPath, "image")
.then(result => {
loader.dismiss();
toastOptions.message = "File uploaded successfully!";
let toast = this.toastCtrl.create(toastOptions);
toast.present();
let json = JSON.parse(result.data);
this.event.imageUrl = json.imgUrl;
})
.catch(err => {
console.log("error: ", err);
loader.dismiss();
toastOptions.message = "Error uploading file";
let toast = this.toastCtrl.create(toastOptions);
toast.present();
});
});
}
).catch(
e => console.log(e)
);