Reputation: 119
I am calling a create service of SAP Net weaver Gateway from SAPUI5. I have written following code for getting CSRF but I am not able to get it. It asks me to enter the username and password as shown in the image.
Code:
function onSave()
{
useroDataModel = newsap.ui.model.odata.ODataModel("proxy/sap/opu/odata/sap/ZUI_GROUP1_CREATE");
empid = oTF2.getValue();
empname = oTF1.getValue();
empaddr = oTF.getValue();
empdoj = oDP.getValue();
uilogon();
useroDataModel.read("/zui_group1_createCollection(im_emp_id='"+empid+"')", null, null, true, fnSuccess, fnError);
useroDataModel.setHeaders({
"X-CSRF-Token": "Fetch" // auth
});
function fnSuccess(data,response)
{
//alert(response.headers['x-csrf-token']);
var header_xcsrf_token = response.headers['x-csrf-token'];
//alert(header_xcsrf_token);
var createrequestdata = {
im_emp_id : empid,
im_emp_name : empname(),
im_emp_addr : empaddr(),
im_emp_doj : empdoj()
};
useroDataModel.setHeaders({
"X-Requested-With": "XMLHttpRequest",
"Content-Type": "application/atom+xml",
"DataServiceVersion": "2.0",
"Accept": "application/atom+xml,application/atomsvc+xml,application/xml",
"X-CSRF-Token": header_xcsrf_token
});
useroDataModel.create("/zui_g2_createCollection", createrequestdata, null, fnS, fnE);
function fnS(response){
if(response.ex_status == "Entry Created.")
{
alert("Created.");
}
else
{
alert("Failed.");
}
}
function fnE(Error){
alert("error in create"+Error.message);
}
}
function fnError(oError)
{
alert("Error in read"+oError.message);
}
}
function uilogon()
{
var tok = "username" + ':' + "password";
var hash = btoa(tok);
auth = "Basic" + hash;
// alert(auth);
// Save to Local Storage
// $.sap.require("jquery.sap.storage");
// var UI5Storage = $.sap.storage(jQuery.sap.storage.Type.session);
// UI5Storage.remove("Auth");
// UI5Storage.put("Auth",auth);
useroDataModel.setHeaders({
//'Accept-Encoding': "gzip",
"Authorization" : auth});
// alert("dne");
}
I am able to fetch the CSRF-TOKEN in auth variable. But it asks me for following authentication in which asks me to enter the username and password of SAP NET WEAVER GATEWAY but if I enter the username and password through which I am logged in, it does not accept.
Upvotes: 0
Views: 17833
Reputation: 2473
If you want to use your method of authentication you will need to authenticate prior to the ODataModel instantiation, you cant read the metadata let alone fetch a CSRF token unless authenticated, also you need to fetch the token prior to doing the POST.
Why not pass the username and password into the constructor of the ODataModel
var oModel = new sap.ui.model.odata.ODataModel(sServiceUrl, bJSON, sUser, sPwd);
once authenticated if you are using binding functionality the CSRF security token will be read for you else if you want to use oModel.read you can do it manually
oModel.refreshSecurityToken()
Upvotes: 4