how to edit a user's information on WordPress Api - reactjs

I'm using react native. I want to edit a user's information by a user id. so wordpress provides the api. when i'm using, getting error 401.
Request failed with status code 401
docs: https://developer.wordpress.org/rest-api/reference/users/#update-a-user
const userDate = {
first_name: userDataAccount.firstName,
last_name: userDataAccount.lastName,
};
const user = await WordpressApi.post("/wp-json/wp/v2/users/" + userFullInfo.id, userDate);
why is that? Please help me...

i have fixed my problem. i added auth header in proper way even it didn't connected, getting error 401. but put http instead of https, it connects well. So that's ssl related problem, i need to double check wp ssl connection. Thank you

Related

Not able to make a GET request to the django REST API backend for the id=1 article, from axios in reactjs

I have a frontend application built using reactjs and django rest framework is used to serve this frontend using APIs. The django rest APIs are working fine, I have checked via Postman.
When I make a GET request to http://127.0.0.1:8000/articles/, I get the list of articles, and when I click on one of them, it is supposed to take me to the article detail page for that specific id of the article. This is done by making a GET request to http://127.0.0.1:8000/articles/id.
The problem is, when I make GET request for id=2,3,4,5,... , it works fine. But when I try to make a request for id=1, I get the following error at console of chrome browser
Access to XMLHttpRequest at 'http://127.0.0.1:8000/articles/1' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Error: Network Error
at createError (createError.js:16)
at XMLHttpRequest.handleError (xhr.js:84)
So, the request is not made at all(I verified from server side). All I get is the above error.
Please note that there is no such error for articles/2 or articles/3 and so on. I have allowed the relevant host in django settings.py file.
This is the code I have for the article detail page.
function ArticlePage(props) {
const [MainArticle, setMainArticle] = useState({});
const {id} = useParams()
const url = 'http://127.0.0.1:8000/articles/'+id;
useEffect(() => {
console.log("hello world");
axios.get(url)
.then((response) => {
setMainArticle(response.data);
console.log(response.data);
})
.catch((error)=>console.log(error))
}, [url]);
return (
<section className="postsBody">
<Article
title={MainArticle.title}
author={MainArticle.author}
timestamp={MainArticle.timestamp}
content={MainArticle.content}
/>
</section>
)
}
Please help me out with this error, via debugging I came to know that the problem is not in the server side, the GET request works for id=1 via postman.
I figured out the problem eventually. The problem is the browser cache. I updated django, djago-rest-framework, react and react-router-dom. Then I did a hard reload of the localhost:3000 website and it eventually started working. The key point is to clear the browser cache just after you add corsheaders and it will work. I took help from this Question
It's because of the CORS policy. Even if you allow the sites in the settings, you need to explicitly enable those websites to access content from your backend. Install cors headers app in Django and set the allowed origins. The documentation for cors headers has sufficient information.

Adding bearer token to swagger requests using swagger-client

I'm trying to add a bearer JWT token to a swagger request upon login of an account but I can't seem to get it working. The documentation leaves a lot to be desired.
const SWAGGER_CLIENT = SwaggerClient(".../api.yml");
const carsResponse = await SWAGGER_CLIENT.client.execute({ operationId: "getCars" }); // I need { Authorizations: Bearer ${token}} here
If it's not possible to add it there then I can always create the client above with the token upon a successful login.
I think the issue is the syntax more than anything. There is virtually no documentation on how to use the .execute() method which is very frustrating. FWIW; I'm using the execute method and passing in tag names to make it more reusable than using the generated functions e.g., getCars(), addCar() etc. I don't know if this is the "right" way to use Swagger but it makes sense to me.
Is is possible to add it globally so I needn't include it in every request? The token will need to be added upon a successful login. It's a CRA application using Redux.
If somebody could explain, or provide a small example of adding the authorization bearer token to the request above that be fantastic and greatly appreciated.
Thanks all.
We will be renaming Try It Out Executor to HTTP client for OAS operations. Thanks for your input!

My url is working in Postman but Not working when using it from a browser?

I hope you are doing fine, I have a small problem, I am devolopping an API using Symfony 4, and Working with ReactJs in the frontend, So I am sending my data to the server using axios, here is it :
import Axios from "axios";
const sendLoginData = (username, password) => {
Axios.post("localhost/api/login_check", { username, password }).then(
response => {
console.log(response);
}
);
};
export default sendLoginData;
The data is sent right, but it seems like my route is not known I get this error in the console :
xhr.js:166 POST http://localhost:3000/localhost/api/login_check 404
(Not Found)
But When I use the same url on Postman, I get my token right, which means my authentication was fine.
So, I verified some answers and found something similar to mine, a person who user .NET for the backend and was getting the same errors, but from what I understood data was sent to the server with parameters in the url, But my case is different I believe.
I don't know How to solve this, and any help would be much appreciated.
Any help would be much appreciated.
Add the scheme in your request.
In postman you are requesting http://localhost/api/login_check, but with axios you are requesting http://localhost/localhost/api/login_check.
To solve that:
Axios.post("http://localhost/api/login_check")

Dahua api give 401 Unauthorised error in get method angular js

I call a dahua API for preset response in angular js but it gives me a 401 Unauthorised error.
My code is below :
var streamurl='http://admin:123456#192.168.1.202/cgi-bin/ptz.cgi?action=start&channel=0&code=PositionABS&arg1=180&arg2=190&arg3=10';
$http.get(streamurl, { withCredentials: true })
.then(function(response2) {
console.log(response2.data);
});
I could be wrong but I think you are getting login screen with that request. I've read through documentation and I have found your way of authentication only working on rtsp:// protocol, and for http I believe you should modify headers, and encode your username/pasword to base64, here's documentation:
ftp://ftp.wintel.fi/drivers/dahua/SDK-HTTP_ohjelmointi/DAHUA_IPC_HTTP_API_V1.00x.pdf
Also you should probably use this since you are using AngularJS/NodeJS, it will make your life easier - or check how this guy did his authentication and "borrow" from him:
https://github.com/nayrnet/node-dahua-api
How to Fix the 401 Unauthorized Error
Check for errors in the URL. It's possible that the 401 Unauthorized error appeared because the URL was typed incorrectly or the link that was clicked on points to the wrong URL - one that is for authorized users only.
If you're sure the URL is valid, visit the website's main page and look for a link that says Login or Secure Access. Enter your credentials here and then try the page again. If you don't have credentials, follow the instructions provided on the website for setting up an account.
If you're sure the page you're trying to reach shouldn't need authorization, the 401 Unauthorized error message may be a mistake. At that point, it's probably best to contact the webmaster or other website contact and inform them of the problem.
The 401 Unauthorized error can also appear immediately after login, which is an indication that the website received your username and password but found something about them to be invalid (e.g. your password is incorrect). Follow whatever process is in place at the website to regain access to their system.
From https://www.lifewire.com/401-unauthorized-error-what-it-is-and-how-to-fix-it-2622934

Alexa, Unable to link your skill

I am creating custom skill in Alexa which uses account linking. I have created my own authentication server using OAuth2 php library and I have configured the authorization url and token urls in skill configuration.
When I try account linking from Alexa mobile app, I get error 'unable to link your skill'. following is my work progress.
Alexa app is able to open my authentication url.
I am able authorize and provide authorization code with redirect uri.
Alexa is requesting for access token using authorization code previously provided.
I am able validate authorization code and response back with access token and refresh token.
Alexa fails in this step to link with my skill. It say's 'Unable to link your skill'.
I have gone through my forums about the same, but couldn't find what exactly the issue is. Could any one please help me out in this regard.
I was facing the same issue too , the problem was solved by selecting "credentials in request body" (default being Http basic) for "Client Authentication Scheme", since the access token in my case was sent in the body of the message. Check how the authentication token is sent by your server.
If your redirect link is currently:
https://layla.amazon.com/api/skill/link/xxxxxxxxxxxxxx?code=xxxxxxxxx&state=xxxxx
You need to change the ? to a #
e.g.
https://layla.amazon.com/api/skill/link/xxxxxxxxxxxxxx#code=xxxxxxxxx&state=xxxxx
Thought this might help anyone wondering how the Alexa service is posting to their OAuth endpoint since it's pretty opaque and undocumented. The redirect to the Alexa service initiates a POST request to the defined OAuth endpoint with the post body in x-www-form-urlencoded format not JSON. So the POST looks like this.
​
POST /authentication/1/oauth HTTP/1.1 url.Values{} grant_type=authorization_code&code=XXXXXXXXXXXXXXXXXXXXXXXXX&redirect_uri=https%253A%252F%252Fpitangui.amazon.com%252Fapi%252Fskill%252Flink%252FM9BEOG3DM65SQ&client_id=XXXXXXXXXXXXXXXXXXXXXX
If your endpoint isn't parsing this data or expecting some format that can be unmarshaled easily then it is probably failing with a 406 response.
In my case the problem was with the Client secret,
In google developer console add your skill redirect URIs
and recheck the client secret you provide in the alexa skill Authorization grant type
My issue was with the final AccessToken call. I was assuming it was using a GET request, so I only catered for this in my function. It is actually creating an access token. So it's using a POST.
After I updated my function to use a post and return the AccessToken in JSON format it all works fine.
Maybe the following steps will help you identify the problem:
Add console.log('LOGS', response) to your Lambda function.
Activate the skill and login in the Alexa app
Go back to your Lambda function and check the last logs for the LOGS entry.
If you find that the Lambda function is invoked than the problem is not from your OAuth server, but you may need to handle the "AcceptGrant directive" in your Lambda function as it is motioned here: https://developer.amazon.com/en-US/docs/alexa/device-apis/alexa-authorization.html#directives
adjust your Lambda function to:
exports.handler = function (request, context) {
if (request.directive.header.namespace === 'Alexa.Authorization' && request.directive.header.name === 'AcceptGrant') {
log("DEBUG:", "Authorization request", JSON.stringify(request));
handleAcceptGrant(request, context);
}
function handleAcceptGrant(request, context) {
var response = {
event: {
header: {
"namespace": "Alexa.Authorization",
"name": "AcceptGrant.Response",
"messageId": request.directive.header.messageId,
"payloadVersion": "3"
},
payload: {}
}
};
log("DEBUG", "Alexa.Authorization ", JSON.stringify(response));
context.succeed(response);
}
If the problem is with the AcceptGrant then The account linking should be now successful.

Resources