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.
Related
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.
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
I have a custom AuthorizationHandler in my Asp.Net Core API project which authorizes requests based on Tokens been passed in the Headers.
The Handler works fine as in it invoked on runtime however am getting the following error
InvalidOperationException: No authenticationScheme was specified, and there was no
DefaultChallengeScheme found.
I have registered my settings in Startup.cs as follows:
public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication(IISDefaults.AuthenticationScheme);
services.AddSingleton<IAuthorizationHandler, TokenAuthorizationHandler>();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseAuthentication();
app.UseMvc();
}
Any suggestions?
The default properties of the project is enable Anonymous Authentication and disable Windows Authentication .
If you want to choose IIS default authentication as your authenticationScheme , you need to modify the project's properties to enable Windows Authentication and disable Anonymous Authentication :
Right-click the project in Solution Explorer and select Properties.
Select the Debug tab.
Clear the check box for Enable Anonymous Authentication.
Select the check box for Enable Windows Authentication.
Save and close the property page.
Reference : https://learn.microsoft.com/en-us/aspnet/core/security/authentication/windowsauth?view=aspnetcore-2.2&tabs=visual-studio#iisiis-express
Or you could add others authenticationSchemes (cookie-based authentication , JWT bearer authentication etc) , refer to Authorize with a specific scheme in ASP.NET Core for more details .
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.
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