IsWebSocketRequest always false in azure - azure

I have published my websocket on azure and I have enabled the web socket feature in my web app but i keep getting IsWebSocketRequest false when i connect to my web socket, note that locally using localhost it is working normally
if (context.IsWebSocketRequest)
context.AcceptWebSocketRequest(new TestWebSocketHandler());
below is my web app configuration

I am not clear what cause your error.
You could refer to this sample.
I add IsWebSocketRequest in Get method, and run in local and on azure it works fine.
public HttpResponseMessage Get(string username)
{
HttpContext currentContext = HttpContext.Current;
if (currentContext.IsWebSocketRequest)
{
HttpContext.Current.AcceptWebSocketRequest(new ChatWebSocketHandler(username));
}
return Request.CreateResponse(HttpStatusCode.SwitchingProtocols);
}

Related

HttpClient 401 Unauthorized - How to authenticate IIS website to another IIS website

I have this well known 401 Unauthorized error. My scenario is that website A needs to call HTTP request (GET) to website B. Both websites runs on the same IIS server under different application pools (accounts). When I call HTTP request within the browser on my computer (that is connected to the windows domain) the HTTP request works and website B returns JSON data. But when that call is done by website A it seems that the information about the service account of website A is not added into the HTTP request and website B denies that request with 401. That leads to two questions
Why the IIS server does not recognize (authenticate/authorize) the website A account?
How can I add manually the account info into the HTTP request (using HTTP Client) so that I don't need to know username and password of the service account?
Currently my code looks like
namespace Infrastructure
{
public class FooService
{
private readonly HttpClient _httpClient;
public FooService(HttpClient httpClient)
{
_httpClient = httpClient;
_httpClient.BaseAddress = new Uri("https://domain/");
// Adding basic header does not work.
// var byteArray = Encoding.ASCII.GetBytes("user:passowrd");
// _httpClient.DefaultRequestHeaders.Authorization =
// new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
}
public async Task<FooServiceData> GetDataAsync() =>
await _httpClient.GetFromJsonAsync<FooServiceData>(
"foo/data");
}
public class FooServiceData
{
public string Url { get; set; }
public string Token { get; set; }
}
}
and the call that throws 401 is executed in controller action
var credentials = _fooService.GetDataAsync().Result;
Update:
When I connect to the website B via browser it does work. When I run ASP.NET MVC website project (on my development machine in Visual Studio) that sends HTTP request, it also does not work (401). The IIS setting (launchSetting.json) contains following
"iisSettings": {
"windowsAuthentication": true,
"anonymousAuthentication": false,
"iisExpress": {
"applicationUrl": "http://localhost:26978",
"sslPort": 44339
}
}
I thought that the Visual Studio is running under my account (and also the IIS service it runs in the background) but it seems that there are some changes in the Auth that prevent the website B to Auth me, any idea?
Update 2:
We tried to setup following property in the properties of the Website B service account but it didn't help.
I solved the issue with the following code on the caller side. Previously I registered the FooService as follows
services.AddHttpClient<FooService>();
but for Windows Authentication the credentials has to be specified
services.AddHttpClient<FooService>()
.ConfigurePrimaryHttpMessageHandler(x => new HttpClientHandler()
{
Credentials = CredentialCache.DefaultNetworkCredentials
});

Azure App Service cannot connect to Azure Redis when calling from Web Browser

I have a REST API services application that is using Asp.net core, and hosted on Azure App Service.
I am adding Azure Redis as a cache mechanism.
I tested the application on my local machine using local redis and it is working fine.
I deployed the Web service To Azure App Service, and test it.
When I try to test the services using Postman, it is working fine, and it is populating the cache, and reading from the cache.
But when I run the Front-end application which is a JavaScript Single Page Application that is calling the back-end services.
I am not querying Redis from the front-end. but from the backend .net application.
The calls to the services fail with this error
Timeout performing EVAL, inst: 1,
clientName: <.....>, serverEndpoint: Unspecified/my-redis.redis.cache.windows.net:6380,
keyHashSlot: 15126 (Please take a look at this article for some common client-side issues that can cause timeouts: http://stackexchange.github.io/StackExchange.Redis/Timeouts)
As I said, I am calling the same EndPoint (which is my App service), with the same parameters, from Postman, and it is working.
But from the browser, it is not working
This is my configuration and code:
In the Startup.cs
public void ConfigureServices(IServiceCollection services)
{
...
services.AddDistributedRedisCache(options => {
options.Configuration = Configuration.GetConnectionString("AzureCache");
options.InstanceName = "master";
});
}
And in the controller (ProductController)
using Microsoft.Extensions.Caching.Distributed;
public class ProductController: ControllerBase
{
IDistributedCache _cashe;
IDataRepository _repo;
public ProductController (IDistributedCache cache, IDataRepository repo)
{
_cache = cache;
_repo = repo;
}
[HttpGet]
public Async Task<IActionResult> GetProductions([FormBody] DataRequest request)
{
string data = _cache.GetString(request.AsKey());
if (data == null)
{
data = _repo.getData(request);
_cache.SetString(request.AsKey());
}
return Ok(data);
}
}
}
The client side code is as follows:
const request = axios.post('https://mydata.myserver.azure.com', reqBody, headers);
request.then(res => {
.... process the data
});
P.S: the error mentioned an article online.
I read the article and nothing jumped out. All my services are less than 5k in size except one, which is between 250k and 300k, and all calls are failing for me.
Error itself describing 'Please take a look at this article for some common client-side issues'. Could you share your client side code through which you are making call?

webapi to IoTHub not working from Azure deployment

was: "Iot Hub diagnostics azure deployed app"
Strange issue. I have a very simple 4.5.2 based webapi application that acts as a field gateway; that is each method connects to IoT Hub on behalf of the consumer which are actual devices capable of only posting to HTTP endpoints.
When I run the code from my local development machine everything works as expected and my IoT Hub receives the data. so, then, I published the webapi application to azure and ran the same methods but there is no activity to the IoT Hub detected at all. weird. I went so far as to debug the application code in azure and everything is working without error. There's no external configuration to mess things up at the moment, its all in the code.
Is there are logical explanation for this behavior?
I'm new to IoT Hub so maybe this is a simple thing. Where can I turn on verbose diagnostics? Since I have code that I believe to be working where can I see the next logical information? Are there permissions of some sort that may be preventing the data to pass through?
WebApi method(s) basically call this code which is contained in a separate assembly
public static void SendTempData(string Name, string value)
{
var telemetryDataPoint = new
{
deviceId = HOME_TEMP_DEVICE,
DeviceName = Name,
TValue = value
};
var messageString = JsonConvert.SerializeObject(telemetryDataPoint);
var task = Task.Run(() =>
{
deviceClient = DeviceClient.Create(iotHubUri, new DeviceAuthenticationWithRegistrySymmetricKey(HOME_TEMP_DEVICE, HOME_TEMP_DEVICE_KEY), TransportType.Mqtt);
var message = new Message(Encoding.ASCII.GetBytes(messageString));
deviceClient.SendEventAsync(message);
});
WaitForTask(ref task);
CheckForFail(task);
}
private static void WaitForTask(ref Task task)
{
while (task.Status != TaskStatus.RanToCompletion)
{
if ((task.IsCanceled) || (task.IsFaulted))
break;
System.Diagnostics.Debug.WriteLine("Thread ID: {0}, Status: {1}", Thread.CurrentThread.ManagedThreadId, task.Status);
}
}
Bottom line is I have no visibility. Is there some verbose setting I can enable to see why IoTHub never sees a connection or data?

signalR giving 403 when authenticated

I have a MVC app that uses signalR and Forms authentication and published to Azure Service - Was working fine with MVC4, SignalR 1.1.2
We upgraded to VS 2013 and the latest and greatest of all the packages, MVC 5.5.2 and signalR 2.1.2, and made the required changes for mapping SignalR via OWIN
Now when I am not logged in, signalR works as expected and connects using WebSockets. But when I do login and refresh the same page, signalR no longer works.
I get an 403 error on connecting via websockets
It then tries server sent events with comes back as (cancelled)
and then Long Polling also fails with a 403 - Forbidden error
Note that when running locally it works fine, it just when publish to azure service that I get this problem
I must be something simple I'm missing. Anybody done a similar upgrade?
Its a large app, so can't really share much code, but in essence all I'm doing is connecting to the signalR hub
<script type="text/javascript" src="/signalr/hubs"></script>
<script type="text/javascript">
$(function () {
// SignalR - Initialise
var dashboardHub = $.connection.miHub;
// start signalR hub - this will connect the user
$.connection.hub.start();
});
</script>
and hub class
public class MiHub : Hub
{
public override Task OnConnected()
{
ConnectUser();
return null;
}
....
}
When I am not logged in to my app, dev tools shows the following:
wss://myservice.cloudapp.net/signalr/connect?transport=webSockets&clientProtocol=1.4&connectionToken=...
response 101
wss://myservice.cloudapp.net/signalr/connect?transport=webSockets&clientProtocol=1.4&connectionToken=...
response 200
{ "Response": "started" }
When I logged in and hit F5 on the same page I get
wss://myservice.cloudapp.net/signalr/connect?transport=webSockets&clientProtocol=1.4&connectionToken=...
response 403

How do I get Azure to let my WebAPI controller return 404?

I have a WebAPI controller that returns an empty 404 response when an entity isn't found, and a 200 when it is. This works fine when running in my local DevFabric, but when deployed I get a 500 instead of a 404. The 200 use case works in both environments.
public IHttpActionResult Get(int id)
{
var result = getEntity(id);
if (result == null)
{
return NotFound();
}
return Ok(result);
}
Why am I not getting my 404 when deployed to Azure?
With the level of information you provided I can suggest yo to remote debug your application from Azure Webrole - http://antirandom.com/2012/09/20/remotely-debugging-a-windows-azure-webrole-via-visual-studio-debugger/
To my understanding 500 is your Web API internal server server. So debugging would help you to find out. Also you can enable Azure Web Role Logging - http://msdn.microsoft.com/en-us/library/windowsazure/dn186185.aspx

Resources