From 82635f20c91d3a0bec3f48c37b16bd9bdd002dd3 Mon Sep 17 00:00:00 2001 From: Kyle Spearrin Date: Sat, 21 Oct 2017 21:48:11 -0400 Subject: [PATCH] manually handle redirects for android blocks --- src/Icons/Controllers/IconsController.cs | 33 +++++++++++++++++++++++- 1 file changed, 32 insertions(+), 1 deletion(-) diff --git a/src/Icons/Controllers/IconsController.cs b/src/Icons/Controllers/IconsController.cs index ab192450f7..c5d1dcf197 100644 --- a/src/Icons/Controllers/IconsController.cs +++ b/src/Icons/Controllers/IconsController.cs @@ -1,4 +1,6 @@ using System; +using System.Linq; +using System.Net; using System.Net.Http; using System.Threading.Tasks; using Bit.Icons.Models; @@ -11,7 +13,10 @@ namespace Bit.Icons.Controllers [Route("")] public class IconsController : Controller { - private static readonly HttpClient _httpClient = new HttpClient(); + private static readonly HttpClient _httpClient = new HttpClient(new HttpClientHandler + { + AllowAutoRedirect = false + }); private readonly IMemoryCache _memoryCache; private readonly IDomainMappingService _domainMappingService; private readonly IconsSettings _iconsSettings; @@ -47,6 +52,32 @@ namespace Bit.Icons.Controllers var iconUrl = $"{_iconsSettings.BestIconBaseUrl}/icon?url={mappedDomain}&size=16..24..32" + $"&fallback_icon_url=https://raw.githubusercontent.com/bitwarden/web/master/src/images/fa-globe.png"; var response = await _httpClient.GetAsync(iconUrl); + + if(response.StatusCode == HttpStatusCode.Redirect && response.Headers.Contains("Location")) + { + var locationHeader = response.Headers.GetValues("Location").FirstOrDefault(); + if(!string.IsNullOrWhiteSpace(locationHeader) && + Uri.TryCreate(locationHeader, UriKind.Absolute, out Uri location)) + { + var message = new HttpRequestMessage + { + RequestUri = location, + Method = HttpMethod.Get + }; + + // Let's add some headers to look like we're coming from a web browser request. Some websites + // will block our request without these. + message.Headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) " + + "AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36"); + message.Headers.Add("Accept-Language", "en-US,en;q=0.8"); + message.Headers.Add("Cache-Control", "no-cache"); + message.Headers.Add("Pragma", "no-cache"); + message.Headers.Add("Accept", "image/webp,image/apng,image/*,*/*;q=0.8"); + + response = await _httpClient.SendAsync(message); + } + } + if(!response.IsSuccessStatusCode) { return new NotFoundResult();