https://marmelab.com/react-admin/Authorization.html
Hi, I was follow this AUTH_GET_PERMISSIONS to do the permissions but it come out this error when I want to login:
It returned the message "Invalid Token Specified" error message.
This is the code for making the errors:
is it related with this code?:
const httpClient = (url, options = {}) => {
if (!options.headers) {
options.headers = new Headers({ Accept: 'application/json' });
}
const token = localStorage.getItem('token');
options.headers.set('Authorization', `Bearer ${token}`);
return fetchUtils.fetchJson(url, options);
}
The expected result:
It will login to the page & with the permissions to display the menu items based on the logged in users.
In your response you have access_token: 'token_value' as property name, but then in code you are destructing the function argument with .then(( {token} ))... as property name. So the value is undefined.
Related
I have the following problem when I request data from the Spotify API, at first I get it, but when I reload the page or try to write this state using useState, an error 400 or 401 occurs. The code I use to get the data:
`
import axios from 'axios';
const BASE_URL = 'https://api.spotify.com/v1';
export const fetchFromAPI = async (url: string, token: string) => {
const { data } = await axios.get((`${BASE_URL}/${url}`), {
method: 'GET',
headers: {
Accept: "application/json",
"Content-Type": "application/json",
Authorization: `Bearer ${token}`
},
});
return data;
}
`
Next, I use the fetchFromAPI function:
`
const { token } = useContext(Context);
const [albums, setAlbums] = useState<string[]>([]);
useEffect(() => {
fetchFromAPI('browse/new-releases', token)
.then((data) => console.log(data));
}, [token])
`
I've tried logging out of my account and back in, I've also tried other links to get data but it's always the same problem. I also checked if the token is present before requesting the data and it is
Ok, I managed to find and solve this error myself.
The error was that I didn't have a user token yet, but useEffect was already starting to receive data.
useEffect(() => {
if (token) {
fetchNewReleases();
fetchFeaturedPlaylists();
fetchCategories();
fetchRecommendations();
} else {
console.log('error');
}}, [token])
For example, this piece of code will print an error twice, and only after that I receive a token and can receive data from the API.
To be honest, I didn't know how to run useEffect only when I have a token, so I solved it in a simpler way, but I don't know if it's completely correct, I have the following condition Object.values(state).length) !== 0 and if it is true, only then will I display the data from the API
I'm attempting to get the Salesforce Access Token using typescript and Axios. Unfortunately, I'm getting a Serialized Error. I can't figure out why. Can anyone assist me, please?
import axios from 'axios';
let clientId : string = ‘somestring-1’;
let clientSecret : string = ‘somestring02’;
let body = {
grant_type: "password",
client_id: clientId,
client_secret: clientSecret,
username: ’s’omeusername,
password: ‘somepassword_concatonated_with_secret’
}
let headers = {
"Authorization": `Basic ${Buffer.from(`${clientId}:${clientSecret}`).toString('base64')}`,
"Content-Type": 'application/x-www-form-urlencoded'
}
let data = await axios.post('https://test.salesforce.com/services/oauth2/token', body, {headers});
The results is
AxiosError: Request failed with status code 400
and
Serialized Error: Object {
"code": "ERR_BAD_REQUEST"
What on earth am I doing wrong?
I'm using Postman and can generate a new token with the "Get new access token" button. How to create a function that updates my token current?
This is my current function:
def access_token():
url = "my_url"
token = "my_current_token"
payload = ""
headers = {
'Authorization': f'Bearer {token}',
'Cookie': 'my_cookie'
}
response = requests.request("GET", url, headers=headers, data=payload)
return response.json()
var user = pm.globals.get("clientId");
var pw = pm.environment.get("clientSecret");
var grantTypeAndScope = "grant_type=client_credentials&scope=scopes"
pm.sendRequest({
url: "https://"+pm.environment.get("host")+"/as/token.oauth2",
method: 'POST',
body: grantTypeAndScope,
header: {
'Authorization': "Basic " + Buffer.from(user+':'+pw).toString("base64"),
"Content-Type": "application/x-www-form-urlencoded",
}
}, function (err, res) {
if (err === null) {
console.info(res);
pm.environment.set('auth_token', res.json().access_token)
} else {
console.error(err);
}
});
Then in the auth tab of my api requests I set the auth type to bearer and use the variable {{auth_token}}
I actually have the javascript to refresh my token in my pre-request tab at the collection level, so it grabs a new token with each request. Not optimal, but I never have to worry about an expired token.
I'm trying to authenticate my Sveltekit front-end with JWT using an HTTPonly cookie for security reasons, but it's not working.
Error: "Authentication credentials were not provided."
I can't see the cookie in the storage after login.
My Login code:
<script>
import { goto } from '$app/navigation';
let username = '';
let password = '';
const submit = async () => {
await fetch('https://myAPI/auth/jwt/create', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
credentials: 'include',
body: JSON.stringify({
username,
password
})
});
goto('/auth/me');
};
</script>
I must say that the user registration is working fine.
<script>
import { goto } from '$app/navigation';
let username = '';
let password = '';
let email = '';
let first_name = '';
let last_name = '';
const submitForm = async () => {
await fetch('https://myAPi/auth/users/', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
username,
password,
email,
first_name,
last_name
})
});
goto('/');
};
</script>
I believe I now have enough elements to provide a more accurate answer.
Your API returns a JWT access token upon successful login, but does not set any cookie containing that token. In fact, your API is not reliant on cookies at all since the protected route does not expect a cookie containing the JWT token, but instead an Authorization header containing the token.
This is why I was so insistant on you providing a detailed implementation of your back-end.
In the tutorial you followed and linked in your comment, the author explicitly declares his intent to use cookies to authenticate. This choice is reflected on the front-end (through the use of the credentials: include option in fetch) but also on the back-end, as demonstrated, for example, in the Laravel implementation of his API (line 35), or in its Node implementation (lines 40-43). In both cases, you can see how a 'jwt' cookie is explicitly set and returned by the back-end.
The author also explicitly uses the cookie to read back and verify the token when a request is made to a protected route (see lines 52-54 in the Node example above, for instance).
Your API, however, as I have stated above, does not rely on the same mechanism, but instead expects an 'Authorization' request header to be set.
So you have 2 options here. The simpler option is to adapt your client-side code to function with the Auth mechanism provided by your API. This means storing your token in, for example, sessionStorage, and correctly setting the Authorization header when making requests to protected endpoints:
// login.svelte
<script>
import { goto } from '$app/navigation';
let username = '';
let password = '';
const submit = async () => {
const result = await fetch('https://myAPI/auth/jwt/create', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
username,
password
})
});
const data = await result.json();
const { refresh, access } = data;
sessionStorage.setItem('token', access);
goto('/auth/me');
};
</script>
// auth/me.svelte
<script>
import { onMount } from 'svelte';
onMount(async () => {
// read token from sessionStorage
const token = sessionStorage.getItem('token');
const result = await fetch('https://myAPI/auth/users/me', {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Authorization': `JWT ${token}`
}
});
const data = await result.json();
console.log(data);
});
</script>
The alternative option is to modify the Auth mechanism in your API from an 'Authorization' header based mechanism to a cookie based mechanism, if this is really what you want, but this would impact other existing services relying on your API, if any.
I'm trying to build a program which can control my Sonos Speaker. I'm following the instructions over at https://developer.sonos.com/build/direct-control/authorize/.
The first step - getting the authorization code - is working as intended but the problem I'm facing arises when I try to send the authorization code per POST request with the following code:
const redirect_uri = "https%3A%2F%2Fsonoscontrol-c4af4.web.app%2F";
const redirect_url = "https://sonoscontrol-c4af4.web.app/";
const client_id = // API Key (deleted value for safety)
const secret = // Secret (deleted value for safety)
const auth_url = `https://api.sonos.com/login/v3/oauth?client_id=${client_id}&response_type=code&state=testState&scope=playback-control-all&redirect_uri=${redirect_uri}`;
function GetAccessToken() {
var target_url = "https://api.sonos.com/login/v3/oauth/access/";
var authCode = GetAuthCode();
var encoded_msg = btoa(client_id + ":" + secret); // base64-encodes client_id and secret using semicolon as delimiter
var params = "grant_type=authorization_code" + `&code=${authCode}` + `&redirect_uri=${redirect_uri}` + `&client_id=${client_id}`;
var myHeaders = new Headers({
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'POST',
'Authentication': `Basic {${encoded_msg}}`,
'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
});
fetch(target_url, {
method: "POST",
mode: "no-cors",
credentials: "include",
redirect: "follow",
headers: myHeaders,
body: params
}).then((res) => {
console.log(res.responseText);
}).catch(function(error) {
console.log(error);
});
}
function GetAuthCode() {
return (new URLSearchParams(location.search)).get('code'); // returns authorization code from URL
}
Now I get the following error when trying to send the POST request: POST https://api.sonos.com/login/v3/oauth/access/ net::ERR_ABORTED 403 (Forbidden)
I am using a Cloud Firebase app as webserver and added the correct redirect URL in the credentials.
What could be the problem for this error message?
I noticed a couple of things in your code that may be causing your 403 Forbidden issue.
Your "Authentication" header should be "Authorization", eg: "Authorization: Basic {YourBase64EncodedClientId:SecretGoesHere}"
Your "target_url" has a trailing slash, it should be "https://api.sonos.com/login/v3/oauth/access"
Your query parameters "params" are including the client_id on the token request, which isn't necessary, though I don't believe it will cause an error.
Addressing the above should hopefully resolve your issue!
Thanks,
-Mark