WCF - CustomBinding for signing timestamp, body and BinarySecirityToken - wcf

I need to call a java/Oracle partner which has strict format requirements.
My request should look like this :
sample request
But it actually looks like this :
my request
The BinarySecurityToken is duplicated for some reason.
My custom binding :
UPLVaccinatieGegevensClient client = new UPLVaccinatieGegevensClient(GetBinding(), new EndpointAddress(new Uri("https://...."), EndpointIdentity.CreateDnsIdentity("...")));
client.ClientCredentials.ClientCertificate.SetCertificate(System.Security.Cryptography.X509Certificates.StoreLocation.LocalMachine, System.Security.Cryptography.X509Certificates.StoreName.My, System.Security.Cryptography.X509Certificates.X509FindType.FindByThumbprint, "...");
client.ClientCredentials.ServiceCertificate.SetDefaultCertificate(System.Security.Cryptography.X509Certificates.StoreLocation.LocalMachine, System.Security.Cryptography.X509Certificates.StoreName.My, System.Security.Cryptography.X509Certificates.X509FindType.FindByThumbprint, "...");
var vs = client.Endpoint.EndpointBehaviors.FirstOrDefault((i) => i.GetType().Namespace == "Microsoft.VisualStudio.Diagnostics.ServiceModelSink");
if (vs != null)
{
client.Endpoint.Behaviors.Remove(vs);
}
client.Endpoint.Contract.ProtectionLevel = System.Net.Security.ProtectionLevel.Sign;
//UPLVaccinatieGegevensClient client = new UPLVaccinatieGegevensClient("UPLVaccinatieGegevens1");
var request = GetRequest();
var response = client.GetAanleverenVaccinatieGegevens(request);
}
private static CustomBinding GetBinding()
{
var messageSecurity = new AsymmetricSecurityBindingElement
{
MessageSecurityVersion = MessageSecurityVersion.WSSecurity10WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10,
InitiatorTokenParameters = new X509SecurityTokenParameters
{
InclusionMode = SecurityTokenInclusionMode.AlwaysToRecipient,
ReferenceStyle = SecurityTokenReferenceStyle.External,
X509ReferenceStyle = X509KeyIdentifierClauseType.RawDataKeyIdentifier,
RequireDerivedKeys = false
},
RecipientTokenParameters = new X509SecurityTokenParameters
{
InclusionMode = SecurityTokenInclusionMode.Never,
ReferenceStyle = SecurityTokenReferenceStyle.External,
X509ReferenceStyle = X509KeyIdentifierClauseType.Any,
RequireDerivedKeys = false
},
};
messageSecurity.EnableUnsecuredResponse = true;
messageSecurity.IncludeTimestamp = true;
messageSecurity.SecurityHeaderLayout = SecurityHeaderLayout.LaxTimestampFirst;
messageSecurity.DefaultAlgorithmSuite = SecurityAlgorithmSuite.Basic256;
messageSecurity.MessageSecurityVersion = MessageSecurityVersion.WSSecurity10WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10;
messageSecurity.SetKeyDerivation(false);
messageSecurity.EndpointSupportingTokenParameters.Signed.Add(messageSecurity.InitiatorTokenParameters);
messageSecurity.LocalClientSettings.TimestampValidityDuration = new TimeSpan(0, 1, 0);
HttpsTransportBindingElement elem = new HttpsTransportBindingElement { RequireClientCertificate = true };
CustomBinding binding = new CustomBinding(messageSecurity, new TextMessageEncodingBindingElement(MessageVersion.Soap11, Encoding.UTF8), elem);
return binding;
}
What am I missing ?

It appears that the extra token was being added when X509SecurityTokenParameters.InclusionMode was set to anything else than SecurityTokenInclusionMode.Never on the either of InitiatorTokenParameters, RecipientTokenParameters or EndpointSupportingTokenParameters.Signed.
You can try to set the value of InclusionMode to SecurityTokenInclusionMode.Never:
InclusionMode = SecurityTokenInclusionMode.Never

Related

connect to ssrs srevice in asp.net core

I get exception when connection with ssrs service last for more than 5 minutes
var binding = new BasicHttpBinding(BasicHttpSecurityMode.TransportCredentialOnly);
binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Ntlm;
binding.MaxReceivedMessageSize = 2147483647;
binding.MaxBufferPoolSize = 2147483647;
binding.MaxBufferSize = 2147483647;
binding.SendTimeout = TimeSpan.FromMinutes(_SendTimeout);
binding.OpenTimeout = TimeSpan.FromMinutes(_SendTimeout);
binding.ReceiveTimeout = TimeSpan.FromMinutes(_SendTimeout);
binding.CloseTimeout = TimeSpan.FromMinutes(_SendTimeout);
var rsExec = new rsexec2005.ReportExecutionServiceSoapClient(binding, new
EndpointAddress(SSRSReportExecutionUrl));
var clientCredentials = new NetworkCredential(SSRSUsername, SSRSPassword,
SSRSDomain);
if (rsExec.ClientCredentials != null)
{
rsExec.ClientCredentials.Windows.AllowedImpersonationLevel =
System.Security.Principal.TokenImpersonationLevel.Impersonation;
rsExec.ClientCredentials.Windows.ClientCredential = clientCredentials;
}
LoadReportResponse report = null;
try
{
rsExec.Endpoint.EndpointBehaviors.Add(new
ReportingServicesEndpointBehavior());
report = await rsExec.LoadReportAsync(null, "/" + SSRSFolderPath + "/" +
reportName, null);
}
catch (Exception ex1)
{
return new Response { code = 1, report = null, message = ex1.InnerException +"
# "+ ex1.Message };
}
rsexec2005.ParameterValue[] reportParam = new
rsexec2005.ParameterValue[report.executionInfo.Parameters.ToList().Count];
var Count = 0;
foreach (var item in report.executionInfo.Parameters.ToList())
{
var Paramkay = Params.Keys.SingleOrDefault(i => i.ToLower() ==
item.Name.ToLower());
if (Paramkay != null)
{
reportParam[Count] = new rsexec2005.ParameterValue();
reportParam[Count].Name = item.Name;
reportParam[Count].Value = Params[Paramkay];
Count++;
}
}
await rsExec.SetExecutionParametersAsync(null, null, reportParam, "en-us");
RenderResponse response = null;
try
{
const string deviceInfo = #"<DeviceInfo><Toolbar>False</Toolbar></DeviceInfo>";
response = await rsExec.RenderAsync(new RenderRequest(null, null, extention, deviceInfo));
}
catch (TimeoutException ex4)
{
return new Response { code = 4, report = null , message= ex4.InnerException + " # " + ex4.Message };
}
catch (Exception ex2)
{
return new Response { code = 2, report = null , message = ex2.InnerException + " # " + ex2.Message };
}

Blob Service REST API - Put Blob returning 403 Forbidden when x-ms-blob-content-type is set

I've successfully been able to create Blobs in my container, but when I try to set the x-ms-blob-content-type header, no Blob is created and I get a 403 error. Here is my code:
var authorizationHeader = CreateAuthorizationHeader(stringToSign);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(blobEndpoint + urlPath);
request.Method = requestMethod;
request.Headers["x-ms-blob-type"] = blobType;
request.Headers["x-ms-date"] = dateInRfc1123Format;
request.Headers["x-ms-version"] = storageServiceVersion;
request.Headers["Authorization"] = authorizationHeader;
request.ContentLength = blobLength;
try
{
using (Stream requestStream = await request.GetRequestStreamAsync())
{
requestStream.Write(blobContent, 0, blobLength);
}
using(HttpWebResponse response = (HttpWebResponse)await request.GetResponseAsync())
{
var eTag = response.Headers["ETag"];
}
}
But whenever I try to add either of these lines, I get a 403:
request.Headers["x-ms-blob-content-type"] = "image/jpeg";
//or
request.ContentType = "image/jpeg";
Have any of you encountered this? Appreciate any feedback, thanks!
UPDATE: adding the stringToSign code below.
var canonicalizedHeaders = String.Format(
"x-ms-blob-type:{0}\nx-ms-date:{1}\nx-ms-version:{2}",
blobType,
dateInRfc1123Format,
storageServiceVersion);
var canonicalizedResource = String.Format("/{0}/{1}", account, urlPath);
var stringToSign = String.Format(
"{0}\n\n\n{1}\n\n\n\n\n\n\n\n\n{2}\n{3}",
requestMethod,
blobLength,
canonicalizedHeaders,
canonicalizedResource);
Did you add x-ms-blob-content-type in both canonicalizedHeaders and in request headers? When adding it to canonicalizedHeaders, please make sure that this would be the first entry as the headers need to be sorted. I took your code and added the header and it worked perfectly fine. Here's my code:
private static async Task UploadBlob()
{
var blobType = "BlockBlob";
var dateInRfc1123Format = DateTime.UtcNow.ToString("R");
var storageServiceVersion = "2014-02-14";
var blobContentType = "image/png";
var canonicalizedHeaders = String.Format("x-ms-blob-content-type:{0}\nx-ms-blob-type:{1}\nx-ms-date:{2}\nx-ms-version:{3}", blobContentType, blobType, dateInRfc1123Format, storageServiceVersion);
var urlPath = "test-test/AlarmClock1.png";
var canonicalizedResource = String.Format("/{0}/{1}", accountName, urlPath);
var requestMethod = "PUT";
var fileContents = File.ReadAllBytes(#"D:\images\images\AlarmClock1.png");
var blobLength = fileContents.Length;
var stringToSign = String.Format("{0}\n\n\n{1}\n\n\n\n\n\n\n\n\n{2}\n{3}", requestMethod, blobLength, canonicalizedHeaders, canonicalizedResource);
var authorizationHeader = SignThis(stringToSign);
var blobEndpoint = "https://myaccountname.blob.core.windows.net/";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(blobEndpoint + urlPath);
request.Method = requestMethod;
request.Headers["x-ms-blob-content-type"] = blobContentType;
request.Headers["x-ms-blob-type"] = blobType;
request.Headers["x-ms-date"] = dateInRfc1123Format;
request.Headers["x-ms-version"] = storageServiceVersion;
request.Headers["Authorization"] = authorizationHeader;
request.ContentLength = blobLength;
try
{
using (Stream requestStream = await request.GetRequestStreamAsync())
{
requestStream.Write(fileContents, 0, blobLength);
}
using(HttpWebResponse response = (HttpWebResponse)await request.GetResponseAsync())
{
var eTag = response.Headers["ETag"];
}
}
catch (Exception excep)
{
}
}

i had upload file and some field items to document library i have made one field mandatory in that field but even then i am able to upload file

SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite site = new SPSite(SPContext.Current.Web.Url, SPUserToken.SystemAccount))
{
using (SPWeb web = site.OpenWeb())
{
web.AllowUnsafeUpdates = true;
SPFolder folder = web.Folders["ContractorDetails"];
SPFileCollection filecol = folder.Files;
Boolean replaceExistingFiles = true;
string filename = System.IO.Path.GetFileName(FileUpload.PostedFile.FileName);
byte[] contents = new byte[Convert.ToInt32(FileUpload.PostedFile.ContentLength)];
SPFile addedFile = filecol.Add(filename, contents, replaceExistingFiles);
SPItem newItem = addedFile.Item;
newItem["Title"] = ddlTitle.SelectedValue;
newItem["First Name"] = tbFirstName.Text;
newItem["Middle Name"] = tbMiddleName.Text;
newItem["Last Name"] = tbLastName.Text;
newItem["NT User Name"] = tbNtuser.Text;
newItem["Contract Firm"] = tbContractFirm.Text;
newItem["Employee Type"] = tbEmpType.Text;
newItem["Division"] = ddlDivision.SelectedValue;
newItem["Location"] = ddlLocation.SelectedValue;
newItem["Contract Start Date"] = dateTimeStart.SelectedDate;
newItem["Contract End Date"] = dateTimeEnd.SelectedDate;
newItem["Project Term"] = Convert.ToInt32(tbProjectTerm.Text);
// newItem["Manager"] = PeopleEditor1.t
newItem["Comments"] = tbcomments.Text;
newItem.Update();
addedFile.Update();
web.AllowUnsafeUpdates = false;
}
}
});
}
Can you just try to upload file from UI to check field is mandatory or not?

writing posixAccount to LDAP doesn't work

I tried to write PosixAccount on LDAP to an existing user. i get no error, but when checking LDAP the new entry has not been written.
i added a new user first which is working well!
=>
public bool RegisterUser(UserObject userObj, HttpContext httpContext){
bool success = false;
//create a directory entry
using (DirectoryEntry de = new DirectoryEntry())
{
try
{
InitializeCommonDataForDirectoryEntry(
de,
String.Format("{0}/{1}",
GetConfigEntry(Common.CommonDefinitions.CE_LDAP_CONFIG_SERVER, httpContext),
GetConfigEntry(Common.CommonDefinitions.CE_LDAP_CONFIG_DIRECTORY_ENTRY_ROOT, httpContext)),
httpContext);
DirectorySearcher ds = new DirectorySearcher(de);
ds.SearchScope = System.DirectoryServices.SearchScope.Subtree;
ds.Filter = "(&(objectClass=organizationalUnit)(ou=people))";
SearchResult result = ds.FindOne();
if (result != null)
{
DirectoryEntry myDirectoryEntry = result.GetDirectoryEntry();
DirectoryEntry newEntry = myDirectoryEntry.Children.Add(String.Format("cn={0}", userObj.userName), "inetOrgPerson");
if (userObj.company != null && !userObj.company.Equals(String.Empty))
newEntry.Properties["businessCategory"].Add(String.Format("{0}", userObj.company));
newEntry.Properties["givenName"].Add(String.Format("{0}", userObj.firstName));
newEntry.Properties["sn"].Add(String.Format("{0}", userObj.lastName));
newEntry.Properties["uid"].Add(String.Format("{0}", userObj.userName));
newEntry.Properties["mail"].Add(String.Format("{0}", userObj.email));
userObj.password = GenerateSaltedSHA1(userObj.password);
newEntry.Properties["userPassword"].Add(String.Format("{0}", userObj.password));
newEntry.Properties["pager"].Add(String.Format("{0}", userObj.newsletter));
newEntry.Properties["initials"].Add(String.Format("{0}", GetConfigEntry(Common.CommonDefinitions.CE_MOWEE_PACKAGE_1, httpContext)));
newEntry.CommitChanges();
newEntry.RefreshCache();
success = true;
}
}
catch (Exception ex)
{
Trace.Write("Exception : RegisterUser: " + ex);
GeneralUtils.SendBugMail(ex, httpContext);
}
}
return success;
}
after that i want to write posixAccount for that user, which is not working
maybe someone can help me PLEASE and check what i did wrong !?
=>
public bool WritePosixAccountDataForRegisteredUser(UserObject userObj, HttpContext httpContext)
{
bool success = false;
//create a directory entry
using (DirectoryEntry de = new DirectoryEntry())
{
try
{
InitializeCommonDataForDirectoryEntry(
de,
String.Format("{0}/ou=people,{1}",
GetConfigEntry(Common.CommonDefinitions.CE_LDAP_CONFIG_SERVER, httpContext),
GetConfigEntry(Common.CommonDefinitions.CE_LDAP_CONFIG_DIRECTORY_ENTRY_ROOT, httpContext)),
httpContext);
DirectorySearcher ds = new DirectorySearcher(de);
ds.SearchScope = System.DirectoryServices.SearchScope.Subtree;
ds.Filter = String.Format("(&(objectClass=*)(cn={0}))", userObj.userName);
SearchResult result = ds.FindOne();
if (result != null)
{
DirectoryEntry userEntry = result.GetDirectoryEntry();
//mandatory attributes
/*
* cn
gidNumber
homeDirectory
uid
uidNumber
* */
IADsPropertyList propList = (IADsPropertyList)userEntry.NativeObject;
ActiveDs.PropertyEntry myNewEntry1 = new ActiveDs.PropertyEntry();
ActiveDs.IADsPropertyValue propVal1 = new ActiveDs.PropertyValue();
propVal1.CaseIgnoreString = "posixAccount";
propVal1.ADsType = (int)ADSTYPEENUM.ADSTYPE_CASE_IGNORE_STRING;
myNewEntry1.Name = "objectClass";
myNewEntry1.Values = new object[] { propVal1 };
myNewEntry1.ControlCode = (int)ADS_PROPERTY_OPERATION_ENUM.ADS_PROPERTY_APPEND;
myNewEntry1.ADsType = (int)ADSTYPEENUM.ADSTYPE_CASE_IGNORE_STRING;
propList.PutPropertyItem(myNewEntry1);
ActiveDs.PropertyEntry myNewEntry2 = new ActiveDs.PropertyEntry();
ActiveDs.IADsPropertyValue propVal2 = new ActiveDs.PropertyValue();
propVal2.CaseIgnoreString = "504";
propVal2.ADsType = (int)ADSTYPEENUM.ADSTYPE_CASE_IGNORE_STRING;
myNewEntry2.Name = "gidNumber";
myNewEntry2.Values = new object[] { propVal2 };
myNewEntry2.ControlCode = (int)ADS_PROPERTY_OPERATION_ENUM.ADS_PROPERTY_APPEND;
myNewEntry2.ADsType = (int)ADSTYPEENUM.ADSTYPE_CASE_IGNORE_STRING;
propList.PutPropertyItem(myNewEntry2);
ActiveDs.PropertyEntry myNewEntry3 = new ActiveDs.PropertyEntry();
ActiveDs.IADsPropertyValue propVal3 = new ActiveDs.PropertyValue();
propVal3.CaseIgnoreString = "/data/WowzaMediaServer-3.0.3/content/mowee/" + userObj.userName;
propVal3.ADsType = (int)ADSTYPEENUM.ADSTYPE_CASE_IGNORE_STRING;
myNewEntry3.Name = "homeDirectory";
myNewEntry3.Values = new object[] { propVal3 };
myNewEntry3.ControlCode = (int)ADS_PROPERTY_OPERATION_ENUM.ADS_PROPERTY_APPEND;
myNewEntry3.ADsType = (int)ADSTYPEENUM.ADSTYPE_CASE_IGNORE_STRING;
propList.PutPropertyItem(myNewEntry3);
ActiveDs.PropertyEntry myNewEntry4 = new ActiveDs.PropertyEntry();
ActiveDs.IADsPropertyValue propVal4 = new ActiveDs.PropertyValue();
propVal4.CaseIgnoreString = "1100";
propVal4.ADsType = (int)ADSTYPEENUM.ADSTYPE_CASE_IGNORE_STRING;
myNewEntry4.Name = "uidNumber";
myNewEntry4.Values = new object[] { propVal4 };
myNewEntry4.ControlCode = (int)ADS_PROPERTY_OPERATION_ENUM.ADS_PROPERTY_APPEND;
myNewEntry4.ADsType = (int)ADSTYPEENUM.ADSTYPE_CASE_IGNORE_STRING;
propList.PutPropertyItem(myNewEntry4);
ActiveDs.PropertyEntry myNewEntry5 = new ActiveDs.PropertyEntry();
ActiveDs.IADsPropertyValue propVal5 = new ActiveDs.PropertyValue();
propVal5.CaseIgnoreString = userObj.userName;
propVal5.ADsType = (int)ADSTYPEENUM.ADSTYPE_CASE_IGNORE_STRING;
myNewEntry5.Name = "cn";
myNewEntry5.Values = new object[] { propVal5 };
myNewEntry5.ControlCode = (int)ADS_PROPERTY_OPERATION_ENUM.ADS_PROPERTY_APPEND;
myNewEntry5.ADsType = (int)ADSTYPEENUM.ADSTYPE_CASE_IGNORE_STRING;
propList.PutPropertyItem(myNewEntry5);
ActiveDs.PropertyEntry myNewEntry6 = new ActiveDs.PropertyEntry();
ActiveDs.IADsPropertyValue propVal6 = new ActiveDs.PropertyValue();
propVal6.CaseIgnoreString = userObj.userName;
propVal6.ADsType = (int)ADSTYPEENUM.ADSTYPE_CASE_IGNORE_STRING;
myNewEntry6.Name = "uid";
myNewEntry6.Values = new object[] { propVal6 };
myNewEntry6.ControlCode = (int)ADS_PROPERTY_OPERATION_ENUM.ADS_PROPERTY_APPEND;
myNewEntry6.ADsType = (int)ADSTYPEENUM.ADSTYPE_CASE_IGNORE_STRING;
propList.PutPropertyItem(myNewEntry6);
de.RefreshCache(new String[] { "objectClass" });
de.RefreshCache(new String[] { "gidNumber" });
de.RefreshCache(new String[] { "homeDirectory" });
de.RefreshCache(new String[] { "uidNumber" });
de.RefreshCache(new String[] { "cn" });
de.RefreshCache(new String[] { "uid" });
de.CommitChanges();
success = true;
}
}
catch (Exception ex)
{
Trace.Write("Exception : RegisterUser: " + ex);
GeneralUtils.SendBugMail(ex, httpContext);
}
}
return success;
}
I think the error you get would be informative for diagnosing any further.
When you create an object in AD I am pretty sure even if you do not specify a CN you get a default naming attribute of CN set. So this posixAccount create, which is setting cn, might be conflicting with an existing cn value. I forget if CN is multivalued or single valued in AD, but if it is single valued this would make more sense.

Get resolved SPUser IDs from Sharepoint 2010 PeoplePicker

I try to get selected user IDs from people picker control as below:
function GetUserIdsFromPP() {
var xml = _picker.find('div#divEntityData');
var visiblefor = new Array();
xml.each(function (i, row) {
var data = $(this).children().first('div').attr('data');
var xmlDoc;
if (window.DOMParser) {
parser = new DOMParser();
xmlDoc = parser.parseFromString(data, "text/xml");
}
else // Internet Explorer
{
xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async = false;
xmlDoc.loadXML(data);
}
var uid = xmlDoc.getElementsByTagName('Value')[0].firstChild.nodeValue;
visiblefor.push(uid);
});
return visiblefor;
}
The problem is that sometimes XML doesn't contain <Key>SPUserID</Key><Value>1</Value> and I get FQUN (user login with domain name).
What is the better way to resolve selected SPUserIds from PeoplePicker control?
This is how resolve emails from people picker control on client side
function GetEmailsFromPicker() {
var xml = _picker.find('div#divEntityData');
var result = new Array();
xml.each(function (i, row) {
var data = $(this).children().first('div').attr('data');
var xmlDoc;
if (window.DOMParser) {
parser = new DOMParser();
xmlDoc = parser.parseFromString(data, "text/xml");
}
else // Internet Explorer
{
xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async = false;
xmlDoc.loadXML(data);
}
var emailIndex = -1;
for (var i = 0; i < xmlDoc.childNodes[0].childNodes.length; i++) {
var element = xmlDoc.childNodes[0].childNodes[i];
var key = element.childNodes[0].childNodes[0].nodeValue;
if (key == 'Email') {
var uid = xmlDoc.childNodes[0].childNodes[i].childNodes[1].childNodes[0].nodeValue;
result.push({ EMail: uid });
break;
}
}
});
return result;
}
Use the above answer, but...
Replace this with an appropriate Jquery or Javascript element name.
var xml = _picker.find('div#divEntityData');