how to set basic authorization header for GET service in sapui5? - sapui5

Can I get a sample code to set basic authorization as header along with other headers ( like x-csrf-token : fetch) in eclipse ?

You can do something like this with jQuery (which is of course included with UI5) for basic authentication:
function ajaxBeforeSend(xhr) {
xhr.setRequestHeader("Authorization", "Basic " + btoa(user + ":" + password));
}
$.ajax({
type: "GET",
url: url,
dataType: "json",
beforeSend: function(xhr) {
ajaxBeforeSend(xhr);
}
}).done(function(data) { /* do something */ }
This is what I've used in some developments and it works well. You can set other headers this way as well.
See http://www.w3schools.com/jsref/met_win_btoa.asp for details on btoa() which base64 encodes the user:pass string.
Your question says: "in eclipse". I don't know what that means as the javascript will work regardless of what editor you use.
Here's the jQuery doco which describes the method used above: http://api.jquery.com/jQuery.ajax/.
(Watch out for CORS issues if service is not on the same host as your app. For CORS I find you also need to add xhr.withCredentials = true; inside the above ajaxBeforeSend() function.)

Related

Access TFS RESTful API from Angular web app

I think TFS RESTful api has a bug. I am trying to access it using an Angular web app. Our TFS server is corporate internal. Here is my code:
var path = 'http://tfs.mycompany.com/tfs/mycompany/_apis/wit/queries?$depth=1&$expand=all&api-version=2.2';
var config = { withCredentials: true };
$http.get(path, config)
.then(function (response) {
$scope.resultList = response.data.d.results || [ response.data.d ];
$scope.message = 'Found ' + $scope.resultList.length + ' item' + ($scope.resultList.length == 1 ? '':'s');
}, function (response) {
$scope.resultList = [];
$scope.message = 'Error ' + response.status + ' ' + JSON.stringify(response.data);
});
The request goes to the server, and the server responds with OK 200. However, the browser (Chrome) blocks the data, and tells me:
A wildcard '*' cannot be used in the 'Access-Control-Allow-Origin' header
when the credentials flag is true. Origin 'http://localhost' is therefore
not allowed access. The credentials mode of an XMLHttpRequest is controlled
by the withCredentials attribute.
The request headers have Origin:http://localhost
The response headers have Access-Control-Allow-Origin:*
Is there any way for me to tell TFS to not return * in the Access-Control-Allow-Origin? This seems like a serious bug in TFS, which renders the RESTful api practically useless for web apps!
You may check Cross-origin resource sharing (CORS) example below to add Authorization in your code:
$( document ).ready(function() {
$.ajax({
url: 'https://fabrikam.visualstudio.com/defaultcollection/_apis/projects?api-version=1.0',
dataType: 'json',
headers: {
'Authorization': 'Basic ' + btoa("" + ":" + myPatToken)
}
}).done(function( results ) {
console.log( results.value[0].id + " " + results.value[0].name );
});
});
Also, check this case to see whether it is helpful:
AJAX cross domain issue with Visual Studio Online REST API

Jhipster + REST client + authentication

I need to understand how to authenticate a REST client (could be Paw, could be an android app, an iOs app using AFNetworking with jHipster and I think, more in general, with spring-boot of which I am no expert).
While I am able to obtain a token when logged in a browser, and subsequently use this token in the following requests, I do not understand how I can authenticate in the first place using RESTful best practices.
For example, in Paw.app, I can pass a Basic authentication, or Oauth2, but I don't understand how to get the session token simply authenticating as I do on a web browser.
Similarly, in AFNetworking I am able to pass basic authentication, e.g.
NSString*auth=[NSString stringWithFormat:#"%#:%#", #"admin", #"admin"];
NSString *authValue = [NSString stringWithFormat:#"Basic %#", [auth base64EncodedString]];
[manager.requestSerializer setValue:authValue forHTTPHeaderField:#"Authorization"];
But I struggle to understand how to authenticate with the session security which is bundled in jHipster/spring boot.
First of all, do not use HTTP session authentication for mobile apps.
On the other hand, Oauth2 or JWT works fine with mobile apps. The basic idea behind them is to get a token from Jhipster to mobile the token has an expiry time. In that time you can use the token to access any REST API of Jhipster to access data.
Below I am showing the code snippet of how I was using the Jhipster rest API in my angularjs based ionic app. I hope it gives the idea of what you need to do.
uncomment cors in application.yml inside jhipster
cors: #By default CORS are not enabled. Uncomment to enable.
allowed-origins: "*"
allowed-methods: GET, PUT, POST, DELETE, OPTIONS
allowed-headers: "*"
exposed-headers:
allow-credentials: true
max-age: 1800
To access REST API with Oauth2 authentication in ionic you must first get the token in the ionic app by
$http({
method: "post",
url: "http://192.168.0.4:8085/[Your app name]/oauth/token",
data: "username=admin&password=admin&grant_type=password&scope=read write&client_secret=my-secret-token-to-change-in-production&client_id=auth2Sconnectapp",
withCredentials: true,
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Accept': 'application/json',
'Authorization': 'Basic ' + 'YXV0aDJTY29ubmVjdGFwcDpteS1zZWNyZXQtdG9rZW4tdG8tY2hhbmdlLWluLXByb2R1Y3Rpb24='
}
})
.success(function(data) {
alert("success: " + data);
})
.error(function(data, status) {
alert("ERROR: " + data);
});
Here "YXV0aDJTY29ubmVjdGFwcDpteS1zZWNyZXQtdG9rZW4tdG8tY2hhbmdlLWluLXByb2R1Y3Rpb24=" is equal to (clientId + ":" + clientSecret)--all base64-encoded
The above $http if successful will give you this JSON which contains token and it's expiry time
{
"access_token": "2ce14f67-e91b-411e-89fa-8169e11a1c04",
"token_type": "bearer",
"refresh_token": "37baee3c-f4fe-4340-8997-8d7849821d00",
"expires_in": 525,
"scope": "read write"
}
Take notice of "access_token" and "token_type" if you want to access any API this is what you have to use. We send the token with API to access data until the token expires then we either refresh it or access for a new one.
For example
$http({
method: "get",
url: "http://192.168.0.4:8085/auth-2-sconnect/api/countries",
withCredentials: true,
headers: {
'Authorization':' [token_type] + [space] + [access_token] '
}
})
.success(function(data) {
alert("success: " + data);
})
.error(function(data, status) {
alert("ERROR: " + data);
});
Here a summarisation of how I implemented the solution. It’s real swift code, but please take it as pseudocode, as it might be incorrect.
make a call to whatever method you need to call, passing in such method a callback (block, or equivalent) for the success and one for the failure
func action(
URLString:String,
method:Method,
encoding:Encoding = .JSON,
parameters:[String : AnyObject]?,
success:(statusCode:Int, responseObject:AnyObject)->Void,
failure:(statusCode:Int, error:NSError)->Void
)
Inside the method es. /events you handle a particular case of failure, which is when the status code is 401.
if(r!.statusCode==ResponseCodes.HTTP_UNAUTHORIZED.rawValue){
loginAndAction(URLString, method: method, encoding: encoding, parameters: parameters, success: success, failure: failure)
}else{
failure(statusCode: response.response!.statusCode, error:response.result.error!)
}
In this particular case, instead of returning back the result and calling the failure callback, you call a login() method which, after the necessary parameters, accept the original success() callback
func loginAndAction(
URLString:String,
method:Method,
encoding: Encoding,
parameters:[String:AnyObject]?,
success:(statusCode:Int, responseObject:AnyObject)->Void,
failure:(statusCode:Int, error:NSError)->Void
)->Void
if the authentication succeeds
var d:[String:AnyObject] = response.result.value as! [String:AnyObject]
self.authToken = d["access_token"] as! String
action(URLString, method: method,encoding:encoding, parameters: parameters, success: success, failure: failure)
at this point the method action could use a proper working token.
This should happen only once a day (based on the token expiration), and it is a mechanism appliable to the oauth2 refresh_token call.

Trying to use 'Postman' and having trouble setting Basic access authentication Headers

I have an API endpoint that I am trying to test with the google app: 'Postman'. I need to set the headers which use 'Basic authentication'. I am not sure what should go in 'Header: Value'
This is how the admin said the headers should be set:
"The head value is the word 'Basic' followed by your org name and your Api key separated by a colon and base64 encoded."
I have tried numerous things but I am not getting it quite right. The error I get is "Message: Token not set".
Your header field should look like this:
Header : Authorization
Value : Basic base64('YourOrgName:YourAPIKEY');
You can get the base64 value of your string here:
https://www.base64encode.org/
For example, for my-org-name:123key4api it should be bXktb3JnLW5hbWU6MTIza2V5NGFwaQ==.
The complete header would look like:
Authorization: Basic bXktb3JnLW5hbWU6MTIza2V5NGFwaQ==
Looks like you are facing trouble in getting the base64 value. Well you can make use of in-built function in Javscript as below.
Simply run below code in any JS runtime, (Simplest would be - open console tab in chrome developer tool)
"username:password!" // Here I used basic Auth string format
// Encode the plain string to base64
btoa("username:password!"); // output: "dXNlcm5hbWU6cGFzc3dvcmQh"
// Decode the base64 to plain string
atob("dXNlcm5hbWU6cGFzc3dvcmQh"); // output: "username:password!"
It's 2019 and with Version 6.5.3 we have a separate tab to use different kind of Authentication techniques.
For basic auth you just have to give username and password after selecting "Basic Auth" under Authentication tab
Putting it all together in a pre-request script
(and then use the access_token for oauth).
var Base64={_keyStr:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",encode:function(e){var t="";var n,r,i,s,o,u,a;var f=0;e=Base64._utf8_encode(e);while(f<e.length){n=e.charCodeAt(f++);r=e.charCodeAt(f++);i=e.charCodeAt(f++);s=n>>2;o=(n&3)<<4|r>>4;u=(r&15)<<2|i>>6;a=i&63;if(isNaN(r)){u=a=64}else if(isNaN(i)){a=64}t=t+this._keyStr.charAt(s)+this._keyStr.charAt(o)+this._keyStr.charAt(u)+this._keyStr.charAt(a)}return t},decode:function(e){var t="";var n,r,i;var s,o,u,a;var f=0;e=e.replace(/[^A-Za-z0-9\+\/\=]/g,"");while(f<e.length){s=this._keyStr.indexOf(e.charAt(f++));o=this._keyStr.indexOf(e.charAt(f++));u=this._keyStr.indexOf(e.charAt(f++));a=this._keyStr.indexOf(e.charAt(f++));n=s<<2|o>>4;r=(o&15)<<4|u>>2;i=(u&3)<<6|a;t=t+String.fromCharCode(n);if(u!=64){t=t+String.fromCharCode(r)}if(a!=64){t=t+String.fromCharCode(i)}}t=Base64._utf8_decode(t);return t},_utf8_encode:function(e){e=e.replace(/\r\n/g,"\n");var t="";for(var n=0;n<e.length;n++){var r=e.charCodeAt(n);if(r<128){t+=String.fromCharCode(r)}else if(r>127&&r<2048){t+=String.fromCharCode(r>>6|192);t+=String.fromCharCode(r&63|128)}else{t+=String.fromCharCode(r>>12|224);t+=String.fromCharCode(r>>6&63|128);t+=String.fromCharCode(r&63|128)}}return t},_utf8_decode:function(e){var t="";var n=0;var r=c1=c2=0;while(n<e.length){r=e.charCodeAt(n);if(r<128){t+=String.fromCharCode(r);n++}else if(r>191&&r<224){c2=e.charCodeAt(n+1);t+=String.fromCharCode((r&31)<<6|c2&63);n+=2}else{c2=e.charCodeAt(n+1);c3=e.charCodeAt(n+2);t+=String.fromCharCode((r&15)<<12|(c2&63)<<6|c3&63);n+=3}}return t}};
var userPass = pm.environment.get("oauth_key") + ':' + pm.environment.get("oauth_secret")
pm.sendRequest({
url: pm.environment.get("basepath")+"/oauthpreview/token",
method: 'POST',
header: {
'Accept': 'application/json',
'cache-control':"no-cache",
'Authorization' : 'Basic ' + Base64.encode(userPass),
'Content-Type': 'application/x-www-form-urlencoded'
},
body: {
mode: 'urlencoded',
urlencoded: [
{key: "grant_type", value: "client_credentials", disabled: false}
]
}
}, function (err, res) {
pm.environment.set("access_token", res.json().access_token);
})

what is the use beforeSend function in (Jquery) Ajax

What is the use of beforeSend Function in jQuery Ajax?
How to use the jQuery function?
I am Using jQuery 1.6.0, and Using Jersey API (Restful Web services) on Server Side.
$.ajax({
type: "GET",
url:ajax_url,
dataType: "json",
contentType: "application/json",
async: false,
beforeSend: function (xhr){
xhr.setRequestHeader('Authorization', "Basic "+ btoa(username + ':' + password));
},
success:function(data){
alert(data.groups);
},
error:function(xhr,err){
console.log("readyState:"+xhr.readyState+"\nstatus: "+xhr.status)
alert(xhr.responseText)
alert("Service is not Available , Try it after Some time");
}
});
Java Code :
#GET
#Produces(MediaType.APPLICATION_JSON)
public String authCheck(){
return "({"groups": "success"})";
}
Whenever I am sending for authentication I am getting success response.
How to use beforeSend function and does we need to do any thing on server side?
Generally beforeSend() is used to do some stuff before actually send AJAX request like set Custom header and etc...
but your need is different that you want to authenticate user before your ajax call than
create one another function which give you User is authenticated or Not in Response
suppose this function is checkAuth();
so use
type: "GET",
url:ajax_url,
dataType: "json",
contentType: "application/json",
async: false,
beforeSend:checkAuth,
.
.
.

MVC + Extjs + IIS6 + Wildcard Mapping = Post Form resulting in 302 object moved

Everything seems to work fine until i want to submit the form and update the database.
Wildcard mapping works on requests like "/navigation/edit/1", but when i submit the form as:
var ajaxPost = function(Url, Params) {
Ext.Ajax.request({
url: Url,
params: Params,
method: 'POST',
async: false,
scope: this
});
};
it says "200 bad response: syntax error" and in firebug there is "Failed to load source for: http://.../Navigation/edit/1".
Any help?
Perhaps its a syntax error: try
params: {"sendparams": Params}
it turns out there was a urlrewrite rule for some other web site corrupting my requests.