Web Socket are not available on signalr core? - c#

I am working on signalr core under asp.net core 2.2.I have mobile as well as
web signalr core clients,I have maintained cross domain connection.My web client
successgully connnected to signalr core, but my android client gives exception below,
"Web sockets are not available on your server",
hence , web client is also using web sockets transport layer, and it is in conencting state.
my server side code is in start up class
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.AddCors(options =>
{
options.AddPolicy("CorsPolicy",
builder => builder.SetIsOriginAllowed((host) => true)/*WithOrigins("https://localhost:44381")*/
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials());
});
services.AddSignalR();
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
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.UseCors("CorsPolicy");
app.UseSignalR(routes =>
{
routes.MapHub<ChatHub>("/chatHub");
});
app.UseMvc();
}
Please , answer me, how i connect android signalr Client to signalr core serever?

You need to enable WebSockets support on your Server.
To enable WebSockets on Windows Server 2012 or later :
Use the Add Roles and Features wizard from the Manage menu or the link in Server Manager.
Select Role-based or Feature-based Installation. Select Next.
Select the appropriate server (the local server is selected by default). Select Next.
Expand Web Server (IIS) in the Roles tree, expand Web Server, and then expand Application Development.
Select WebSocket Protocol. Select Next.
If additional features aren't needed, select Next.
Select Install.
When the installation completes, select Close to exit the wizard.

Related

Blazor Server with Microsoft Identity in IIS with virtual application

I've created a Blazor Server project using the standard Visual Studio 2022 template with authentication set to Microsoft Identity. It works locally without issue.
When I try to deploy it to the default website on an IIS server in a virtual application, it gives the following error:
Program.cs:
var builder = WebApplication.CreateBuilder(args);
var initialScopes = builder.Configuration["DownstreamApi:Scopes"]?.Split(' ') ??
builder.Configuration["MicrosoftGraph:Scopes"]?.Split(' ');
builder.Services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
.AddMicrosoftIdentityWebApp(builder.Configuration.GetSection("AzureAd"))
.EnableTokenAcquisitionToCallDownstreamApi(initialScopes)
.AddMicrosoftGraph(builder.Configuration.GetSection("MicrosoftGraph"))
.AddInMemoryTokenCaches();
builder.Services.AddControllersWithViews()
.AddMicrosoftIdentityUI();
builder.Services.AddAuthorization(options =>
{
// By default, all incoming requests will be authorized according to the default policy
options.FallbackPolicy = options.DefaultPolicy;
});
builder.Services.AddRazorPages();
builder.Services.AddServerSideBlazor()
.AddMicrosoftIdentityConsentHandler();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.MapBlazorHub();
app.MapFallbackToPage("/_Host");
app.Run();
I think it is an issue with the return url, because the virtual application name is added to the address automatically. I have this url included in my app registration, but it still doesn't work.
I think after you see the error message page above, you may try to visit http://localhost or maybe you change the default home page url so http://localhost/the_word_you_covered and see if the user already signed in successfully.
I created a new Blazor server application with Microsoft Identity, then I fill the appsettings.json with tenant id, client id, and leave the CallbackPath as /signin-oidc by default. And in AAD, set redirect URL as https://localhost/signin-oidc. It worked well when test locally. After published to IIS, the sign in didn't work well so I comment the
builder.Services.AddAuthorization(options =>
{
// By default, all incoming requests will be authorized according to the default policy
options.FallbackPolicy = options.DefaultPolicy;
});
and content in the so that I can see more error issue.
if (!app.Environment.IsDevelopment()) { }
But after doing these steps, everything worked well except the sign in redirect back to http://localhost/signin-oidc. Pls note here we need to set the redirect URL as http in Azure AD portal because IIS uses HTTP by default. But since there's no page routing to signin-oidc.
=========================================
If what I said above is not the issue, I'm afraid you can create a self-signed certificate and bind it to the default website, then visiting https instead. Just now I tried again and it keep showing 500 error like screenshot below. Then I create self-signed certificate to use https then solved the 500 error.

Asp.Net Core MVC with Windows Authentication on IIS

I have an ASP.NET Core MVC application with Windows Authentication. I published it on IIS server in local network of our company. All works fine, all users log in with their rights. But each time when they open a browser they need to enter their credentials. Each time we see a window for entering the user name and password. How to make a logon automatic?
I added this strings to Startup.cs
public void ConfigureServices(IServiceCollection services)
{
…
services.AddAuthentication(IISDefaults.AuthenticationScheme);
//custom authorization
services.AddAuthorization(options =>
{
options.AddPolicy("Operator", policy => policy.AddRequirements(new CheckADGroupRequirement(Configuration["RolesConfig:Operator"], Configuration["RolesConfig:Manager"])));
options.AddPolicy("Manager", policy => policy.AddRequirements(new CheckADGroupRequirement(Configuration["RolesConfig:Manager"])));
});
services.AddSingleton<IAuthorizationHandler, CheckADGroupHandler>();
//custom authorization
…
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
…
app.UseAuthentication();
…
}
In IIS I set to Enabled only Windows Authentication
The only solution I found it was set Automatic logon in Internet Options but I think it’s bad practice.

Azure AD SSO: .Net Core 2.1 Single Sign On Based On Organization's Office 365 Username&Password

I have created an ASP.NET Core 2.1 MVC web application and I have used a simple login form to authenticate the users. Now We have decided to remove the login form and use a single sign-on option with my Organization's Office 365 user credentials or my office’s outlook username & password and followed the following Microsoft website but I could not choose the right SSO one.
This web app is a MVP (minimum viable product) project so we just don't want to use our own authentication & authorization process and only my organization people going to use this app so we have decided to use the Organization's Azure AD SSO. I am not using SAML or WS-Federation protocols in my web app but I just wanted to implement the SSO for my project.
I searched many sites on the internet, a few websites explained "No code is required to configure SSO but only Azure AD configurations" and some other websites explained with some piece of code also. So now I am totally confused that how should I achieve the SSO for my simple web application.
Hosted environment: Azure App Service
Application users: only organization users (internal web app)
My Startup.cs code:
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.
public void ConfigureServices(IServiceCollection services)
{
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.AddSession(options =>
{
options.Cookie.IsEssential = true;
});
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
//Fetching Connection string from APPSETTINGS.JSON
var ConnectionString = Configuration.GetConnectionString("MbkDbConstr");
//Entity Framework
services.AddDbContext<ShardingDbContext>(options => options.UseSqlServer(ConnectionString));
//Automapper Configuration
AutoMapperConfiguration.Configure();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseSession();
app.UseAuthentication();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller:required}/{action}/{id?}",
defaults: new { controller = "UserAccount", action = "UserLogin" });
});
}
}
Note: I have configured the app.UseAuthentication() & other functions but authentication part not used inside my projects.
If you want to Authenticate your users with App Services, refer the document to see how to enable AAD Authentication in app services.
Generally for any web application, you can configure App Registration in Azure AD. You can configure claim attribute as well in order to use SSO feature. Refer the document for how to configure app registration in Azure AD.

Asp Net Core authentication troubles

I have made asp net core web app with Angular. It is using authentication based on cookies using standard net core authentication mechanism. All is working fine until IIS restart (recycle). After application restarted all users becomes unauthenticated and needs to relogin.
May be some one knows what should be done to make information stored in cookies be actual for several days and not depending on application restart.
This is the piece of code
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<MyAppContext>(options => options.UseMySql(connectionString));
services.AddIdentity<ApplicationUser, ApplicationRole>(options =>
{
options.User.RequireUniqueEmail = true;
options.SignIn.RequireConfirmedEmail = true;
})
.AddEntityFrameworkStores<MyAppContext>()
.AddDefaultTokenProviders();
services.AddAuthorization();
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(options =>
{
options.SlidingExpiration = true;
options.ExpireTimeSpan = System.TimeSpan.FromDays(7);
options.LoginPath = $"/Identity/Login";
options.LogoutPath = $"/Identity/Logout";
options.Cookie.IsEssential = true;
});
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory)
{
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseSpaStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
}
Asp.Net Core uses the Data Protection mechanism to generate temporary encryption keys. and with the restart of the server or IIS, these keys are lost and re-generated.
In order that the keys for encrypting web application information are stored permanently and not lost with the server restart you can go to Application pool setting in IIS and set Load user profile to True
In this case, the keys will be permanently stored in the user's profile folder for the application's application pool, encrypted by the Windows DPAPI mechanism.
Or you can check these links 1,2 to keep the login status after iis reset

AspNetCore Web Api Microsoft Account Authentication

My basic requirement is a Web Api that exposes some REST resources. Authentication is required to access any resource, and I want that to happen via Microsoft Accounts. This is to be a web api for programmatic access.
I started along this path: https://learn.microsoft.com/en-us/aspnet/core/security/authentication/social/microsoft-logins?view=aspnetcore-2.2
And have got to the end. It probably works fine except I get this:
InvalidOperationException: The default Identity UI layout requires a partial view '_LoginPartial' usually located at '/Pages/_LoginPartial' or at '/Views/Shared/_LoginPartial' to work.
But I don't want a UI with a sign in experience. I want apps (and users from clients such as browsers) to authenticate via Microsoft and then access my REST resources.
My configure services looks like this:
services.AddIdentity<IdentityUser, IdentityRole>()
.AddDefaultTokenProviders()
//.AddDefaultUI(UIFramework.Bootstrap4)
.AddEntityFrameworkStores<IdentityDbContext>();
services.AddAuthentication().AddMicrosoftAccount(microsoftOptions =>
{
microsoftOptions.ClientId = _config["Authentication:Microsoft:ApplicationId"];
microsoftOptions.ClientSecret = _config["Authentication:Microsoft:Password"];
});
And then:
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseStaticFiles();
app.UseAuthentication();
Program just does:
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.UseUrls("http://localhost:5000", "https://localhost:5001");
You have implemented the Microsoft Authentication AND the login process in the same application, this kind of solution produce a cookie for the ASP.NET.
You probably want clients to authenticate, via OAuth, passing a Bearer Token.
In this case you must use a JwtBearer token authentication.
In this scenario your application DO NOT provide a UI for the authentication (like the example), instead ONLY validate/authenticate the token received.
Here some references
jwt auth in asp.net core
jwt validation
token authenticationin Asp.NET
Authentication in ASP.NET Core JWT

Categories