Sending parameter along URL actionscript - apache-flex

As part of a mobile app I'm building I have to authenticate trough the API of Last.FM.
As documented on their website I tried to format to url correctly but appearently I'm doing something wrong because I get error:
Error #2044: Unhandled ioError:. text=Error #2032: Stream Error. URL: https://ws.audioscrobbler.com/2.0/?method=auth.getMobileSession
Last.FM documentation: http://www.last.fm/api/mobileauth
My code below:
var username:String = "xxxxxxx";
var password:String = "xxxxxxxxxxxx";
var api_key:String = "xxxxxxxxxxxxxxxxxxxxxxxxxx";
var secret:String = "xxxxxxxxxxxxxxxxxxxxxx";
var api_sig:String = MD5.hash( "api_key" + api_key + "methodauth.getMobileSessionpassword" + password + "username" + secret);
var request:URLRequest = new URLRequest("https://ws.audioscrobbler.com/2.0/?method=auth.getMobileSession");
var variables:URLVariables = new URLVariables();//create a variable container
variables.username =username;
variables.password = password;
variables.api_key = api_key;
variables.api_sig = api_sig;
request.data = variables;
request.method = URLRequestMethod.POST;//select the method as post/
var loader:URLLoader = new URLLoader();
loader.addEventListener(Event.COMPLETE, handleComplete);
loader.load(request);//send the request with URLLoader()
Does someone know the answer?

Try to use HTTPService instead of URLLoader. Smth like this:
var http:HTTPService = new HTTPService();
http.useProxy = false;
http.resultFormat = "e4x";
http.method = "POST";
http.url = "https://ws.audioscrobbler.com/2.0/?method=auth.getMobileSession";
var variables:Object = {};
variables.username = username;
variables.password = password;
variables.api_key = api_key;
variables.api_sig = api_sig;
var token:AsyncToken = http.send(variables);
var responder:Responder = new Responder(handleRequestComplete, handleError);
token.addResponder(responder);
Where handleRequestComplete and handleError are your handlers for the request results:
private function handleRequestComplete(event:ResultEvent):void
{
// your code here
}
private function handleError(event:FaultEvent):void
{
// your code here
}

Related

How can I make proper request for the Identity Server Token Endpoint?

I tried to send an api call to the identity server via .net 6 console application.
Here is the request:
public static async Task<WorkflowResponse> PostRequestToIdentityAsync()
{
var url = "http://didentity/connect/token";
IdentityRequestDataVM identityRequestDataVM = new IdentityRequestDataVM();
identityRequestDataVM.username = "csm";
identityRequestDataVM.password = "MjAyMjox";
identityRequestDataVM.grant_type = "password";
identityRequestDataVM.scope = "m_gln m_msd";
string jsonString = JsonConvert.SerializeObject(identityRequestDataVM);
using (var httpClient = new HttpClient())
{
var request = new HttpRequestMessage
{
Method = HttpMethod.Post,
RequestUri = new Uri(url),
Content = new StringContent(jsonString),
Headers =
{
{"X-Login","override"}
}
};
var user = "gclt";
var password = "glsrt";
request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded"));
request.Headers.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes($"{user}:{password}")));
HttpResponseMessage message = await httpClient.SendAsync(request);
if (message.StatusCode == System.Net.HttpStatusCode.OK)
{
var contents = await message.Content.ReadAsStringAsync();
WorkflowResponse workflowResponse = JsonConvert.DeserializeObject<WorkflowResponse>(contents);
return workflowResponse;
}
else
{
throw new Exception(await message.Content.ReadAsStringAsync());
}
}
}
But, it returned 400 err code (Bad request), is there any mistake in the code snippet ?
It is working fine with postman.

ITfoxtec SAML 2.0 encrypt assertion

Is it possible to encrypt the assertion response with ITfoxtec Identity Saml2 (open source - https://itfoxtec.com/identitysaml2)? Haven't been able to find anything.
The GitHub site (https://github.com/ITfoxtec/ITfoxtec.Identity.Saml2) mentions decrypting but not encrypting. Doesn't seem to be any examples on encrypting either.
Any help is appreciated. Thanks.
In saml2postbinding class, replace BindInternal method with below code.
protected override Saml2PostBinding BindInternal(Saml2Request saml2RequestResponse, string messageName)
{
BindInternal(saml2RequestResponse);
var element1 = XmlDocument.CreateElement("saml2", "EncryptedAssertion", "urn:oasis:names:tc:SAML:2.0:assertion");
XmlDocument xmlDoc = new XmlDocument();
var assertionElements = XmlDocument.DocumentElement.SelectNodes($"//*[local-name()='{Saml2Constants.Message.Assertion}']");
var assertionElement = (assertionElements[0] as XmlElement).ToXmlDocument().DocumentElement;
var certificate = ITfoxtec.Identity.Saml2.Util.CertificateUtil.Load(#"F:\IT-FoxTec-Core Copy\ITfoxtec.Identity.Saml2-master (1)\ITfoxtec.Identity.Saml2-master\test\TestIdPCore\itfoxtec.identity.saml2.testwebappcore_Certificate.crt");
var wrappedAssertion = $#"<saml2:EncryptedAssertion xmlns:saml2=""urn:oasis:names:tc:SAML:2.0:assertion"">{assertionElement.OuterXml}</saml2:EncryptedAssertion>";
xmlDoc.LoadXml(wrappedAssertion);
var elementToEncrypt = (XmlElement)xmlDoc.GetElementsByTagName("Assertion", Saml2Constants.AssertionNamespace.OriginalString)[0];
element1.InnerXml = wrappedAssertion.ToXmlDocument().DocumentElement.SelectNodes($"//*[local-name()='{Saml2Constants.Message.Assertion}']")[0].OuterXml;
var element2 = wrappedAssertion.ToXmlDocument().DocumentElement;
var childNode = XmlDocument.GetElementsByTagName("Assertion", Saml2Constants.AssertionNamespace.OriginalString)[0];
XmlDocument.DocumentElement.RemoveChild(childNode);
var status = XmlDocument.DocumentElement[Saml2Constants.Message.Status, Saml2Constants.ProtocolNamespace.OriginalString];
XmlDocument.DocumentElement.InsertAfter(element1, status);
if (certificate == null) throw new ArgumentNullException(nameof(certificate));
var encryptedData = new EncryptedData
{
Type = EncryptedXml.XmlEncElementUrl,
EncryptionMethod = new EncryptionMethod(EncryptedXml.XmlEncAES256Url)
};
var algorithm = true ? EncryptedXml.XmlEncRSAOAEPUrl : EncryptedXml.XmlEncRSA15Url;
var encryptedKey = new EncryptedKey
{
EncryptionMethod = new EncryptionMethod(algorithm),
};
var encryptedXml = new EncryptedXml();
byte[] encryptedElement;
using (var encryptionAlgorithm = new AesCryptoServiceProvider())
{
encryptionAlgorithm.KeySize = 256;
encryptedKey.CipherData = new CipherData(EncryptedXml.EncryptKey(encryptionAlgorithm.Key, (RSA)certificate.PublicKey.Key, true));
encryptedElement = encryptedXml.EncryptData(elementToEncrypt, encryptionAlgorithm, false);
}
encryptedData.CipherData.CipherValue = encryptedElement;
encryptedData.KeyInfo = new KeyInfo();
encryptedData.KeyInfo.AddClause(new KeyInfoEncryptedKey(encryptedKey));
EncryptedXml.ReplaceElement((XmlElement)xmlDoc.GetElementsByTagName("Assertion", Saml2Constants.AssertionNamespace.OriginalString)[0], encryptedData, false);
EncryptedXml.ReplaceElement((XmlElement)XmlDocument.GetElementsByTagName("Assertion", Saml2Constants.AssertionNamespace.OriginalString)[0], encryptedData, false);
if ((!(saml2RequestResponse is Saml2AuthnRequest) || saml2RequestResponse.Config.SignAuthnRequest) && saml2RequestResponse.Config.SigningCertificate != null)
{
Cryptography.SignatureAlgorithm.ValidateAlgorithm(saml2RequestResponse.Config.SignatureAlgorithm);
XmlDocument = XmlDocument.SignDocument(saml2RequestResponse.Config.SigningCertificate, saml2RequestResponse.Config.SignatureAlgorithm, CertificateIncludeOption, saml2RequestResponse.Id.Value);
}
PostContent = string.Concat(HtmlPostPage(saml2RequestResponse.Destination, messageName));
return this;
}
Here certificate is public key certificate for any relying party.
I m sorry to say that assertion response encryption is currently not supported.
You are Welcome to create an issue on the missing encryption funktionalitet.
If you implement the functionality please share the code.

Xamarin Forms HttpClient Multipart/FormData returns 403 Forbidden

I'm trying to make chat app with XamarinForms and I'm trying to upload a file with parameters to server. But I'm getting always 403 Forbidden message. (There is no authentication, there is only token key for now).
If I try to get or send any data to server, it works as well. When I try to send a file with data it returns 403 Forbidden message. I also tried to send same data with Postman. it's worked as well. I'm writing part of code, Could you please tell me, I made it wrong where?
Thanks in advance.
private async Task<HttpClient> GetClient()
{
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Add("Accept", "application/json");
client.DefaultRequestHeaders.Add("X-Token-Key", ServiceToken);
client.DefaultRequestHeaders.UserAgent.Add(new System.Net.Http.Headers.ProductInfoHeaderValue("Chrome", "41.0.2228.0"));
return client;
}
If I send text message, it works as well.
public async Task<MobileResult> SendConversationTextMessage(MessageModel message)
{
HttpClient client = await GetClient();
string param = JsonConvert.SerializeObject(message);
var response = await client.PostAsync(Url + "conversation/message_add_text", new StringContent(param, Encoding.UTF8, "application/json"));
var mobileResult = JsonConvert.DeserializeObject<MobileResult>(await response.Content.ReadAsStringAsync());
return mobileResult;
}
If I send message with data, it returns 403 Forbidden
public async Task<MobileResult> SendConversationFileMessage(
FileModel FileMessage,
int UserRemoteId,
int ConversationId,
int ToUserId,
string SendedTime,
MessageModel.MessageType Type,
MessageModel.MessageStatus Status,
string MessageType)
{
HttpClient client = await GetClient();
string PostUrl = Url + "conversation/message_add_" + MessageType;
MultipartFormDataContent content = new MultipartFormDataContent();
ByteArrayContent baContent = new ByteArrayContent(FileMessage.BinaryData);
StringContent UserIdContent = new StringContent(UserRemoteId.ToString());
StringContent ConversationIdContent = new StringContent(ConversationId.ToString());
StringContent ToUserIdContent = new StringContent(ToUserId.ToString());
StringContent SendedTimeContent = new StringContent(SendedTime.ToString());
StringContent TypeContent = new StringContent(Type.ToString());
StringContent StatusContent = new StringContent(Status.ToString());
content.Add(baContent, "AttachedFile", FileMessage.Name);
content.Add(UserIdContent, "serId");
content.Add(ConversationIdContent, "ConversationId");
content.Add(ToUserIdContent, "ToUserId");
content.Add(SendedTimeContent, "SendedTime");
content.Add(TypeContent, "Type");
content.Add(StatusContent, "Status");
try
{
var response = await client.PostAsync(PostUrl, content);
string result = await response.Content.ReadAsStringAsync();
var mobileResult = JsonConvert.DeserializeObject<MobileResult>(result);
return mobileResult;
}
catch (Exception e)
{
return new MobileResult
{
Result = false,
Data = null,
Message = e.ToString()
};
}
}
Postman-Screenshot
Edit: I've tested to send multipart/form-data different way but result is same I'm writing below code:
MultipartFormDataContent content = new MultipartFormDataContent();
var UserIdContent = new StringContent(UserId.ToString());
UserIdContent.Headers.Add("Content-Disposition", "form-data; name=\"UserId\"");
UserIdContent.Headers.Remove("Content-Type");
content.Add(UserIdContent, "UserId");
var ConversationIdContent = new StringContent(ConversationId.ToString());
ConversationIdContent.Headers.Add("Content-Disposition", "form-data; name=\"ConversationId\"");
ConversationIdContent.Headers.Remove("Content-Type");
content.Add(ConversationIdContent, "ConversationId");
var ToUserIdContent = new StringContent(ToUserId.ToString());
ToUserIdContent.Headers.Add("Content-Disposition", "form-data; name=\"ToUserId\"");
ToUserIdContent.Headers.Remove("Content-Type");
content.Add(ToUserIdContent, "ToUserId");
var SendedTimeContent = new StringContent(SendedTime.ToString());
SendedTimeContent.Headers.Add("Content-Disposition", "form-data; name=\"SendedTime\"");
SendedTimeContent.Headers.Remove("Content-Type");
content.Add(SendedTimeContent, "SendedTime");
var TypeContent = new StringContent(Type.ToString());
TypeContent.Headers.Add("Content-Disposition", "form-data; name=\"Type\"");
TypeContent.Headers.Remove("Content-Type");
content.Add(TypeContent, "Type");
var StatusContent = new StringContent(Status.ToString());
StatusContent.Headers.Add("Content-Disposition", "form-data; name=\"Status\"");
StatusContent.Headers.Remove("Content-Type");
content.Add(StatusContent, "Status");
var streamContent = new StreamContent(file.InputStream);
streamContent.Headers.Add("Content-Disposition", "form-data; name=\"AttachedFile\"; filename=\"" + file.FileName + "\"");
streamContent.Headers.Add("Content-Type", "video/mp4");
content.Add(streamContent, "AttachedFile", file.FileName);

when retrive data from mongodb it give the tiimeout exception

Bellow is my code
public async void TestLoops(long device, double date1, double date2)
{
var connectionString = "mongodb://localhost.:27017";//Connection string
MongoClientSettings settings1 = MongoClientSettings.FromUrl(new MongoUrl(connectionString));// Set Url to the MongoClient
//MongoS
// MongoClient mongoClient = new MongoClient(settings1);
var client = new MongoClient(new MongoClientSettings
{
Server = new MongoServerAddress("connectionString"),
ClusterConfigurator = builder =>
{
builder.ConfigureCluster(settings => settings.With(serverSelectionTimeout: TimeSpan.FromSeconds(1000)));
}
});
//Server s = new MongoServerAddress(connectionString);
var db = client.GetDatabase("tracking");//Specifing the Database name
var user = db.GetCollection<BsonDocument>("location");//Specifing t
var builder1 = Builders<BsonDocument>.Filter;
// var builder1 = Builders<BsonDocument>.Filter;
//int
var filt = builder1.Eq("device", device) & builder1.Gte("timestamp", date1) & builder1.Lte("timestamp", date2);
//var filter = builder1.Eq("device", 358740050124519);
var data = user.Find(filt).Count();
lblmsg.Text = data.ToString();
}
when i write the var data = user.Find(filt); it works fine
You can do
var collection = database.GetCollection<Type>("DBName");
var cursor = collection.Find(Query.EQ("FieldToMatch" : "ValueToMatch"));
var count = cursor.Count();
another approach
db.collection.CountAsync(); // you can pass new BsonDocument() or a condition to countAsync based on your requirement.

Remote Image with basic authentication?

I would like to load a an image from an external domain and I have the below so far:
private function get_coverArt(coverArtID:String):void
{
var requestString:String = "/rest/getCoverArt.view?v=1.5.0&c=AirSub&id=" + coverArtID;
var requestURL:String = subServerURL + requestString;
myCoverArtLoader = new URLLoader();
var myRequest:URLRequest = new URLRequest();
var authHeader:URLRequestHeader = new URLRequestHeader();
authHeader.name = 'Authorization';
authHeader.value = 'Basic ' + credentials;
myRequest.requestHeaders.push(authHeader);
myRequest.url = requestURL;
myRequest.method = URLRequestMethod.GET;
myCoverArtLoader.dataFormat = URLLoaderDataFormat.BINARY;
myCoverArtLoader.addEventListener(Event.COMPLETE, set_coverArt);
myCoverArtLoader.load(myRequest);
}
private function set_coverArt(evt:Event) : void {
coverArtImg = new Image();
var loader:Loader = new Loader();
loader.loadBytes(myCoverArtLoader.data);
coverArtImg.source = loader;
}
This does not seem to work - any help?
Thanks!
Try setting the source directly like so:
private function set_coverArt(evt:Event) : void {
coverArtImg = new Image();
coverArtImg.source = myCoverArtLoader.data;
}
Also, check your authentication, here's a question I answered regarding the auth :
Actionscript 3: Reading an RSS feed that requires authentication

Resources