I am trying to use Drupal Webform REST.
I got an error "The 'restful post webform_rest_submit' permission is required." on browser console. I have enabled modules and REST resources as mentioned.
I used Authorization, the Auth generated in Postman, using basic auth.
I am struggling to use 'x-csrf-token' in postman.
I want to use submit the form by an anonymous user. Do I still need Authorization, will just token not work on same-origin?
const handleSubmit = async (e) => {
e.preventDefault();
await axios({
method: 'GET',
url: `${baseurl.URL}/session/token`,
headers: {
'Accept': 'application/vnd.api+json',
}
})
.then(response => response)
.then((token)=>{
console.log("CSRF TODKEN", token.data);
axios({
method: 'post',
url: `${baseurl.URL}/webform_rest/submit?_format=json`,
headers:{
'Accept': 'application/vnd.api+json',
'Content-Type': 'application/json',
'X-CSRF-Token': token.data,
'Authorization':'Basic $S$EDSnVMXDICYbVGJ'
},
data: {
"webform_id": "contact_form",
"name":name,
"email": email,
"subject": subject,
"message": message
}
})
})
.then(response => {
console.log(response)
response.status === 200 && console.log("Form successfully submitted")
})
.catch(err => console.log("SUBMIT FAIL ERROR ",err))```
It worked. I gave permission to "Access POST on Webform Submit resource" to anonymous users.
Related
I installed jwt plugin and I configured jwt token to access WordPress rest API, when I use postman everything is good and I can have a successful post request but when I post data using axios in vuejs I get this error
response: "{\"code\":\"rest_cannot_create_user\",\"message\":\"Sorry, you are not allowed to create new users.\",\"data\":{\"status\":401}}"
below code is my post request in my app:
Register() {
const data = JSON.stringify({
name: this.username,
username: this.username,
email: this.email,
password: this.password,
roles: ['editor'],
});
axios
.post('http://localhost/wp-json/wp/v2/users', data, {
headers: {
Authorization:
'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOjEsIm5hbWUiOiJQZWRyYW0iLCJpYXQiOjE2NTQ1MTY4MDgsImV4cCI6MTgxMjE5NjgwOH0.0NoZwWpMMDw0_5xd3anIEKq_djwdV3vqbGMw_UeSvYI',
'Content-Type': 'application/json',
},
})
.then((response) => {
console.log(response);
})
.catch((error) => {
console.log(error);
});
},
also when I use the code in nodejs in the backend application everything works fine.
after sending in body "email" and "password" https://identitytoolkit.googleapis.com/ returns a few objects in the response.
One of them is "idToken": with a value of the token.
What do I need?
I need to get this token, store it in variable and reuse it in further tests.
So far I prepared something like this:
it("Get a fresh admin firebase token", () => {
cy.request({
method: "POST",
url: "https://identitytoolkit.googleapis.com/...",
body: {
"email": "myUsername",
"password": "myPassword",
"returnSecureToken": true
},
headers: {
accept: "application/json"
}
}).then((responseToLog) => {
cy.log(JSON.stringify(responseToLog.body))
}).then(($response) => {
expect($response.status).to.eq(200);
})
})
})```
Above code works, but cy.log() returns the whole body response. How can I separate only idToken and reuse it in my next API scenarios?
Considering that idToken in in response body so inside then() you can directly wrap the value and save it using an alias and then use it later.
it('Get a fresh admin firebase token', () => {
cy.request({
method: 'POST',
url: 'https://identitytoolkit.googleapis.com/...',
body: {
email: 'myUsername',
password: 'myPassword',
returnSecureToken: true,
},
headers: {
accept: 'application/json',
},
}).then((response) => {
cy.wrap(response.body.idToken).as('token')
})
})
cy.get('#token').then((token) => {
cy.log(token) //logs token or Do anything with token here
})
In case you want to use the token in a different it block you can:
describe('Test Suite', () => {
var token
it('Get a fresh admin firebase token', () => {
cy.request({
method: 'POST',
url: 'https://identitytoolkit.googleapis.com/...',
body: {
email: 'myUsername',
password: 'myPassword',
returnSecureToken: true,
},
headers: {
accept: 'application/json',
},
}).then((response) => {
token = response.body.idToken
})
})
it('Use the token here', () => {
cy.log(token) //prints token
//use token here
})
})
I have done logging-in WordPress Rest API with JWT Plugin passing administrator account and password and stores the received token in AsyncStorage like this.
await AsyncStorage.setItem(
'user',
JSON.stringify({
token: userData.token,
user_email: userData.user_email,
user_nicename: userData.user_nicename,
user_display_name: userData.user_display_name,
}),
);
Then I manage to get all posts including private post by including the token with request header like this,
let userInfo = await AsyncStorage.getItem('user');
let jsonUser = await JSON.parse(userInfo);
let credential = 'Bearer ' + jsonUser.token;
fetch('http://localhost/reactnativewordpress/wp-json/wp/v2/posts', {
headers: {
Authorization: credential,
},
method: 'GET',
withCredentials: true,
credentials: 'include',
})
.then(response => response.json())
.then(responseJson => {
this.setState({
items: responseJson
});
})
.catch(error => {
console.log('Error :' + error);
});
The responseJson have only public posts, no private post at all.
Thanks for help.
You need to add the
status=private
in your request,
like this http://localhost:8000/wp-json/wp/v2/posts?status=private
With that, the Authorization header should run ;)
I have an axios call fetching some json data.
Method is get, and i need credentials to login.
checkCreds2 (username, password) {
var configJITIT = {
withCredentials: true,
method: 'get',
url: 'xxx',
dataType: 'json',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
params: {
$format: 'json'
}
}
this.axios(configJITIT)
.then(function (response) {
console.log(response.config)
if (response.status === 200) {
console.log('success!')
}
})
.catch(function (error) {...})
}
Thing is, when i do the call and type in my credentials, the console logs an error: GET Status 200 (OK)
The problem is, my data is not displayed as long my request gets an error.
I have to refresh the page so the data is displayed.
It really is an error.
After refreshing the page, everything's fine.
I don't want to have to refresh the page.
Any ideas?
Your params object looks a bit strange. Did you try to use the get method from axios ? It has all the correct configuration you need, you just have to provide your additional parameters.
Example:
axios.get('/user', {
params: {
ID: 12345
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
So I able to successfully send a request via postman, but whenever I throw it into fetch I get back a 401 error.
export const createUser = () => {
return async (dispatch) => {
dispatch({ type: CREATE_USER });
console.log('we are in the create user function');
try {
let response = await fetch('secret.com/v1/login/signup', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
email: 'test1231273123#test.com',
password: 'Asadasd123123',
first_name: 'joe',
last_name: 'doe',
phone_number: '373738'
})
});
console.log('response ' + JSON.stringify(response));
} catch (error) {
console.log(error);
}
};
};
Here is the error I keep receiving.
response {"type":"default","status":401,"ok":false,"headers":{"map":{"access-control-allow-methods":["GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS"],"access-control-allow-origin":["*"],"connection":["keep-alive"],"access-control-allow-credentials":["true"],"content-length":["188"],"content-type":["text/html; charset=utf-8"],"access-control-allow-headers":["Content-Type, Accept, Authorization"],"www-authenticate":["Basic realm=\"Restricted\""],"date":["Thu, 12 Jan 2017 16:57:58 GMT"],"server":["nginx"]}},"url":"https://secret.com/v1/login/signup","_bodyInit":{},"_bodyBlob":{}}
My backend developer believes I ran into a cross domain issue and need to setup a proxy server? "set up some proxy server (I would recommend nginx) that would proxy ajax queries to our API domain"
I think it has something to do with fetch? Ideas?
I believe you need to provide the protocol, change:
await fetch('secret.com/v1/login/signup'...
to
await fetch('http://secret.com/v1/login/signup'