I am creating a Web app using ReactJS and Firebase. I am using Firebase Authentication for login
I have implemented FB Auth using Firebase Auth Successfully. Now what i want to accomplish is to get a larger size profile image rather than the default one. I have tried different techniques but unable to get the desired result.
The Graph API i want to hit
Firebase Auth Function
const signUpWithFb = async ()=>{
console.log("\n Auth Provider Function Start \n");
const provider = new firebase.auth.FacebookAuthProvider();
provider.addScope('email');
await firebase.auth().signInWithPopup(provider).then(async (result)=> {
console.log("\n Auth Provider before Fetch Function \n");
await fetch(`https://graph.facebook.com/v11.0/me?fields=name,picture.width(960)
.height(960),first_name,last_name,email&access_token=${result.credential.accessToken}`)
.then((res)=>{
console.log(res);
console.log("Response Status: "+res.status);
console.log("Response Type: "+res.type);
console.log("Response Status Text: "+res.statusText);
console.log("Response Body: ");
console.log(res.body);
console.log("Response URL: "+res.url);
console.log(res.picture); // give me undefined
console.log("\n Auth Provider Function End After Fetch Function \n");
})
})
}
Response i am getting
The Problem i am facing is that when i try to hit the Graph API using JavaScript Fetch Method Or react-axios. It gives me
`Response Status: 200
Response Type: cors
Response Body:
body: ReadableStream
locked: false
-> On Clicking the url form res.url.
Please Check the attached Images for Referencing
Response
res.url
Thanks
Related
I want to hide some information such as bearer token and API key in header. I have been heard about ssr and using proxy to hide that information, but how? Can someone tell me how to do that? Or is that possible to do in client side?
I tried with some ssr that fetch in react, but it doesn't work for me. I also tried with proxy, but that works for API key that didn't need a dynamically params like user token.
To use server-side rendering (SSR), you will need to install and import the following packages: express, cors, and Axios. The cors middleware allows for Cross-Origin Resource Sharing, while Axios is used to make HTTP requests to external APIs or databases, and handle the response data asynchronously. By setting the headers with Axios, you can pass along sensitive information such as API keys and bearer tokens. After receiving the data back, you can destructure it from the Axios response and then send it back to your users by using the res.json() method.
const cors = require('cors');
const axios = require('axios');
const app = express();
app.use(cors());
app.get('/api/data', async (req, res) => {
try {
const { data } = await axios.get('https://api.example.com/data', {
headers: {
Authorization: `Bearer ${process.env.BEARER_TOKEN}`,
'API-Key': process.env.API_KEY,
},
});
res.json(data);
} catch (error) {
res.status(500).json({ error: error.message });
}
});
app.listen(3000, () => {
console.log('Server started on port 3000');
});
I'm building a webapp using react and flask. I'm currently implementing user login features using react-token-auth and flask_praetorian. I've already created my back-end functions that handle logging in and can successfully return a token. However, I am now having issues with making an authenticated request.
My flask function
#app_login.route('/get_username')
#flask_praetorian.auth_required
def protected():
response = jsonify({'username': flask_praetorian.current_user().username})
return response
and on react
const fetchUsername = () => { authFetch(`http://${configData.LOCAL_SERVER}:${configData.WEBAPP_PORT}/get_username`).then(response => {
return response.json()
}).then(response => {
console.log(response)
})
}
I'm using the default createAuthProvider as shown on the react-token-auth project page
export const { useAuth, authFetch, login, logout } = createAuthProvider({
getAccessToken: session => session.accessToken,
storage: localStorage,
onUpdateToken: token =>
fetch(`http://${configData.LOCAL_SERVER}:${configData.WEBAPP_PORT}/app_login/refresh`, {
method: 'POST',
body: token.refreshToken,
}).then(r => r.json()),
});
Whenever I make a request, I get a 401 (UNAUTHORIZED) and react returns the error 'authFetch' was called without access token. Probably storage has no session or session were expired
I've checked my local storage and I can see that the key is there:
Storage {persist:root: '{"player":"{\\"value\\":{\\"name\\":\\"\\",\\"access_toke…_persist":"{\\"version\\":-1,\\"rehydrated\\":true}"}', REACT_TOKEN_AUTH_KEY: '"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE2…5OX0.rTBCD7YPD8wrB95v1j9oazNLusKOPErI5jed_XWXDhU"', length: 2}
I'm really trying to avoid using technologies like Redux so any assistance regarding this specific setup would be great.
I'm creating a node web app that needs to integrate with some azure services using Azure REST API. I'm using the node MSAL library for user login and retrieving an access token for making requests to the Azure REST api. I'm able to login a user successfully and retrieve an access token. However, when I try to make a request to Azure's REST api I am receiving a 401 error that says error="invalid_token", error_description="The access token is from wrong audience or resource."
The web app itself is built with Node LTS and React v16.8.6. It has been deployed in Azure and registered with active directory.
I'm using MSAL v1.0.1 to login a user and retrieve a token when the user lands on the login page.
login.js
import React, { Component } from 'react';
import * as Msal from 'msal';
let msalConfig = {
auth: {
clientId: process.env.REACT_APP_CLIENT_ID,
authority: `https://login.microsoftonline.com/process.env.REACT_APP_TENANT_ID'`,
navigateToLoginRequestUrl: false,
redirect_uri: 'http://localhost:3000/newEntry',
resource: 'https://management.azure.com/'
},
cache: {
cacheLocation: "localStorage",
storeAuthStateInCookie: true
}
};
var msalInstance = new Msal.UserAgentApplication(msalConfig);
var tokenRequest = {
scopes: ['https://management.azure.com/']
}
class Login extends Component {
constructor(props) {
super(props);
this.state = {
response: null,
};
}
componentWillMount() {
// prevent login loop by checking for logged in user and then acquire a token if logged in
if (!msalInstance.getAccount() && !msalInstance.isCallback(window.location.hash)) {
this.login();
} else {
msalInstance.acquireTokenSilent(tokenRequest)
.then(res => localStorage.setItem('access_token', res.accessToken))
.catch(err => console.error(err))
}
}
login = () => {
msalInstance.handleRedirectCallback((error, response) => {
if (error) console.error(error);
console.log(response);
})
msalInstance.loginRedirect(tokenRequest);
}
render() {
return (
<div>
<h2>Login</h2>
</div>
)
}
}
export default Login;
I am successfully returning an access token and putting it in local storage.
On a separate page I am retrieving the MSAL access token from local storage and using it to make a request to retrieve all resources associated with my Azure subscription.
componentWillMount() {
let token = localStorage.getItem('access_token');
let url = 'https://management.azure.com/subscriptions/process.env.REACT_APP_SUBSCRIPTION_ID/resource?api-version=2018-02-14'
fetch(url, {
method: 'GET',
headers: {
'Authorization': `Bearer ${token}`
}
})
.then(response => console.log(response))
.catch(err => console.error(err));
}
I suspect I'm getting the error because there is some discrepancy between the resource value sent with the login request and the scope value sent with the token request.
I've attempted changing the resource value to 'resource': 'https://management.core.windows.net/' per Azure: The access token has been obtained from wrong audience or resource but that didn't change anything.
I've also attempted various scopes including https://management.azure.com/user_impersonation and https://management.azure.com//user_impersonation following this example Access Token do not include access for API with MSAL
The get method is default, and the problem might be in 'Authorization': `Bearer ${token}`.
Sometimes people use different rules, like 'Authorization': token, or 'Token': `Bearer ${token}`.
I see some API using 'S-token': token. try that. I thinkit is because the token did get there.
You are using msal, so resource parameter is not needed in your msalConfig. You can remove it.
Change the scopes to scopes: ['https://management.azure.com/.default'].
So I ended up switching to the ADAL library to see if I would get the same error and I did. I did however realize the resource request URL wasn't correct. The api-version wasn't an accepted version. Once I switched it to 2018-02-01 the request returned 200.
makePlaylist = event => {
event.preventDefault()
let token = localStorage.getItem('token')
let playlist = {name: this.state.text, public:false}
axios.post(
`https://api.spotify.com/v1/users/${this.state.user_id}/playlists`, playlist,
{headers: {
"Authorization": 'Bearer ' + token
}
}
)
.then(response => {
console.log(response)
})
.catch(error => {
console.log(error)
})
}
and I get the following error
https://api.spotify.com/v1/users/my_user_id_here/playlists 403 error
I looked up the documentation online at
https://developer.spotify.com/documentation/web-api/reference/playlists/create-playlist/
and it looks like I'm setting things up as far as I can tell. Anyone know what I'm doing wrong with the request? I know the access token is valid.
"Trying to create a playlist when you do not have the user’s authorization returns error 403 Forbidden." Make sure that the Spotify app that you made in Dashboard has the proper scope permissions on the user you are trying to create the playlist for. Here is the scope for creating a private playlist: https://developer.spotify.com/documentation/general/guides/scopes/#playlist-modify-private
Here is the tutorial for setting up authorization with passing in a scope:
https://developer.spotify.com/documentation/general/guides/authorization-guide/
I want to make an HTTP request to the Cloudinary API for pictures in my account. The url necessary looks like this:
https://<<API KEY>>:<<API SECRET>>#api.cloudinary.com/v1_1/<<RESOURCE NAME>>/resources/image
and when I hit this url from the browser, I get what I'm looking for, a beautiful JSON object with all my pictures.
But when I hit the url from within a React component,
componentDidMount() {
this.props.fetchArt();
}
I get the following error:
TypeError: Failed to execute 'fetch' on 'Window': Request
cannot be constructed from a URL that includes credentials:
The action creator looks like
export function fetchArt() {
const url = 'https://'+CLOUDINARY_KEY+':'+CLOUDINARY_SECRET+'#api.cloudinary.com/v1_1/prints20/resources/image';
const request = fetch(url).then(res => res.json())
return {
type: FETCH_ART,
payload: request
}
}
Link to the repo: https://github.com/PantherHawk/prints20-2018
Thanks a million in advance!
If your endpoint requires some sort of authorization you'll need to pass that info inside the headers of your request.
Cloudinary Authentication is done using Basic Authentication over secure HTTP. Your Cloudinary API Key and API Secret are used for the authentication.
fetch('https://api.cloudinary.com/v1_1/CLOUD_NAME/resources/image', {
method: 'get',
headers: {
'Authorization': 'Basic ' + base64.encode(API_KEY + ":" + API_SECRET),
},
}).then(res => res.json())