How can I get the JWT token after authenticating? - reactjs

I have a Rest spring-boot API that when a user authenticates the api returns the token jwt, I noticed in the browser that the token appears in the Response Header> Authentication and in the tests with the Postman it shows in the Body.
How can I get this token to store in the Local Storage browser by Reactjs?
My code that makes the requests looks like this:
import { ACCESS_TOKEN, API_BASE_URL } from '../constants';
export function request (options) {
const headers = {
'Content-Type': 'application/json',
}
if (localStorage.getItem(ACCESS_TOKEN)) {
headers.append('Authorzation', 'Bearer ' + localStorage.getItem(ACCESS_TOKEN))
}
return fetch(API_BASE_URL+options.url, {
method: options.method,
headers: headers,
body: options.body
})
.then(function(response){
// Falta pegar o token e gravar na local estorage
if (!response.ok) {
return Promise.reject(json);
}
return json;
});
};

// Save data to the current local store
localStorage.setItem("username", "John");
// Access some stored data
alert( "username = " + localStorage.getItem("username"));
The first argument of setitem is the key
My account got blocked by some down votes questions, the funny thing is I have to re-edit them, even though I already have the accepted answer.I do not understand what's the point to do this.I am so frustrated by this stackoverflow system.
Now, I basically can do nothing but keep editing my questions, and they have all been answered. This is ridiculous !!!

Related

How can I associate an Alexa skill with a catalog?

I am trying to associate my Alexa skill with a catalog that I created by hitting the https://api.amazon.com/v0/catalogs endpoint with an Auth token that I had generated through a LWA profile.
This worked, and I created a catalog like so:
{
associatedSkillIds: [],
createdDate: '2022-01-22T20:50:37.318Z',
id: 'amzn1.ask-catalog.cat.[REDACTED]',
lastUpdatedDate: '2022-01-22T20:50:37.318Z',
title: 'TestCatalog',
type: 'AMAZON.AudioRecording',
usage: 'AlexaTest.Catalog.AudioRecording'
}
However, the next step, associating my Alexa skill with the Catalog is always returning 401 https://developer.amazon.com/en-US/docs/alexa/smapi/catalog-content-upload.html#associate-catalog-with-skill
This is my function to attempt to associate the skill with the catalog:
async associateSkillWithCatalog() {
console.log(`Associating skill...`);
const accessToken = await this.getRefreshToken(); // makes post to https://api.amazon.com/auth/o2/token
console.log(this.alexaEndpoint + this.skillAssoc(cat.id, skillId));
const response = await axios.put(
"https://api.amazonalexa.com/v0/skills/amzn1.ask.skill.[REDACTED]/catalogs/amzn1.ask-catalog.cat.[REDACTED]",
{
headers: {
'Content-type': 'application/json',
'Authorization': `Bearer ${accessToken}`
}
}
);
return response.data;
}
Always receiving back this Error: Request failed with status code 401\n at createError.
Why would I be receiving 401 Error here, despite other requests against this API not failing?
Thanks!

Authorize request to API by React

I want to use Santum with Laravel and I have a problem with Authorize. Sanctum works becouse I can take response if I send request via Postman. But I don;t understand how authorization works in React. Look at my code.
Here I generated token and save that in a cookie (I have httponly)
public function getToken(){
$user = User::first();
$token = $user->createToken('Authrization', ['server:update'])->plainTextToken;
Cookie::queue("Authorization", $token);
return $token;
}
In React I wanted use this token automatically (I read that this is possibe by withCreditional). Co I read this code
axios.get('http://localhost:8000/token')
.then(response => {
console.log(response.data.token);
});
const json = axios.get('http://localhost:8000/api/taks/all-tasks', { method: 'GET', withCredentials: true }).then(res => {
j = this.res.data;
return j;
})
console.log('Json' + json)
But I have an error (401). How can I authorize access to all-tasks route and route with the simples way?

Token based authentication using Authentication header giving 403 forbidden error

I have the following code in my react app:
I am sending an update request to rest backed which requires a user to be authenticated to perform PUT/POST/DELETE requests.
const update = (e) => {
e.preventDefault()
const formData = new FormData(form.current);
console.log('Token ' + localStorage.getItem("token")) // valid token
const requestOptions = {
method: 'PUT',
headers : {
// 'Authorization': 'Basic ' + btoa('user:password') // basic authentication works
"Authorization": 'Token ' + localStorage.getItem("token"),
},
body: formData
};
fetch(url, requestOptions)
.then(async response => {
const data = await response.json();
if(!response.ok){
const error = (data && data.message ) || response.status;
return Promise.reject(error)
}
alert('member updated')
history.push("/members")
})
.catch(error => console.error('Some error ', error))
}
Unfortunately, I'm getting these in console logs:
PUT http://localhost:8000/uskindia/56/ 403 (Forbidden)
Some error 403
And this in backed logs:
Forbidden: /uskindia/56/
[... *:*:*] "PUT /uskindia/56/ HTTP/1.1" 403 58
Trying to solve this for the last 24 hours but not getting it right.
From various tries, it seems like:
backend DRF and django-rest-auth is not handling token properly
tried various user agents like curl, httpie and postman to view request and response closely
Even in backed put logs, but request.user == AnonymousUser with token based authorisation.
works well with basic authorizatin, scheme.
if you are using djangorestframework for backend you must send token with this format :
"Authorization": 'Bearer ' + localStorage.getItem("token"),
use Bearer instead of token.
There was a typo in settings.py
# Earlier
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASS': [
'rest_framework.authentication.TokenAuthentication',
],
# ....
}
# Changed to
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework.authentication.TokenAuthentication',
],
# ...
}
Thanks to Blog by Vitor Freitas
which made it clear that, if response contains
WWW-Authenticaate:Token then it means Token authentication was working.
As this was missing in my case, so I started all over setting REST_FRAMEWORK settings from scratch and found the root cause of issue.

Get userinfo from ADFS 2016, react, ADAL.js

I've been stuck on this issue for a while now, I'm using ADAL.js on the front-end to handle login and authentication. Once logged in I need to get the info for the user (roles, groups, name etc...) however I can't get anything back from the /adfs/userinfo endpoint other than a 401.
So far I log the user in and get back an id_token and access token (or "adal.access.token.key{guid}" in the browser) which is identical to the access key. Due to a cors issue on the front-end I then send this to a back-end mvc core 2.2 controller to make the call to /adfs/userinfo which is where I get the 401. Javascript code below
this.adalAuthentication.Instance.acquireToken(this.adalAuthentication.Instance.config.clientId, (error, token) => {
if (error || !token) {
console.log('ADAL Error Occurred: ' + error);
return;
}
axios({
method: 'get',
url: '/identity/completeLogin/' + token,
headers: {
'Authorization': 'Bearer ' + token
}
}).then((response) => { console.log(response.data) });
});
And controller action...
[HttpGet("completeLogin/{access_token}")]
public async Task<HttpResponseMessage> CompleteLogin(string access_token)
{
var client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("OAuth" + access_token);
var response = await client.GetAsync("https://adfs.server/adfs/userinfo");
response.EnsureSuccessStatusCode();
try
{
response.Content.Headers.ContentType = new MediaTypeHeaderValue("text/html");
return response;
}
catch (Exception e)
{
throw(e);
}
}
At this point I'm stumped, I'm thinking I either can't use ADAL for this or perhaps need to use oidcinstead of OAuth/jwt but I don't want to have to rewrite lots just to find out that doesn't work either or there's a better/best practice way of doing it. Has anyone had this issue before and/or can point me in the right direction or can see where I'm going wrong?
Other things I've tried;
hitting adfs/oauth/token endpoint (just returns with adfs server error)
setting Authorisation on the backend to client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer" + access_token); (just returns invalid token).
Making the front and backend a post method and using the getCachedToken method on the ADAL AuthenticationContext
EDIT: I also have this question open with a the slightly more specific goal of getting an access token with the id token
There's a Postman sample here.
Be aware that "userinfo" only returns a "sub" claim.

Spotify API Post Request Add Tracks To Playlist - ERROR 400 BAD REQUEST

Im having what seems to be a very common error when working on the Spotify API adding tracks to a users playlist. In a previous fetch method I have obtained the users playlistId and am now trying to post tracks onto that playlist with that playlistId. I have followed the documentation but am obviously missing something, here is code:
` //userUd, playlistId, currentUserAccessToken, trackURIs are all defined
fetch(`https://api.spotify.com/v1/users/${userId}/playlists/${playlistId}/tracks`, {
headers: {
'Authorization': 'Bearer ' + currentUserAccessToken
},
contentType: 'application/json',
method: 'POST',
body: JSON.stringify({
"uris": `[${trackURIs}]`
})
}).then(success => {
return success;
}).catch(err => {
console.log('here is your error', err);
})`
I did the GET request to authorize user - included scope for creating public playlist, in different code block which is working, here's that:
`let scopes = 'playlist-modify-public';
window.location.replace(https://accounts.spotify.com/authorize?client_id=${clientID}&scope=${scopes}&redirect_uri=${redirectURI}&response_type=token);`
Thanks a ton!
The JSON array needs quotes around each element in it. So each track should be quoted, like so:
{"uris": ["spotify:track:4iV5W9uYEdYUVa79Axb7Rh", "spotify:track:1301WleyT98MSxVHPZCA6M"]}
I think you're supplying an object names uris with an invalid array.
And, note you can pass the playlist items as query params too (instead of in the body), without using json. https://developer.spotify.com/web-api/add-tracks-to-playlist/

Resources