I have a curious CORS error in a Rails API setup with post request from Vue signup,
Despite setting the values at localhost:8080 for the Vue app and localhost:3000 for the response, it still wont allow access.
Rails CORs settings are below.
Rails.application.config.middleware.insert_before 0, Rack::Cors do
allow do
origins 'localhost:8080'
resource 'localhost:3000',
headers: :any,
methods: [:get, :post, :put, :patch, :delete, :options, :head]
end
end
The request method using Nuxt axios plugin is below'
// Check submit
signin () {
this.$plain.post( '/api/v1/sign_up/', { email: this.email, password: this.password, password_confirmation: this.password_confirmation} )
.then(response => this.signinSuccessful(response))
.catch(error => this.signinFail)
console.log({ email: this.email, password: this.password, password_confirmation: this.password_confirmation });
alert('Processing!');
},
And the axios plugin code itself is also below.
/* eslint-disable */
import axios from 'axios'
export default function ({ $axios, store }, inject) {
const API_URL = "http://localhost:3000"
const secured = axios.create({
baseURL: API_URL,
withCredentials: true,
headers: {
"Content-Type": "application/json",
},
})
const plain = axios.create({
baseURL: API_URL,
withCredentials: true,
headers: {
"Content-Type": "application/json"
},
})
secured.interceptors.request.use((config) => {
const method = config.method.toUpperCase();
if (method !== "OPTIONS" && method !== "GET") {
config.headers = {
...config.headers,
"X-CSRF-TOKEN": localStorage.csrf,
};
}
return config;
});
secured.interceptors.request.use(null, (error) => {
if (error.response && error.response.config && error.response.status === 401) {
return plain
.post("/refresh", {}, { headers: { "X-CSRF-TOKEN": localStorage.csrf } })
.then((response) => {
localStorage.csrf = response.data.csrf;
localStorage.signedIn = true;
let retryConfig = error.response.config;
retryConfig.headers["X-CSRF"] = localStorage.csrf;
return plain.request(retryConfig);
})
.catch((error) => {
delete localStorage.csrf;
delete localStorage.signedIn;
location.replace("/");
return Promise.reject(error);
});
} else {
return Promise.reject(error);
}
})
inject('plain', plain)
inject('secured', secured)
}
It is getting rejected due to CORs policy for authenticated requests as in screenshot, and I tried changing "with-credentials" to false but got error bad request, any tips on this welcome?
Related
I started developing a new MS Teams Application and I am trying to authenticate a MS Teams user on my app's backend by following the source code of
https://github.com/OfficeDev/Microsoft-Teams-Samples/tree/main/samples/app-sso
But unfortunately when I am trying to create a SimpleGraphClient with the token acquired by this function
// Get Access Token
const getAccessToken = async(req) => {
return new Promise((resolve, reject) => {
const { tenantId, token } = reqData(req);
const scopes = ['User.Read']; //['User.Read', 'email', 'offline_access', 'openid', 'profile'];
const url = `https://login.microsoftonline.com/${ tenantId }/oauth2/v2.0/token`;
const params = {
client_id: process.env.MicrosoftAppId,
client_secret: process.env.MicrosoftAppPassword,
grant_type: 'urn:ietf:params:oauth:grant-type:jwt-bearer',
assertion: token,
requested_token_use: 'on_behalf_of',
scope: scopes.join(' ')
};
// eslint-disable-next-line no-undef
fetch(url, {
method: 'POST',
body: querystring.stringify(params),
headers: {
Accept: 'application/json',
'Content-Type': 'application/x-www-form-urlencoded'
}
}).then(result => {
if (result.status !== 200) {
result.json().then(json => {
// eslint-disable-next-line prefer-promise-reject-errors
reject({ error: json.error });
});
} else {
result.json().then(async json => {
resolve(json.access_token);
});
}
});
});
};
I am taking the exception :
throw new Error('SimpleGraphClient: Invalid token received.');
What am I doing wrong?
I'm authenticating to Laravel (7.3) Passport with the following configuration:
nuxt.config.js
auth: {
redirect: {
login: '/login',
logout: '/login',
home: '/'
},
strategies: {
'laravel.passport': {
url: 'http://laravel.test',
client_id: '2',
client_secret: 'S0gpcgfIDgbvIHCL3jIhSICAiTsTUMOR0k5mdaCi',
redirect_uri: 'http://localhost:3000'
}
}
}
Authentication method in pages/login.vue:
async nuxtLaravelPassport() {
try {
const response = await this.$auth
.loginWith('laravel.passport')
.then(result => {
console.log(result)
})
} catch (err) {
console.log(err)
}
},
It brings me to the authentication page of Laravel, then I log in and I'm redirected to my Nuxt.js home page with a code and state as parameters.
What should I do with these code and state ? Get a token ? If yes, how ?
Hello everyone and thanks in advance ...
I'm trying to use the Contact Form7 APIs to fill in and submit a form from an Angular NativeScript App.
I have tried different solutions but I always get the same error response.
{"into":"#","status":"validation_failed","message":"Oops, there seems to be some error in the fields. Check and try again, please.","invalidFields":[{"into":"span.wpcf7-form-control-wrap.nome","message":"Attention, this field is required!","idref":null},{"into":"span.wpcf7-form-control-wrap.mail","message":"Attention, this field is required!","idref":null}]}
In the example I have entered static values in the body for convenience
Help me ;(
attempt 1
onTappedInvia(): void {
fetch("http://www.example.com/wp-json/contact-form-7/v1/contact-forms/{id}/feedback", {
method: "POST",
headers: { "Content-Type": "multipart/form-data" },
body: JSON.stringify({
nome: "Test API",
mail: "test#test.test"
})
}).then((r) => r.json())
.then((response) => {
const result = response.json;
console.log(response);
}).catch((e) => {
console.log(e);
});
}
attempt 2
deliverForm() {
var formData: any = new FormData();
formData.append('nome', "Test API");
formData.append('email', "test#test.test");
formData.append('your-message', "Test API");
this.submitted=true;
console.log(formData);
this.formService.create(formData)
.subscribe(
data => {
console.log('Invoice successfully uploaded');
console.log('Error'+ JSON.stringify(data));
},
error => {
console.log('Error'+ JSON.stringify(error));
});
console.log('USCITO');
}
and formService
const HttpUploadOptions = {
headers: new HttpHeaders({ "Content-Type": "multipart/form-data;" })
}
#Injectable({
providedIn: 'root'
})
export class FormService {
constructor(
private HttpClient: HttpClient
) { }
create(formData){
return this.HttpClient.post('http://www.example.com/wp-json/contact-form-7/v1/contact-forms/{id}/feedback', formData, HttpUploadOptions)
}
}
The problem was with the Content-Type. i tried with application/x-www-form-urlencoded and it works!
fetch("http:www.aficfestival.it/wp-json/contact-form-7/v1/contact-forms/5173/feedback?", {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: form
}).then((r) => r.json())
.then((response) => {
const result = response.json;
console.log(response);
}).catch((e) => {
console.log(e);
});
}
newbie to React looking for some help... I'm using React to make API requests like so:
class CatsApi {
static createCat(cat) {
const request = new Request('http://localhost:4300/api/v1/cats', {
method: 'POST',
headers: new Headers({
'Content-Type': 'application/json'
}),
body: JSON.stringify(cat)
});
return fetch(request).then(response => {
return response.json();
}).catch(error => {
return error;
});
}
Meanwhile, I have authentication to my API via react-devise:
https://github.com/timscott/react-devise
Which has a method getBearerToken like so: https://github.com/timscott/react-devise/blob/master/src/actions/authTokenStore.js
How do I use getBearerToken to pass the API the token so API requests are authenticated with the token?
Thank you!
You can use the Authorization header like:
{ 'Authorization': `Bearer ${authToken}` }
Using fetch you could try with something like:
fetch('http://localhost:4300/api/v1/cats', {
method: 'POST',
headers: {
'Authorization': `Bearer ${token}`
'Accept' : 'application/json',
'Content-Type' : 'application/json',
},
body: JSON.stringify({
cat : cat_value,
})
})
.then((response) => response.json())
.then((responseData) => { console.log(responseData) })
.catch((error) => { console.log(error) })
.done()
Also, it'd be great to see what's the Rails output in the console when you make a request, or the browser console.
I want to implement OAuth2 authorization in react native.I implemented code the following way.
const HOST_ADRESS = "192.168.173.1"; //change with your own host
const client_id = "app";
const username = "balan#gmail.com";
const password = "12345";
fetch('https://'+HOST_ADRESS+"/oauth/token", {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Cache-Control': 'no-cache'
},
body: "client_id=app&client_secret=app1234&grant_type=pass&username="+username+"&password="+password
})
.then((response) => response.json())
.then((responseJson) => {
console.log("******* RESPONSE ********* "+ JSON.stringify(responseJson));
})
.then((response) => response.text())
.then((responseText) => {
console.log("--------------responseText"+responseText);
console.log("******* RESPONSE ********* "+ JSON.stringify(responseJson));
})
.catch((error) => {
const data = {error: "A error happened"};
//redux error.
//dispatch(actionsCreators.errorLogin(data));
console.log("+++++++++++++++++++error"+error);
console.warn(error);
});
But it always get an error like
{"error":"unauthorized","error_description":"Full authentication is required to access this resource"}