How to attach IOT policy to cognito identity using API gateway? - javascript

I am trying to attach iot policy to cognito identity using API gateway. Here is the aws doc.
I am getting "Missing Authentication Token" error message and status code 403 FORBIDDEN
Below is my code in react native,
return await fetch(
'https://myApiResourcePath/target-policies/policy_name',
{
method: 'PUT',
headers: {
'Content-Type':'application/json',
},
body: JSON.stringify({
identityId: use_id,
}),
}
)
.then((res) => {
return res.json();
})
.then((res) => {
console.log({ res });
})
.catch((err) => {
console.log(err);
});
Below is my mapping template in AWS ali gateway,
{
"target":"$input.path('$.identityId')"
}
The IAM role have AWSIoTConfigAccess only.
How can I able to use api gateway to attach policy?

Related

Spotify Web API / Next.js: Only getting data from one end-point

I'm pretty new to working with API's, and I'm currently trying to fetch some data from the Spotify API in a Next.js website.
The problem is that the only end-point that gives me any data is the 'top-tracks': (https://api.spotify.com/v1/me/top/tracks), all the other end-points I've tried gives this error:
Request failed FetchError: invalid json response body at https://api.spotify.com/v1/me/player/recently-played reason: Unexpected token U in JSON at position 0
This is the function I'm using to fetch data from the API:
const basic = Buffer.from(`${client_id}:${client_secret}`).toString("base64");
const TOKEN_ENDPOINT = `https://accounts.spotify.com/api/token`;
export default async function handler(req, res) {
const response = await fetch(TOKEN_ENDPOINT, {
method: "POST",
headers: {
Authorization: `Basic ${basic}`,
"Content-Type": "application/x-www-form-urlencoded",
},
body: querystring.stringify({
grant_type: "refresh_token",
refresh_token,
}),
})
.then((response) => response.json())
.then((data) => {
const access_token = data.access_token;
return fetch(`https://api.spotify.com/v1/me/player/recently-played`, {
method: "GET",
headers: {
Authorization: `Bearer ${access_token}`,
},
});
})
.then((response) => response.json())
.catch((err) => {
console.error("Request failed", err);
});
return res.status(200).json(response);
}
(First getting the access token, using clientId and secret from env-variables, then fetching data from API using said token)
Any idea of what I'm doing wrong here? All help is greatly appreciated :)
Also:
I've added the necessary scopes, so I should have permisssion to get the data!

Auth0 React Native patch user by Management API

I want to patch the user_metadata of a user in my Auth0 Authentication in react native but I get the following error:
{"error": "Unauthorized", "message": "Missing authentication", "statusCode": 401}
So I am importing Auth0 in my react native:
import Auth0 from "react-native-auth0";
const auth0 = new Auth0({
domain: Config.AUTH0_DOMAIN,
clientId: Config.AUTH0_CLIENT_ID
});
I use the constants Config.AUTH0_DOMAIN and Config.AUTH0_CLIENT_ID from my dashboard from my application.
As a next step I execute the following code:
login = () => {
auth0.webAuth
.authorize({
scope: Config.AUTHO_SCOPE,
audience: Config.AUTH0_AUDIENCE,
device: DeviceInfo.getUniqueID(),
prompt: "login"
})
.then(res => {
auth0.auth
.userInfo({token: res.accessToken})
.then(data => {
fetch(`https://<MY_AUTH_DOMAIN>/api/v2/users/${encodeURIComponent(data.sub)}`, {
method: "PATCH",
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
"metadata": {first_name: 'John', last_name: 'Doe', skillLevel: 'PRO!'}
})
}).then(res => res.json())
.then(async (data) => {
try {
console.log('user stored', data);
} catch (e) {
console.log("error while user storing", e)
}
})
})
})
}
Whereby Config.AUTHO_SCOPE and Config.AUTH0_AUDIENCE is also from my auth0's app dashboard.
Am I missing some authentication in my headers or is the Management API the wrong choice? Do I need to to this query probably from my Back-End?
Resources:
Official API Doc from the Management API: https://auth0.com/docs/api/management/v2?_ga=2.147997749.368915485.1617866251-2089752765.1617460658#!/Users/patch_users_by_id
Official react-native-auth0 doc: https://auth0.github.io/react-native-auth0/src_management_users.js.html
Thanks for the help!
I was having this issue and I got it working after a little work.
First, I had to configure my project to give metadata write permission in Auth0's dashboard at Applications/Apis.
The two I added were read:current_user and update:current_user_metadata.
Then, in my authorize request, I modified both scope and audience.
audience: 'https://<MY APP DOMAIN>/api/v2/'
scope: 'read:current_user update:current_user_metadata openid profile offline_access'
Next, I got the userId by passing my authentication token to auth.userInfo like so.
auth0.auth.userInfo({token: authToken}).then((response)=>{
return response.sub;
})
Finally, I used the value returned from response.sub along with the authToken that I had setup with special audience and scope to patch the user, and it worked successfully. UserId is what response.sub returned.
auth0.users(authToken).patchUser({id: userId, metadata: newUserMetadata});
EDIT:
One other issue I see with your code snippet, if you want to use fetch, is you didn't put a bearer authorization token in the header. Your fetch response will probably return with a 401 error if that's the case. The code should look something like this:
const serverResponse = await fetch('https://<MYAPP>.auth0.com/api/v2/users/' + user.sub,{
headers:{
Authorization: 'Bearer ' + accessToken
}
})

How do I get the scope values of a discord oauth2 implicit grant?

I have built a discord bot and now want to build a website for it. I have managed to setup an implicit grant with discord oauth2, however I don't know how to get any of my scope values (identity, email, guilds, bot). All I have is the access token, the token type, the time it will take to expire, the guild id and the scopes, which are listed in the url. Please help!!!!
You need to call the GetCurrentUser Api
It is a GET to https://discord.com/api/users/#me
And you have to pass the Authorization header with your token.
EDIT
In javascript this code should do the work:
fetch('https : //discord.com/api/users/#me', {
method: 'GET',
headers: {
'Authorization': jwtToken,
}
})
.then(res => res.json())
.then(data => {
console.log(data);
});
Or async version:
async getUserInfo() {
const response = await fetch('https://discord.com/api/users/#me', {
method: 'GET',
headers: {
'Authorization': jwtToken,
}
});
var data = await response.json();
console.log(data);
}
getUserInfo();
The values you're looking for should be set as claims in your token.
Try to paste the token into https://jwt.io/

Reactjs fetch headers not working properly

I'm trying to use fetch with react to get a response from an aws api gateway endpoint. I'm using custom authorizer with the endpoint. I can use curl with headers to successfully get data from the endpoint, as well as use the chrome extension postman to get the data successfully, but using the below code with react, I always get a 401 error even with a valid token. I'm somewhat new to react, but I think I have code that should work. What am I doing wrong? Is there something I need to change?
componentDidMount() {
Auth.currentAuthenticatedUser()
.then((res) => {
let token = res.signInUserSession.idToken.jwtToken
///*
let myHeaders = new Headers();
myHeaders.append('authorization', token)
myHeaders.append('type', 'TOKEN')
fetch(<URL>, {headers: myHeaders})
.then((res) => {
console.log(res);
})
.catch((err) => {
console.log(err);
})
})
.catch((err) => {
console.log(err);
})
}
It looks like you need to enable CORS: http://docs.aws.amazon.com/apigateway/latest/developerguide/how-to-cors.html

Returning JSON within the same Fetch POST API call

I currently have a web app built on the Express framework for Node.js.
I'm now building a React Native app that needs to perform user login. To do this, I've created a mongo-helpers.js file that will simply perform the api calls to localhost:3000/api and return JSON. So far, I've had no problem making GET calls and receiving data, however here is my problem and what I want to do:
Objective: When the Login button is pressed (in the React Native app) make an API call to localhost:3000/api/login, passing the username and password into the body of the fetch API POST request. If the user is logged in, send back the user's Mongo Document.
Problem: Though I am able to make the API Post request and successfully log in the user, I am unable to send back the user's Mongo document with res.json(user)
Here is my code:
Express WEB APP: routes/api/api.js
// POST and login user
router.post('/login', (req, res) => {
user.findOne({name: req.body.name, password: req.body.password})
.then((user) => {
console.log(user);
res.json(user)
})
.catch((error) => res.json(error))
});
React Native App: mongo-helpers.js
// Returns a promise
// if login succeeds then return the user
// if login fails return error
exports.login = (name, password) => {
return new Promise(
(resolve, reject) => {
fetch(APP_SERVER_URL+'/login', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({name, password})
}).then((response) => {
console.log('Response', response);
}).then((data) => {
console.log(data); // returns undefined :(
resolve(data);
}).catch((error) => {
console.log('Error', error); // no error is returned
reject(error);
})
}
)
};
I am logging the response and here is what it shows. There's no user data within it
You need to call the json function and it will returns a promise, try that:
fetch(APP_SERVER_URL+'/login', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({name, password})
}).then((response) => {
response.json().then((data) => {
console.log(data)
});
}).catch((error) => {
console.log('Error', error); // no error is returned
reject(error);
})
}
https://developer.mozilla.org/en-US/docs/Web/API/Body/json
Use return response in first then callback.

Categories