issue post a resource with lucadegasperi/oauth2-server-laravel - api

Im having a problem for creating a resource, when i make a POST request to my route.
My route looks like:
Route::group(array('prefix' => 'api/v1', 'before' => 'oauth'), function()
{
//Media Route
Route::resource('media', 'PostController',['except' => ['create', 'edit']]);
});
when i post the resource it says i should provide an valid access token, but i already doing that. This is the resource uri.
appname.dev/api/v1/media/?access_token=ksfdkfjkfsj
even with:
appname.dev/api/v1/media?access_token=ksfdkfjkfsj
it doesn't work it throws an error with json response
"error": "invalid_request",
"error_description": "The request is missing a required parameter, includes an invalid parameter value, includes a parameter more than once, or is otherwise malformed. Check the \"access token\" parameter."
I'm testing this with the Postman plugin in chrome and using the lucadegasperi oauth2-server package for laravel.
What am i doing wrong?
Thx in advance

Related

Strapi doesn't authorize JWT

Good morning,
I've encountered a weird issue with my strapi-project.
I have a standard user model which I query for info on the user's profile page via the /users/me endpoint. This was all working fine last week but as I tried logging in this morning, the authorization appeared to not work anymore. I log my user in via this code:
....
async submitForm() {
axios.post('http://localhost:1337/auth/local', {
'identifier': this.email,
'password': this.password
})
.then((response) => {
const { jwt, user } = response.data;
window.localStorage.setItem('jwt', jwt);
window.localStorage.setItem('userData', JSON.stringify(user));
router.push('/dashboard');
})
.catch((e) => {
this.$store.commit('LOGIN_ERROR', e)
});
},
...
Which then redirects to my dashboard which queries the /users/me endpoint like so:
let token = localStorage.jwt;
axios.get(`http://localhost:1337/users/me`, {
headers: {
Authorization: `Bearer ${token}`
}
})
.then((response) => {
console.log(response.data);
})
A few days ago this was working fine, also the token variable used in the post contais the token returned from the backend after logging in. Now strapi gives me an error in the console:
[2021-10-16T07:16:52.568Z] debug GET /users/me (5 ms) 500
[2021-10-16T07:17:03.231Z] debug POST /auth/local (76 ms) 200
[2021-10-16T07:17:24.915Z] error TypeError: Cannot read property 'type' of null
at module.exports (/home/user/WebstormProjects/strapi-project/node_modules/strapi-plugin-users-permissions/config/policies/permissions.js:35:14)
at async /home/user/WebstormProjects/strapi-project/node_modules/strapi-utils/lib/policy.js:68:5
at async serve (/home/user/WebstormProjects/strapi-project/node_modules/koa-static/index.js:59:5)
at async /home/user/WebstormProjects/strapi-project/node_modules/strapi/lib/middlewares/parser/index.js:48:23
at async /home/user/WebstormProjects/strapi-project/node_modules/strapi/lib/middlewares/xss/index.js:26:9
My first guess was that maybe something with axios was wrong e.g. that the token wasn't sent correctly in the request so I tried the same thing with webstorm's http client:
POST http://localhost:1337/auth/local
Content-Type: application/json
{
"identifier": "test#test.com",
"password": "..."
}
Which returns the user and token:
"jwt": "<TOKEN>",
If I try using this token to authenticate the user, however a get a 401
GET http://localhost:1337/users/me
Authorization: "Bearer <token>"
Accept: application/json
returns
{
"statusCode": 401,
"error": "Unauthorized",
"message": "Invalid token."
}
So I tried figuring out what was going on there and after an hour I noticed that when looking at the user in the backend the user didn't have the authenticated role assigned. When I changed this manually in the backend, the request authorization works again.
So can anyone maybe tell me what is going on here? Because from my understanding, when POSTing valid credentials to /auth/local the user's role should change to Authenticated, which was working some days back.
Is there something I'm missing?
Any help would be greatly appreciated,
greetings, derelektrischemoench
Okay, so let me reply to your first part:
"Because from my understanding, when POSTing valid credentials to /auth/local the user's role should change to Authenticated"
Answer is, not really. When you send valid credentials to the auth/local, Strapi just checks the database for matching username/email and password. If a user is found, then it fetches the role assigned that user and puts all the data in ctx.state.user.role. So you could have many other roles, like Viewer, Commenter etc with each having different set of access limits.
The different roles can be created here:
http://localhost:1337/admin/settings/users-permissions/roles
So depending on the roles assigned, Strapi will just fetch and store the values in ctx.state.user.role on each request via the strapi-plugin-users-permissions plugin for your convenience, so that you can easily check which user it is and which role it has in any controller or service file using the ctx from the request to provide any additional functionality.
You can check how it does it in the following file:
node_modules/strapi-plugin-users-permissions/config/policies/permissions.js
Now coming to what could have caused it:
Well it could have been you yourself. Possibly while saving the user or viewing user details you could have removed the role from the user and saved the record.
The other possibility could be a database switch.
It can also be a Strapi version upgrade that caused, but it's highly unlikely.
You could have a update query in the your code that updates the user model, where you might have missed the role parameter. So check your code once.
Nevertheless, it can simply be solved by re-assigning the user roles via the users module.

How to get the data associated with the error response back?

I am making a request from the front-end to a route in my backend that is validating the token associated with a user, which would send an error response back to the front-end if the token has expired. I am sending some json with it but upon doing console.log of the error message in the catch block, the json sent along the error response is not shown.
Sending the error response like this
res.status(401).json({
message: 'User session has expired'
})
But the response that I am getting in the catch block in the front-end has no sign of the json sent with the error.
POST http://localhost:3001/check-validation 401 (Unauthorized)
Error: Request failed with status code 401
at createError (createError.js:17)
at settle (settle.js:19)
at XMLHttpRequest.handleLoad (xhr.js:78)
I don't understand why the json sent along the error response is not shown and how to get it?
Upon doing console.log of the error only the stacktrace of the error is shown and not the data associated with it. The data sent with it can be procured and depends on how the request has been made or by what library it has been made. If the request is made by axios then the following can be done:
axios.post('/formulas/create', {
name: "",
parts: ""
})
.then(response => {
console.log(response)
})
.catch(error => {
console.log(error.response.data.message)
});
Here, in axios the details of the error would be wrapped up in error.response. Whereas, if the request was made by the fetch API then something following can resolve the problem:
fetch('/401').then(function(response) {
if (response.status === 401) {
return response.json()
}
}).then(function(object) {
console.log(object.message)
})
P.S I was searching a lot regarding this problem but didn't get an answer on SO, neither got any article or docs regarding it, even the official Express docs on error handling were not helpful. At last, I understood that the problem lies with the library that is being used to make the request. That's why answering my own question to mark the presence of this question on SO. A detailed discussion can be found here related to axios and here related to fetch api

node-bigcommerce Get and Post Routes

I'm using the npm package, 'node bigcommerce', and I have all my API's setup but whenever I try to make a GET route, the error, Error: Request returned error code: 404 and body: The route is not found, check the URL, shows up. I don't know how or where to specify the url to find. Also, I have the same problem with POST Routes. The code is here. Thanks ahead!
var express = require('express'),
BigCommerce = require('node-bigcommerce');
var bigCommerce = new BigCommerce({
clientId: '* Client ID *',
secret: '* Secret *',
callback: 'https://store-xxi13.mybigcommerce.com',
responceType: 'json',
accessToken: '* Access Token *',
storeHash: 'xxi13'
});
bigCommerce.get('/happy', (data) =>{
console.log(data);
});
The path supplied in your get request, '/happy' is not a BigCommerce API endpoint--that's why you're getting a 404 not found. If you made a request to /products for example, it should work to pull product data.
Also, the callback would usually be a path on your app, not the store URL. For example, callback: 'https://myapplication.com/auth', would be the path on your app where you want the BigCommerce auth service to send your temporary code and Oauth token during the installation flow:
https://developer.bigcommerce.com/api/#app-installation-and-update-sequence
You can find examples of configuring the client and making requests in the README for the node-bigcommerce client:
https://github.com/getconversio/node-bigcommerce

AWS Amplify React Native, throwing 403 InvalidSignatureException when passing data to request

We create an API for authenticated identities only. so the only valid user can access it. the API is throwing 403 InvalidSignatureException whenever there is data in the body of any request.
we also tested the API on native Android. it is working fine with that.
our POST request code is the following,
API.post(apiName, path, {body:{key:value}}).then(response => {
consoloe.log(response);
}).catch(error => {
consoloe.log(error);
});
We have followed everything on GitHub and API gateway but not getting proper solution for it.
I also received the InvalidSignatureException.
I can't tell for sure what the issue is with your request, but I solved my problem by looking at the error response and figured out that my region was wrong (us_east_1 instead of us-east-1).
Try the following:
API.post(apiName, path, {body:{key:value}}).then(response => {
console.log(response);
}).catch(error => {
console.log(error.response); // <--
});
In my case the error.response was:
And under data.message the error was described
In my case I was just getting 403 with no message. After 30 mins I realised that my path variable was missing slash.

Linkedin token not valid

Here is a strange thing I am fighting against.
First of all I am using this simple-linkedinphp lib to perform API calls from my php backend.
I got a user access token from our IOS app which has the following structure:
{"access_token":"lettersAndSymbols","expires_in":5183999}
I store it in a variable called $token.
Then I try to get the user's profile with this token like this:
$linkedin = new \LinkedIn($this->linkedin_config);
$linkedin->setResponseFormat($linkedin::_RESPONSE_JSON);
$linkedin->setTokenAccess(array('oauth_token' => $token["access_token"], 'oauth_token_secret' => ""));
$linkedinUserJson = $linkedin->profile("~");
Then I get the response with error:
array(5) {
["linkedin"]=>
string(358) "{
"errorCode": 0,
"message": "[unauthorized]. The token used in the OAuth request is not valid. sameLettersAndSymbols",
"requestId": "74T6SY6ML6",
"status": 401,
"timestamp": 1376043937705
}
But when I try to open an api url in a browser with the same LettersAndSymbols like https://api.linkedin.com/v1/people/~?oauth2_access_token=LettersAndSymbols, I get the correct response with user object.
How can that be? Am I doing something wrong with the API lib?
I can see a problem in this line
$linkedin->setTokenAccess(array('oauth_token' => $token["access_token"], 'oauth_token_secret' => ""));
your must provide a secret to set the token access.
I found a nice example about Linkedin Integration, wich I like to share with you, I tested and it works just fine.
How to Integrate login with LinkedIn oAuth in PHP