Remote Image with basic authentication? - apache-flex

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

Related

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.

web api post image with custom data

I am trying to post some custom data with image to web api. Please take a look at the method below.
public void Post(FlyerDetails FlyerDetails)
{
var httpRequest = HttpContext.Current.Request;
if (httpRequest.Files.Count > 0)
{
foreach (string file in httpRequest.Files)
{
var filePath = HttpContext.Current.Server.MapPath("~/Flyers/" + httpRequest.Files[file].FileName);
Bitmap bmp = new Bitmap(httpRequest.Files[file].InputStream);
Graphics g = Graphics.FromImage(bmp);
g.SmoothingMode = SmoothingMode.AntiAlias;
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.PixelOffsetMode = PixelOffsetMode.HighQuality;
g.DrawString(FlyerDetails.Message, new Font(FlyerDetails.FontColor, FlyerDetails.FontSize), Brushes.DarkRed, new PointF(0, 0));
g.Flush();
bmp.Save(filePath);
}
}
}
Now the problem is when i keep this method with parameter and post the data from fiddler it shows me 415 Unsupported Media Type error . If i remove the parameter then it is working fine. But i really need to pass the data along with the posted image.
Can any one suggest a good way to accomplish this ?
Thanks
After searching a lot i figured out the way to upload the data along with the image. Here is the revised version of the code. Hope that it will helpful to someone.
public async Task<HttpResponseMessage> Post()
{
var streamProvider = new MultipartFormDataStreamProvider(HttpContext.Current.Server.MapPath("~/Flyers/"));
await Request.Content.ReadAsMultipartAsync(streamProvider);
var response = Request.CreateResponse(HttpStatusCode.Created);
var filePath = "";// file path
if (System.IO.File.Exists(filePath))
{
string extension = Path.GetExtension(filePath);
Bitmap bmp = new Bitmap(filePath);
Graphics g = Graphics.FromImage(bmp);
g.SmoothingMode = SmoothingMode.AntiAlias;
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.PixelOffsetMode = PixelOffsetMode.HighQuality;
Color brushColor = System.Drawing.ColorTranslator.FromHtml(streamProvider.FormData["FontColorCode"]);
g.DrawString(streamProvider.FormData["FontFamily"], new Font(brushColor.Name, Convert.ToInt32(streamProvider.FormData["FontSize"])), new SolidBrush(brushColor), new PointF(0, 0));
g.Flush();
bmp.Save(HttpContext.Current.Server.MapPath("~/" + Guid.NewGuid() + extension));
response.Headers.Location = new Uri(new Uri(HttpContext.Current.Request.Url.AbsoluteUri).GetLeftPart(UriPartial.Authority) + "/Flyers/" + Guid.NewGuid() + extension);
}
return response;
}
NOTE : One should post the data as mutipart-formdata.
this line also gets a post parameter along with uploaded file:
string value = HttpContext.Current.Request.Params.Get("key");

Sending parameter along URL actionscript

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
}

Looping through an arraylist sourced from an XML file

I am reading in an XML file that is shown in the attached image. I'm reading it in using URLRequest, which works properly. The next thing I'd like to do is to populate an arraylist with all of the "project" nodes. I'm converting the XML to an array, but the source is showing the project as being in the [0] node and the arraylist's length is 1.
What's the proper way to do this so I can loop through all the projects in the arraylist?
private var xmlParameters:XML
private var xmlStoryMap:XMLList;
protected function application1_creationCompleteHandler(event:FlexEvent):void
{
var params:Object;
var xmlLoader:URLLoader = new URLLoader();
xmlLoader.addEventListener(Event.COMPLETE, xmlloader_onComplete_Handler);
xmlLoader.addEventListener(IOErrorEvent.IO_ERROR,IOError_handler);
xmlLoader.load(new URLRequest("myXML.xml"));
}
protected function xmlloader_onComplete_Handler(event:Event):void
{
var loader:URLLoader = URLLoader(event.target)
xmlParameters = new XML(loader.data);
xmlStoryMap = xmlParameters.projects;
initializeMap();
}
protected function initializeMap():void
{
var testlist:ArrayList = new ArrayList();
testlist.source = convertXMLtoArray(xmlStoryMap.project);
}
private function convertXMLtoArray(file:String):Array
{
var xml:XMLDocument = new XMLDocument(file);
var decoder:SimpleXMLDecoder = new SimpleXMLDecoder;
var data:Object = decoder.decodeXML(xml);
var array:Array = ArrayUtil.toArray(data);
return array;
}
If you don't want to have a loop issue, use this instead
protected function xmlloader_onComplete_Handler(event:Event):void
{
var loader:URLLoader = URLLoader(event.target)
var xmlString:String = loader.data;
initializeMap(xmlString);
}
protected function initializeMap(xmlString:String):void
{
var testlist:ArrayList = new ArrayList();
testlist.source = convertXMLtoArray(xmlString);
}
private function convertXMLtoArray(xmlString:String):Array
{
var xmlDoc:XMLDocument = new XMLDocument(xmlString);
var decoder:SimpleXMLDecoder = new SimpleXMLDecoder();
var data:Object = decoder.decodeXML(xmlDoc);
return ArrayUtil.toArray(data.storymap.projects.project);
}
For looping through the projects,
for each(var projectXML:XML in xmlParameters.projects.project)
{
// Do operation
}

load symbol of flash in flex at runtime

Hey people, I've this huge problem loading a symbol from a swf file in the application at runtime. I want to load it and pass it as a argument to another class where it could be used further. The symbol name is passed on from the array collection from the "o" object. Can anybody please tell me what's the right way to go about it.. Thanks in advance..!!
Following is the code for reference..
public override function Show(o:ObjectProxy):void
{
var _this:Weather;
var _super:ContentItem;
var item:WeatherItem;
var items:ArrayCollection;
var widgetCount:Number;
var headlineFontSize:int;
var conditionsIconThemeLoader:Loader;
this.m_weatherWidgetContainer = new HBox();
super.Show(o);
_this = this;
_super = super;
(undefined == o["HeadlineFontSize"]) ? headlineFontSize = 20 : headlineFontSize = o["HeadlineFontSize"];
if (undefined != o["direction"])
this.m_textDirection = o["direction"];
if (o.LargeUrl.Forecast is ArrayCollection)
items = ArrayCollection(o.LargeUrl.Forecast);
else
items = new ArrayCollection([o.LargeUrl.Forecast]);
widgetCount = this.m_computeWidgetSpace(items.length);
conditionsIconThemeLoader = new Loader();
conditionsIconThemeLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, function(e:Event):void
{
for(var i:uint = 0; i < widgetCount; i++)
{
var symbolClass:Class = e.currentTarget.loader.contentLoaderInfo.applicationDomain.currentDomain.getDefinition(int(items[i].condition)) as Class;
var symbolInstance:Sprite = new symbolClass();
item = new WeatherItem();
item.Show(items[i], headlineFontSize, symbolInstance, widgetCount);
_this.m_weatherWidgetContainer.addChild(item);
}
});
conditionsIconThemeLoader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, function(e:IOErrorEvent):void
{
Alert.show("Failure loading " + WidgetStylesheet.instance.Weather_Widget_Theme + ".swf");
});
// Attempt to load theme weather icon file
conditionsIconThemeLoader.load(new URLRequest("assets/animation/" + WidgetStylesheet.instance.Weather_Widget_Theme + ".swf"));
super.media.addChild(this.m_weatherWidgetContainer);
}
Heres the answer
public override function Show(o:ObjectProxy):void
{
var _this:Weather;
var _super:ContentItem;
var conditionsIconThemeLoader:Loader;
var loaderContext:LoaderContext;
this.m_weatherWidgetContainer = new HBox();
this.m_weatherWidgetContainer.percentHeight = 100;
this.m_weatherWidgetContainer.percentWidth = 100;
super.Show(o);
_this = this;
(undefined == o["HeadlineFontSize"]) ? this.m_headlineFontSize = 20 : this.m_headlineFontSize = o["HeadlineFontSize"];
if (undefined != o["direction"])
this.m_textDirection = o["direction"];
if (o.LargeUrl.Forecast is ArrayCollection)
this.m_items = o.LargeUrl.Forecast;
else
this.m_items = new ArrayCollection([o.LargeUrl.Forecast]);
conditionsIconThemeLoader = new Loader();
loaderContext = new LoaderContext(false, ApplicationDomain.currentDomain);
conditionsIconThemeLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, this.m_loaderSuccess);
conditionsIconThemeLoader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, this.m_loaderFail);
// Attempt to load theme weather icon file
conditionsIconThemeLoader.load(new URLRequest("assets/animation/" + WidgetStylesheet.instance.Weather_Widget_Theme + ".swf"), loaderContext);
this.m_weatherWidgetContainer.addEventListener(FlexEvent.CREATION_COMPLETE, this.m_drawHorizontalLine);
super.media.addChild(this.m_weatherWidgetContainer);
}

Resources