SignalR Core, error: The 'Sec-WebSocket-Accept' header value 'u1mOHwcpjPm7txGcxCm1jVmOgjo=' is invalid - asp.net-core

I'm trying to implement SignalR Core in a .Net core 2.0 Web app, and implement client side in a Xamarin.Android application.
I created a fresh .Net core 2.0 Web app solution and imported Microsoft.AspNetCore.SignalR and setup the Startup.cs file like in this sample
https://github.com/aspnet/SignalR-samples/blob/master/ChatSample/ChatSample/Startup.cs
My code:
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddSignalR();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseFileServer();
app.UseSignalR(routes =>
{
routes.MapHub<ChatHub>("chat");
});
}
}
This project is deployed to Amazon Elastic Bean Stalk.
On the client side, I have imported Microsoft.AspNetCore.SignalR.Client and I initialize a connection like in this sample
https://github.com/aspnet/SignalR-samples/blob/master/XamarinAndroidChatClient/XamarinAndroidChatClient/MainActivity.cs
My code:
public async override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
hubConnection = new HubConnectionBuilder()
.WithUrl("http://*******.eu-central-1.elasticbeanstalk.com/chat")
.Build();
try
{
await hubConnection.StartAsync();
}
catch(Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.StackTrace);
}
}
But .StartAsync() throws this exception:
{System.Net.WebSockets.WebSocketException (0x80004005): The 'Sec-WebSocket-Accept' header value 'LNqQiPhES/zOwW10TMji4AVvvoA=' is invalid.
at System.Net.WebSockets.WebSocketHandle.ValidateAndTrackHeader (System.String targetHeaderName, System.String targetHeaderValue, System.String foundHeaderName, System.String foundHeaderValue, System.Boolean& foundHeader) [0x0002c] in <6c708cf596db438ebfc6b7e012659eee>:0 `
I found this post which was related to Amazon ELB and setting up websockets
(Elastic Beanstalk stripping Sec-WebSocket-Accept header)
Also found this post with same problem
(https://forums.aws.amazon.com/thread.jspa?messageID=613220)
As in this post, things are working fine if I choose "LongPolling" as transport
hubConnection = new HubConnectionBuilder()
.WithUrl("http://*******.eu-central-1.elasticbeanstalk.com/chat")
.WithTransport(TransportType.LongPolling)
.Build();
This guy was suggested to switch LoadBalancer listeners from HTTP to TCP, I tried this, but issue is still remaining
Also I read a suggestion to install websockets in ISS on AWS Management Console, but I can't find this option anywhere?
Any kind of help or suggestions are appreciated

You'll need to log onto the Elastic BeanStalk server and enable the Websocket Protocol on in the server roles in Server Manager, this fixed it for me.

Related

How to resolve Request to Long error in Asp.Net Core Azure B2C Configuraiton?

I am new to Asp.Net Core identity.
I have configured the startup as per below. When I run the code in a normal and incognito browser I get the below error.
I have cleared cookies as previous questions have suggested. What is interesting is a high number of cookies get created when loading the sign screen.
My issue is similar to those described in the below old articles. Both solutions seem outdated.
https://www.javaer101.com/en/article/18781756.html
https://blog.bitscry.com/2018/09/19/azure-ad-request-too-long/
using d365fl.DocumentGenerator.blazor_frontend.Data;
using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc.Authorization;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Identity.Web;
using Microsoft.IdentityModel.Logging;
namespace d365fl.DocumentGenerator.blazor_frontend
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
ConfigureIdentiy(services);
services.AddRazorPages();
services.AddServerSideBlazor();
services.AddSingleton<WeatherForecastService>();
}
private void ConfigureIdentiy(IServiceCollection services)
{
services.AddMicrosoftIdentityWebAppAuthentication(Configuration, "AzureAdB2C");
services.AddControllersWithViews(options =>
{
var policy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build();
options.Filters.Add(new AuthorizeFilter(policy));
});
services.Configure<OpenIdConnectOptions>(Configuration.GetSection("AzureAdB2C"));
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
IdentityModelEventSource.ShowPII = true;
}
else
{
app.UseExceptionHandler("/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
endpoints.MapBlazorHub();
endpoints.MapFallbackToPage("/_Host");
});
}
}
}
EDIT 1 - HTTP Request from Developer Toolbar
EDIT 2 - Screen Shot of Cookie data from Developer Toolbar / Network Tab
As we discussed in the comment, the issue is cause by too many cookies.
Please clear your cookies and modify your code to avoid endless loops and back and forth requests.
See this answer for more details.

How to configure an external SOAP service in a net core 2.2 project

I have a project developed in .net core 2.2.
You need to use a WCF in .Net Framework.
The inclusion of WCF and Reference.cs went well. The service is Ok, as a connected service.
However I am getting a dependency injection error:
microsoft.extensions.dependencyinjection.servicelookup.callsite factory.create argument callsite(type servicetype, type implementationtype, callsitechain callsitechain, parameterinfo[] parameters, bool throwifcallsitenotfound)
Performing searches on the internet, some answers were related to the configuration of Startup.cs and Program.cs:
public void ConfigureServices(IServiceCollection services)
{
services
.AddMvc()
.SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
.AddSessionStateTempDataProvider()
.AddJsonOptions(options =>
{
options.SerializerSettings.ContractResolver = this.GetJsonSerializerContractResolver();
options.SerializerSettings.DateFormatString = this.GetJsonSerializerDateFormatString();
});
this.ConfigureIoC(services);
}
private void ConfigureIoC(IServiceCollection services)
{
this.ConfigureHelpers(services);
this.ConfigureUnitOfWorks(services);
this.ConfigureFacades(services);
this.ConfigureBusinessServices(services);
this.ConfigureServiceFilters(services);
this.ConfigureRestConsumers(services);
}
private void ConfigureHelpers(IServiceCollection services)
{
services.AddScoped(typeof(IHpUrl), typeof(HpUrl));
services.AddScoped(typeof(IHpArvoreProduto), typeof(HpArvoreProduto));
}
My doubt is whether I would need only one method:
private void ConfigureSoaps(IServiceCollection services)
{
services.AddScoped(typeof(ISoapBla), typeof(SoapBla));
}
Since in some responses from the Web, the use of SoapCore among other solutions has been suggested.

asp.net core hosted service sleeps after api inactivity

I have a hosted service that checks an email account every minute. I also am using MVC with Web API 2.1. In order to get my hosted service to start, I have to "wake it up" by calling API methods. After a period of inactivity from the Web API the hosted service goes to sleep and stops checking the email. It's like it is getting garbage collected. How do I get it to run continuously?
Assistance will be greatly appreciated.
Startup.cs:
public void ConfigureServices(IServiceCollection services)
{
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new Info {Title = "CAS API", Version = "v1"});
// Set the comments path for the Swagger JSON and UI.
var xmlFile = $"{Assembly.GetEntryAssembly().GetName().Name}.xml";
var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
c.IncludeXmlComments(xmlPath);
})
.AddCors(options =>
{
options.AddPolicy("CorsPolicy",
builder => builder.WithOrigins(Configuration["uiOrigin"])
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials());
})
.AddHostedService<EmailReceiverHostedService>()
.Configure<EmailSettings>(Configuration.GetSection("IncomingMailSettings"))
.AddSingleton<IEmailProcessor, MailKitProcessor>()
.AddSingleton<IEmailRepository, EmailRepository>()
...
EmailReceiverHostedService.cs:
using CasEmailProcessor.Options;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using System;
using System.Threading;
using System.Threading.Tasks;
public class EmailReceiverHostedService : IHostedService, IDisposable
{
private readonly ILogger _logger;
private readonly Timer _timer;
private readonly IEmailProcessor _processor;
private readonly EmailSettings _emailConfig;
public EmailReceiverHostedService(ILoggerFactory loggerFactory,
IOptions<EmailSettings> settings,
IEmailProcessor emailProcessor)
{
_logger = loggerFactory.CreateLogger("EmailReceiverHostedService");
_processor = emailProcessor;
_emailConfig = settings.Value;
_timer = new Timer(DoWork, null, Timeout.Infinite, Timeout.Infinite);
}
public Task StartAsync(CancellationToken cancellationToken)
{
_logger.LogInformation("Timed Background Service is starting.");
StartTimer();
return Task.CompletedTask;
}
public Task StopAsync(CancellationToken cancellationToken)
{
_logger.LogInformation("Timed Background Service is stopping.");
StopTimer();
return Task.CompletedTask;
}
public void Dispose()
{
_timer?.Dispose();
}
private void StopTimer()
{
_timer?.Change(Timeout.Infinite, 0);
}
private void StartTimer() { _timer.Change(TimeSpan.FromSeconds(_emailConfig.TimerIntervalInSeconds), TimeSpan.FromSeconds(_emailConfig.TimerIntervalInSeconds)); }
private void DoWork(object state)
{
StopTimer();
_processor.Process();
StartTimer();
}
}
As you have thought, the root cause is your host can be shut down because of app pool recycle when hosting in IIS. This has been pointed below:
It is important to note that the way you deploy your ASP.NET Core WebHost or .NET Core Host might impact the final solution. For instance, if you deploy your WebHost on IIS or a regular Azure App Service, your host can be shut down because of app pool recycles.
Deployment considerations and takeaways
For a possible workaround, you could try set idle timeout to zero to disable default recycle.
Due to IIS defualt recycle, you may consider the different hosting approcahes:
Use a Windows Service
Use a Docker Container (Windows Container), but for that, you’d need Windows Server 2016 or later.
Use Azure Functions
For your scenario, you could try Host ASP.NET Core in a Windows Service
I create task on Windows Event Scheduler to access an URL to wakeup the service.
powershell.exe -command {Invoke-WebRequest http://localhost:8080}

IdentityServer 4: No storage mechanism for grants specified - use AddInMemoryStores

I am using Identity Server 4 , ASP.NET Core and trying to replace the IdentityServer developer in Production environment. But getting the following error:
No storage mechanism for grants specified. Use the 'AddInMemoryStores' extension method to register a development version.
So, I tried to implement the services as mentioned in this answer:
IProfileService
IResourceOwnerPasswordValidator
This is my ConfigureServices Method in Startup class:
services.AddMvc();
var identityBuilder = services.AddIdentityServer();
identityBuilder.AddInMemoryScopes(identitySrvConfig.GetScopes());
identityBuilder.AddInMemoryClients(identitySrvConfig.GetClients());
identityBuilder.AddProfileService<ProfileService>();
identityBuilder.Services.AddTransient<IResourceOwnerPasswordValidator, ResourceOwnerPasswordValidator>();
Taking into consideration that in my case the interface signature is different:
public class ResourceOwnerPasswordValidator : IdentityServer4.Validation.IResourceOwnerPasswordValidator
{
public Task ValidateAsync(ResourceOwnerPasswordValidationContext context)
{
throw new NotImplementedException();
}
}
But I am still getting the same error, what is the problem?
If you are applying custom Identity i.e
services.AddIdentity<AppUser, UserRole>(options => { options.User.RequireUniqueEmail = true; }).AddEntityFrameworkStores<AbcDbContext>();
then in
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
Comment
app.UseIdentityServer();
because we are using custom identity, not default
They were/are reworking those APIs. You should use AddInMemoryPersistedGrants

No authentication handler is configured to handle the scheme: Microsoft.AspNet.Identity.Application

I am using ASP.NET Core with ASP.NET Identity and have the following:
User user = await _userManager.FindByEmailAsync(myEmail);
SignInResult result = await _signInManager.PasswordSignInAsync(user, myPassword, true, false);
I get a user but when I try to sign in the user I get the error:
[Error] An unhandled exception has occurred while executing the request
System.InvalidOperationException: No authentication handler is configured to handle the scheme: Microsoft.AspNet.Identity.Application
On web project Startup file I have:
public void Configure(IApplicationBuilder applicationBuilder, IHostingEnvironment hostingEnvironment, ILoggerFactory loggerFactory) {
// Other configuration code lines
applicationBuilder.UseIISPlatformHandler(options => options.AuthenticationDescriptions.Clear());
applicationBuilder.UseIdentity();
} // Configure
public void ConfigureServices(IServiceCollection services) {
// Other configuration code lines
services
.AddIdentity<User, Role>()
.AddEntityFrameworkStores<Context, Int32>()
.AddDefaultTokenProviders();
}
I have no idea what is wrong. I tried to change the configuration and I always get the same error ...
Any idea?
applicationBuilder.UseIdentity();
is what should configure the cookie middleware, make sure that line is called before calling
applicationBuilder.UseMvc()
authentication must be configured before mvc