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..
Related
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);
I created a Django RESTful API with JWT as authentication method, but unable to pass the token as headers using angularJS.
I think there is no error on my API, since I used the token I acquired by this script and tested it in Postman:
my JWT token authentication script is here:
// Uses http.get() to load data from a single API endpoint
list() {
return this.http.get('api/', this.getHttpOptions());
}
// helper function to build the HTTP headers
getHttpOptions() {
return {
headers: new HttpHeaders({
'Content-Type': 'application/json',
'Authorization': 'JWT ' + this._userService.token
})
};
}
I tried using http.get() here. Thanks in advance!
the error will be like:
401 (Unauthorized)
Try this:
list() {
return this.http.get('api/', { this.getHttpOptions() });
}
getHttpOptions() {
const headers = new HttpHeaders({
'Content-Type': 'application/json',
'Authorization': 'JWT ' + this._userService.token
});
return headers;
}
Same issue on JWT for CakePHP3, and follow header slove it, may it is helpful.
this.http.get('api/', { headers: new HttpHeaders({
'Content-Type': 'application/json',
'Authorization': 'JWT ' + this._userService.token,
'Authenticationtoken': 'JWT ' + this._userService.token
}) });
Thanks guys,
I found the problem is about CORS, My solutions are here, there are two approaches to solve this problem, one is add 'Access-Control-Allow-Origin': '*' to your http request, sometimes you need add more. Another answer is add CORS_ORIGIN_WHITELIST = 'localhost:4200', in your backend.
https://www.youtube.com/watch?v=OIbndrrUYiY
I am not able to add bearer token in $resource service header for token based authentication. I used following code
Factory
return $resource(appSettings.serverPath + "/api/product/:id", null, {
'get': {
method: 'GET',
headers: {
'Authorization': 'Bearer ' + currentUser.getProfile().token
}
}
Also i tried below code as per some research in app.run
$http.defaults.headers.common.Authorization = 'Bearer ' + currentUser.getProfile().token;
But both options do not add this header in my request and i can see request in chrome without this headers and hence got unauthorized response. I am using angular 1.5.9. Any clue on this.
Assuming currentUser is a service and currentUser.getProfile() is a synchronous API:
app.factory("myRestAPI", function(currentUser) {
return $resource(appSettings.serverPath + "/api/product/:id", null, {
'get': {
method: 'GET',
headers: {
//REPLACE expression
//'Authorization': 'Bearer ' + currentUser.getProfile().token
//WITH a function
'Authorization':
function() {
return 'Bearer ' + currentUser.getProfile().token;
}
}
}
);
});
By using a function instead of an expression, the Authorization header will be computed on every call.
From the Docs:1
headers – {Object} – Map of strings or functions which return strings representing HTTP headers to send to the server. If the return value of a function is null, the header will not be sent. Functions accept a config object as an argument.
I'm facing a problem, I tried to connect to Auth0 API to enable a strong identification on my WebApp.
For context :
Front-End : I'm using an angularJS front, and there I implemented the Lock Library to manage the Auth0 popup by following this webapp-specific tutorial.
Back-End : NodeJS & Express server, in order to verify the user's authentification, I use the npm lib "request" to call the Auth0 API.
If i understand well, a click on the auth0 widget sends a request to the specified endpoint URL, and it's received by the back-end:
app.get('/auth0CallbackURL', function (req, res) {
console.log(req.query.code);
var auth0code = req.query.code;
var client_secret = PROCESS.ENV.SERCRETID;
var domain = PROCESS.ENV.DOMAIN;
var client_id = PROCESS.ENV.CLIENTID;
var redirectUrl = PROCESS.ENV.REDIRECTURL;
var request = require('request'); // request-promise
var requestParams = {
url: 'https://mycompanydomain.auth0.com/oauth/token?client_id='+client_id+'&redirect_uri='+redirectUrl+'&client_secret='+client_secret+'&code='+auth0code+'&grant_type=authorization_code',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}
And then I call request() to get back the access_token and verify the authentification.
request(requestParams, function(err, data) {
if (err) {
console.log('Err:', err);
} else {
console.log('response body: ', data.body)
}
But the only result I get is :
{
"error": "access_denied"
"error_description": "Unauthorized"
}
At the begining i thougt it was my Auth0 configuration that's didn't allow my authentification, but it seems that there are OK.
Thanks in advance for your replies.
As per the page you linked, you need to pass the following information:
client_id=YOUR_CLIENT_ID
&redirect_uri=https://YOUR_APP/callback
&client_secret=YOUR_CLIENT_SECRET
&code=AUTHORIZATION_CODE
&grant_type=authorization_code
in the request body and with a content type of application/x-www-form-urlencoded.
You're setting the content type correctly, but then are passing the data in the URL query component and instead you need to pass it the POST request body.
Using request package you should do the following:
var requestParams = {
url: 'https://mycompanydomain.auth0.com/oauth/token',
method: 'POST',
body: 'client_id=' + client_id +
'&redirect_uri=' + redirectUrl +
'&client_secret=' + client_secret +
'&code=' + auth0code +
'&grant_type=authorization_code',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}
I am developing a app in Ionic framework.The api calls data from secured server.When i check the api in browser i am getting this popup.
So i could not use this api in mobile app.i found some solution for this issue nothing worked Here is the code i have tried
var string = username + ":" + password;
// Encode the String
var encodedString = btoa(string);
$http({method: 'GET', url: 'https://creatorup.com/wp-json/users/me',
headers: { 'Authorization': 'Basic ' + encodedString }
})
When i use this code i got the response "401 (unauthorized)" error.