Request failed with status code 401 at createError "Unauthenticated" - reactjs

I'm using laravel with reactjs I'm getting this problem when I'm doing logout
axios.defaults.withCredentials = true;
// axios.defaults.headers.common = {'Authorization': 'bearer ' + localStorage.getItem('auth_token')}
axios.interceptors.request.use(function (config){
const token = localStorage.getItem('auth_token');
// config.headers["Authorization"] = "bearer " + token;
config.headers.Authorization = token ? `Bearer ${token}` : '';
return config;
});

So what does that logout api do this is clearly a permission error coming from laravel. Show the logout method from the backend. Also check your network you can see the full message there.

Related

REACT + Typescript, making API with Axios. headers makes type error

I'm so Newbie in Programming.
I'm using Django as backend, React+Typescript as frontend.
I'm using Axios to make JWT login function. but stuck in the middle.
Because headers/Authorization makes type error.
as above Authorization does not work.
showing this error.
Can anyone help me out of this situation?
Try to remove the null in your condition. Replace it with either undefined or a empty string ""
Authorization: localStorage.getItem("access_token") ? "JWT" + localStorage.getItem("access_token") : ""
const axiosbase = axios.create({
baseURL: 'Your Base URL',
timeout: 5000,
transformRequest: [(data, headers) => {
return data;
}]
});
//default headers
var token = 'Your JWT';
axiosbase.defaults.headers["Authorization"] = 'Bearer ' + token;
axiosbase.defaults.headers["Accept"] = 'application/json, text/plain, */*';
axiosbase.defaults.headers["Content-Type"] = 'application/json';
// Add a request interceptor
axiosbase.interceptors.request.use((config) => {
return config;
}, (error) => {
// Do something with request error
console.log('Error occured while request');
return Promise.reject(error);
});
// Add a response interceptor
axiosbase.interceptors.response.use(
(response) => {
// Do something with response data
//console.log('Response was received');
return response;
},
);
export default axiosbase;

PostMan vs Axios on Including authorization Header while Making requests

Making a postman request to an endpoint with some Header
when I run the below code
function authenticateToken(req,res,next){
const bearerHeader = req.headers["authorization"]
console.log(req.headers)
if(typeof bearerHeader !== 'undefined'){
const bearer = bearerHeader.split(' ');
const bearerToken = bearer[1];
req.token = bearerToken;
next();
}
else{
console.log('hihihi')
res.sendStatus(403);
}
}//a middleware function used for JWT
it's returning everything as I expected like below
but the problem is, I need to connect it with my react. So I am making Axios request but it's not working
I tried giving headers using interceptors like below
axios.interceptors.request.use(
config=>{
config.headers.authorization = `Bearer ${token}`
return config
},
error =>{
return Promise.reject(error)
return error
}
)
axios.post("http://localhost:3000/stockdata/post",{
// some data
})
I also tried giving like below
axios.post(url,{data},{headers:{
'authorization': "Bearer "+ token,
'Accept': 'application/json',
'Content-Type': 'application/json'
})
i also tried with 'Authorization': "Bearer "+ token and without quotes Authorization: "Bearer "+token and also tried one time by removing Accept and content-type . but this is what am getting
The problem is only with the Axios request, not any other thing. what's going wrong in it?
I think when you tried with axios, there will be two requests as it has CORS issue. This issue comes if the client host is different from server host.
The first request is type OPTIONS to know whether to allow the POST or not and second request is actual POST.
What you are seeing might be of request type OPTIONS. This you can verify by checking network tab in the browser. This won't happen in POSTMAN. You could add CORS plugin to your server to resolve this issue.
The attached screenshot shows POSTMAN sending request to http://localhost:3000/stockdata/post
However, the axios request is being sent to http://localhost:3000/stockdata
Adjusting the request end-point may help resolve the issue.
After adjusting the target URL, the following code example may be tried to get the axios response:
import axios from 'axios'
let url = "http://localhost:3000/stockdata/post"
let data = {}
let token = "xyz"
let config = {"headers": {
"Authorization": "Bearer " + token,
"content-type": "application/json"
}
}
axios.post(url, data, config)
.then((response) => {
console.log(response)
}, (error) => {
console.log(error)
}
)
More information:
https://blog.logrocket.com/how-to-make-http-requests-like-a-pro-with-axios/

Connecting to bank account with OAuth2.0 and Google App Scripts

My bank offers to connect to their APIs using OAuth2. I want to create an App Script to autmatically write my transactions to google docs. This is my first time using OAuth and I can't seem to get the access token. Below I have pasted my attempt at receiving an access token, but the site refuses my request. Below my code example are two code examples (one for Node and one for Python) which are provided by the bank. Are there any obvious mistakes that I don't see?
My code:
function get_auth_token() {
var identityServerUrl = "https://auth.sbanken.no/identityserver/connect/token"; // access token endpoint
var clientId = '...'
var secret = '...'
var basicAuth = Utilities.base64Encode(encodeURIComponent(clientId) + ":" + encodeURIComponent(secret)); // create basicAuth header value according to Oauth 2.0 standard
var response = UrlFetchApp.fetch(identityServerUrl, {
headers: {
'Accept': 'application/json',
'customerId' : clientId,
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': 'Basic ' + basicAuth}
});
}
Node code from the bank:
exports.getAccessToken = () => {
var identityServerUrl = "https://auth.sbanken.no/identityserver/connect/token"; // access token
endpoint
var clientId = credentials.clientid; // application key received from API Beta in the internetbank
var secret = credentials.secret; // password received from API Beta in the internetbank
var basicAuth = btoa(encodeURIComponent(clientId) + ":" + encodeURIComponent(secret)); // create basicAuth header value according to Oauth 2.0 standard
var accessToken;
// request accessToken (the basic auth data is put on the request header prior to sending the request)
let response;
var promise = new Promise(function (resolve, reject) {
request
.post(identityServerUrl)
.send('grant_type=client_credentials')
.set('Authorization', "Basic "+basicAuth)
.set('Accept', 'application/json')
.set('customerId', credentials.userid)
.end(function(err, res){
if (err || !res.ok) {
console.log(err);
reject();
} else {
console.log('yay got ' + JSON.stringify(res.body));
resolve(res.body);
}
});
});
Python code from the bank:
CLIENT_ID = '' # Get from https://secure.sbanken.no/Personal/ApiBeta/Info/
SECRET = '' # Get this from https://secure.sbanken.no/Personal/ApiBeta/Info/
AUTH_URL = 'https://auth.sbanken.no/identityserver/connect/token'
ACCOUNTS_URL = 'https://api.sbanken.no/exec.bank/api/v1/accounts'
CUSTOMER_ID = '' # Your own personnummer
def get_auth_token(auth_url, client_id, secret):
headers = {
'Accept': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded',
}
body = {'grant_type': 'client_credentials'}
urlencoded_client_id = urllib.quote(client_id)
urlencoded_secret = urllib.quote(secret)
auth_string_to_be_b64encoded = '{}:{}'.format(
urlencoded_client_id, urlencoded_secret)
b64encoded_auth_string = base64.b64encode(auth_string_to_be_b64encoded)
headers['Authorization'] = 'Basic {}'.format(b64encoded_auth_string)
r = requests.post(url=auth_url, headers=headers, data=body)
auth_token = r.json()['access_token']
return auth_token
From the code samples, I'd bet that you need to pass grant_type=client_credentials as part of the request. There are two ways you can do this:
Add it to the URL https://auth.sbanken.no/identityserver/connect/token?grant_type=client_credentials
Include it as the payload of the UrlFetchApp.fetch() request (this would be the more "correct" approach):
var response = UrlFetchApp.fetch(identityServerUrl, {
headers: {
'Accept': 'application/json',
'customerId' : clientId,
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': 'Basic ' + basicAuth
},
payload: 'grant_type=client_credential'
});
Unfortunately, I can't verify if that's all you'll need to do to make it work, but it should get you going in the right direction. Also, I'd really recommend you try to configure this through Google's OAuth2 library, although it isn't the most straight-forward to implement.
The answer can be found in Diego's post, but I also made some other changes to the code:
var headers = {
'Authorization': 'Basic ' + basicAuth,
'Content-Type': 'application/x-www-form-urlencoded',
'Accept': 'application/json'
};
var options = {
"method" : "get",
"headers" : headers,
"payload" : {'grant_type': 'client_credentials'},
};
var response = UrlFetchApp.fetch(identityServerUrl, options);

How to pass bearer token in $window.open url

I am opening the url without authentication using below code,
$window.open(downloadUrl);
I want to use below authorization
Authorization': 'Bearer ' + '123hrwertjwtjwjrtr',
i have used below code but it is not working,
var params =
{
'Authorization': 'Bearer ' + '123hrwertjwtjwjrtr',
'Content-type': 'application/x-www-form-urlencoded',
};
var downloadUrl = somedummyurl;
var url = [downloadUrl, $.param(params)].join('?');
$window.open(url);
Can anyone suggest how to add bearer token while calling the api url.
In api am using httpget method and used authorize tag..

Keycloak token not active with angularjs

I have spring boot backend app with Angular js app. The login process and initial backend communication are successful. After some idle time, the front end will show 403 forbidden with token not active on the backend console.
The code below contains refresh token, But it seems not working.
// use bearer token when calling backend
themesApp.config(['$httpProvider', function($httpProvider) {
var isExpired = keycloak.isTokenExpired();
var token = keycloak.token;
if (isExpired) {
keycloak.updateToken(5)
.success(function() {
$httpProvider.defaults.headers.common['Authorization'] = 'BEARER ' + token;
})
.error(function() {
console.error('Failed to refresh token');
});
}
$httpProvider.defaults.headers.common['Authorization'] = 'BEARER ' + token;
}]);
Error on the backend
2017-05-29 10:08:23.715 ERROR 5072 --- [nio-8080-exec-3] o.k.a.BearerTokenRequestAuthenticator : Failed to verify token
org.keycloak.common.VerificationException: Token is not active
Something must be wrong on the Keycloak Server, Token not active means token being is expired or is used before it gets valid. Could it be that the time/date is wrong on your KC server ?
you can config the 'Session Idle Time' here:
I had the same issue and handle it with an automatical logout. So the user has to login again.
In your code:
var token = keycloak.token;
you define the value of token once. After the update you have to set it again:
// use bearer token when calling backend
themesApp.config(['$httpProvider', function($httpProvider) {
var isExpired = keycloak.isTokenExpired();
var token = keycloak.token;
if (isExpired) {
keycloak.updateToken(5)
.success(function() {
// UPDATE THE TOKEN
token = keycloak.token;
$httpProvider.defaults.headers.common['Authorization'] = 'BEARER ' + token;
})
.error(function() {
console.error('Failed to refresh token');
});
}
$httpProvider.defaults.headers.common['Authorization'] = 'BEARER ' + token;
}]);

Resources