I've got a .net Core 2.1 MVC application that hosts an Angular 6 application. I am using Visual Studio 2017 15.7.3. I'm trying to set up Windows Authentication but am having issues. I've followed the documentation and my Program.cs and Startup.cs are below:
Program.cs:
using Microsoft.AspNetCore.Server.HttpSys;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Logging;
using NLog.Web;
using System;
namespace CoreIV_Admin_Core
{
public class Program
{
public static void Main(string[] args)
{
var logger = NLog.Web.NLogBuilder.ConfigureNLog("nlog.config").GetCurrentClassLogger();
try
{
logger.Debug("init main");
CreateWebHostBuilder(args).Build().Run();
}
catch (Exception ex)
{
//NLog: catch setup errors
logger.Error(ex, "Stopped program because of exception");
throw;
}
finally
{
// Ensure to flush and stop internal timers/threads before application-exit (Avoid segmentation fault on Linux)
NLog.LogManager.Shutdown();
}
}
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
//.UseHttpSys(options =>
//{
// options.Authentication.Schemes = AuthenticationSchemes.NTLM | AuthenticationSchemes.Negotiate;
// options.Authentication.AllowAnonymous = false;
//})
.ConfigureLogging(logging =>
{
logging.ClearProviders();
logging.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Information);
})
.UseNLog(); // NLog: setup NLog for Dependency injection
}
}
Startup.cs:
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Server.HttpSys;
using Microsoft.AspNetCore.SpaServices.Webpack;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
namespace CoreIV_Admin_Core
{
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.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();
services.AddAuthentication(HttpSysDefaults.AuthenticationScheme);
services.AddMvc()
.SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}
// 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();
app.UseWebpackDevMiddleware(new WebpackDevMiddlewareOptions
{
HotModuleReplacement = true
});
}
else
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseHttpContext();
app.UseAuthentication();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
routes.MapSpaFallbackRoute(
name: "spa-fallback",
defaults: new
{
controller = "Home",
action = "Index"
});
});
}
}
}
If I uncomment the .UseHttpSys section in program.cs and press play in Visual Studio to debug, it almost immediately stops the debug session and the following error is in the Event log:
"Application 'MACHINE/WEBROOT/APPHOST/myapp' with physical root
'C:\Users\me\myapp' created process with commandline 'C:\Program Files
(x86)\Microsoft Visual
Studio\2017\Professional\Common7\IDE\Extensions\Microsoft\Web
Tools\ProjectSystem\VSIISExeLauncher.exe -argFile
"C:\Users\me\AppData\Local\Temp\tmpFCA6.tmp"' but failed to listen on
the given port '28353'".
If I try with .UseHttpSys commented out, the debugging works but I am unable to be properly authenticated.
Camilo thanks for your comment, it helped point me in the right direction. I removed the UseHttpSys section from program.cs and added .UseIISIntegration(). I also changed services.AddAuthentication(HttpSysDefaults.AuthenticationScheme) to services.AddAuthentication(IISDefaults.AuthenticationScheme) in my startup.cs. I then ticked Enable Windows Authentication in the Debug section of the project properties and chose "IIS Express" for the Launch and it all worked. I'm new to .net core with windows authentication so I don't know if I got it all set up exactly correct but it works and hopefully, this post helps point others in the right direction.
Related
I am running Visual Studio 2019. I have an angular app that works completely fine when Electron is not running. For example, If I choose IIS Express from the debug list, all works well (ApiControllers run correctly and return data):
However, if I run with Electron.Net App, the site loads and shows the page, but my ApiControllers are not contactable. The following error appears:
Here is my Startup.cs
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public IServiceProvider serviceProvider { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
// In production, the Angular files will be served from this directory
services.AddSpaStaticFiles(configuration =>
{
configuration.RootPath = "ClientApp/dist";
});
// Registers a few services with their interfaces
IOCContainer iocContainer = new IOCContainer();
iocContainer.ConfigureServices(services);
//
// Is this needed?
services.AddCors(options =>
options.AddPolicy("DefaultCorsPolicy", builder => builder
.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod()));
// This is very important for some of the services I register in the iocContainer
services.AddHttpClient();
}
// 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();
}
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();
if (!env.IsDevelopment())
{
app.UseSpaStaticFiles();
}
app.UseRouting();
app.UseCors();
//app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
//endpoints.MapControllerRoute(
// name: "api",
// pattern: "api/{controller}/{action}");
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller}/{action=Index}/{id?}");
});
app.UseSpa(spa =>
{
// To learn more about options for serving an Angular SPA from ASP.NET Core,
// see https://go.microsoft.com/fwlink/?linkid=864501
spa.Options.SourcePath = "ClientApp";
if (env.IsDevelopment())
{
spa.UseAngularCliServer(npmScript: "start");
}
});
ElectronBootstrap();
}
public async void ElectronBootstrap()
{
BrowserWindowOptions options = new BrowserWindowOptions
{
Show = false,
//WebPreferences = new WebPreferences() {
// AllowRunningInsecureContent = true,
// ContextIsolation = false
//}
};
BrowserWindow mainWindow = await Electron.WindowManager.CreateWindowAsync();
mainWindow.OnReadyToShow += () =>
{
mainWindow.Show();
};
mainWindow.SetTitle("App Name here");
mainWindow.WebContents.OpenDevTools();
MenuItem[] menu = new MenuItem[]
{
new MenuItem
{
Label = "File",
Submenu=new MenuItem[]
{
new MenuItem
{
Label ="Exit",
Click =()=>{Electron.App.Exit();}
}
}
},
new MenuItem
{
Label = "Info",
Click = async ()=>
{
await Electron.Dialog.ShowMessageBoxAsync("Welcome to App");
}
}
};
Electron.Menu.SetApplicationMenu(menu);
}
}
and here is my Program.cs
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
webBuilder.UseElectron(args);
//webBuilder.UseSetting("https_port", "8080");
});
//public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
// WebHost.CreateDefaultBuilder(args)
//.UseStartup<Startup>()
//
}
Any thoughts on what I might be doing wrong? I assume the IIS server is not running, but that would defy the point of having a self contained desktop application running on Electron. What options do I have?
My goal:
To have a self contained desktop application that others can use.
It will read and write files from local file system.
It will make requests out to APIs
It will have an Angular front end and a C# back end.
Additional info:
This may be relevant:
Be careful with the default application set up in Visual Studio for Angular apps.
There is a "getBaseUrl" constant in the Angular/Typescript code module. If you use it in injection of your services, it will always route you through the full URL which may or may not be correct after packaging up your application. Instead, you can blank it out or simply not use it.
I create applications for internal use,
trying to get user login through IHttpContextAccessor
Controller:
private Microsoft.AspNetCore.Http.IHttpContextAccessor _httpContextAccessor;
var userName = _httpContextAccessor.HttpContext.User.Identity.Name;
//var userName = #"ad\LOGINUSER";
if I extract username using _httpContextAccessor.HttpContext.User.Identity.Name; mam błąd na stronie
Error.
An error occurred while processing your request.
Request ID: |77762974-42ec74070b648c99.
Development Mode
Swapping to Development environment will display more detailed information about the error that occurred.
if I use var userName = #"ad\LOGINUSER"; everything works normally
of course, the error is after publishing, everything works fine in normal compilation on computer
I'm using .net core 3.1
My startup code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using AppEcp.Models;
using Microsoft.EntityFrameworkCore;
using Newtonsoft.Json.Serialization;
using Microsoft.AspNetCore.Server.IISIntegration;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.AspNetCore.Mvc.Infrastructure;
namespace AppEcp
{
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
.AddMvc();
services
.AddHttpContextAccessor();
// services
// .TryAddSingleton<IActionContextAccessor, ActionContextAccessor>();
services
.AddAuthentication(IISDefaults.AuthenticationScheme);
services
.AddControllersWithViews()
.AddJsonOptions(options => options.JsonSerializerOptions.PropertyNamingPolicy = null);
// .AddJsonOptions(options => options.SerializerSettings.ContractResolver = new DefaultContractResolver());
services.AddCors(c =>
{
c.AddPolicy("AllowOrigin", options => options.AllowAnyOrigin());
});
var connectionAd = #"Server=wsql3;Database=ActiveDirectory;Trusted_Connection=True;MultipleActiveResultSets=true";
services.AddDbContext<UzytkownicyDbContext>(options => options.UseSqlServer(connectionAd));
var connectionUrlop = #"Server=wsql3;Database=ECP;Trusted_Connection=True;MultipleActiveResultSets=true";
services.AddDbContext<EcpDbContext>(options => options.UseSqlServer(connectionUrlop));
}
// 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();
// app.UseDatabaseErrorPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
// app.UseHsts();
}
// app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Ewidencja}/{id?}");
});
}
}
}
does anyone know what i have done wrong?
You didn't enable Authentication by UseAuthentication:
app.UseAuthentication(); // add this line
app.UseAuthorization();
Within a Controller, you don't have to access HttpContext by _httpContextAccessor.HttpContext...., you can get the User by HttpContext.User.
Also, it's your duty to check whether the User is null :
var user = HttpContext.User;
if(user ==null)
{
...
}else{
var userName = user.Identity.Name;
...
}
Finally, if above changes doesn't fix the problem, could you please show us the logs?
I get an error of "Ambiguity between 'Startup.Configuration' and 'Startup.Configuration'" on my startup class. I don't know what I have done to cause this issue. All I did was create a DBContext class and this error occured. Please see my code below:
Startup.cs
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.SpaServices.AngularCli;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Identity;
using System;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using System.Text;
using IssueTracker.Data;
namespace IssueTracker
{
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.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
// In production, the Angular files will be served from this directory
services.AddSpaStaticFiles(configuration =>
{
configuration.RootPath = "ClientApp/dist";
});
// Enabling CORS
services.AddCors(options =>
{
options.AddPolicy("EnableCORS", builder =>
{
builder.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod().AllowCredentials().Build();
});
});
// Connect to the Database
services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration.getConnectionString("DefaultConnection")));
}
// 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.UseCors("EnableCORS");
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseSpaStaticFiles();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller}/{action=Index}/{id?}");
});
app.UseSpa(spa =>
{
// To learn more about options for serving an Angular SPA from ASP.NET Core,
// see https://go.microsoft.com/fwlink/?linkid=864501
spa.Options.SourcePath = "ClientApp";
if (env.IsDevelopment())
{
spa.UseAngularCliServer(npmScript: "start");
}
});
}
}
}
ApplicationDbContext
using IssueTracker.Models;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
namespace IssueTracker.Data
{
public class ApplicationDbContext : IdentityDbContext<IdentityUser>
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options) {}
// Creating the roles
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
builder.Entity<IdentityRole>().HasData(
new { Id = "1", name="Admin", NoralizeName = "ADMIN" },
new { Id = "1", name="Customer", NoralizeName = "CUSTOMER" },
new { Id = "1", name="Moderator", NoralizeName = "MODERATOR" }
);
}
public DbSet<ProductModel> Products { get; set; }
}
}
Could you please tell me what is wrong here? Thank you.
I had the same error and simply closing and reopening my IDE (Visual Studio Code) solved it. I hope it helps
One reason for this error might be that you have accidently made a copy of Startup.cs file.
I coppied solution file for backup purposes then I got that error. When I delete the backup file problem solved.
Making a micro-service architecture with Ocelot I started to build a test service in a separate solution. Everything is working and I can get the mock response to https://localhost:5101/service/stats/collected.
Then in another solution I'm making a fresh new webapi project. Then I follow the getting started at Ocelot's official website.
Configuring the .json file to use it as a GW I got a 500 from the project if I try to hit https://localhost:5001/api/stats/collected and I cannot figure out why ?
Here the main files for the APIGW :
ocelot.json
{
"ReRoutes": [
{
"DownstreamPathTemplate": "/service/stats/collected",
"DownstreamScheme": "https",
"DownstreamHostAndPorts": [
{
"Host": "localhost",
"Port": 5101
}
],
"UpstreamPathTemplate": "/api/stats/collected"
}
],
"GlobalConfiguration": {
"BaseUrl": "https://localhost:5001"
}
}
Program.cs
using System.IO;
using System.Net;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Ocelot.DependencyInjection;
using Ocelot.Middleware;
namespace APIGateway.Base
{
public class Program
{
public static void Main(string[] args)
{
new WebHostBuilder()
.UseKestrel(
options =>
{
options.Listen(IPAddress.Loopback, 5001, listenOptions =>
{
listenOptions.UseHttps("localhost.pfx", "qwerty123");
});
options.AddServerHeader = false;
}
)
.UseContentRoot(Directory.GetCurrentDirectory())
.ConfigureAppConfiguration((hostingContext, config) =>
{
config
.SetBasePath(hostingContext.HostingEnvironment.ContentRootPath)
.AddJsonFile("appsettings.json", true, true)
.AddJsonFile($"appsettings.{hostingContext.HostingEnvironment.EnvironmentName}.json", true, true)
.AddJsonFile("ocelot.json")
.AddEnvironmentVariables();
})
.ConfigureServices(s => {
s.AddOcelot();
})
.ConfigureLogging((hostingContext, logging) =>
{
//add your logging
})
.UseIISIntegration()
.Configure(app =>
{
app.UseOcelot().Wait();
})
.Build()
.Run();
}
}
}
Startup.cs
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace StatsService.Base
{
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.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}
// 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.UseHsts();
}
app.UseHttpsRedirection();
app.UseMvc();
}
}
}
UPDATE:
I find out that disabling the SSL on each project by commenting the options in the method UseKestrel make my GW works.
How can I setup up this to have a secure connexion between my GW and the Service ? Localhost and Prod ?
As you are using "localhost" as the hostname, I'd guess that you are using a self signed certificate for localhost. In that case you might have to add
"DangerousAcceptAnyServerCertificateValidator": true
to your ReRoutes configuration (see https://ocelot.readthedocs.io/en/latest/features/configuration.html#ssl-errors).
Other options would be:
using a valid certificate (quite hard to achieve for localhost)
register the self signed certificate in your user's certificate store as a trustworthy certificate.
I Have to changed ReRoute to Route then my routes redirect correctly.Please Use Route in your ocelot configuration file
You project is enabled for SSL, you have to disabled the SSL and remove the route with HTTPS in the launchSettings.json in all of your WEB API project. It will work successfully.
I am trying to get a net core 3.1 with identity setup with Razor pages where all pages require login and I want the login to last on the browser for 300 days.
I have tried updating my startup.cs file to so that the login will last for a long time. But no matter what I have tried the login will not last more than 20 or 30 minutes. Below is my current startup.cs file.
using System;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using IKDataWeb.Data;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc.Authorization;
using Microsoft.AspNetCore.Identity.UI.Services;
using IKDataWeb.Services;
namespace IKDataWeb
{
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.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(
Configuration.GetConnectionString("DefaultConnection"),
sqlServerOptions => sqlServerOptions.CommandTimeout(900)
));
services.AddDefaultIdentity<IdentityUser>(options => {
options.SignIn.RequireConfirmedAccount = true;
options.Lockout.AllowedForNewUsers = true;
})
.AddRoles<IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>();
services.ConfigureApplicationCookie(options =>
{
options.ExpireTimeSpan = TimeSpan.FromDays(300);
options.SlidingExpiration = true;
});
services.AddRazorPages().AddRazorOptions(options =>
{
options.PageViewLocationFormats.Add("/Pages/Shared/Components/Master/{0}.cshtml");
});
services.AddControllers(config =>
{
var policy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build();
config.Filters.Add(new AuthorizeFilter(policy));
});
services.AddSingleton<IEmailSender, EmailSender>();
services.AddSingleton<IEmailConfiguration>(Configuration.GetSection("EmailConfiguration").Get<EmailConfiguration>());
services.AddTransient<IEmailService, EmailService>();
services.AddTransient<IFilterProducts, FilterProducts>();
}
// 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();
app.UseDatabaseErrorPage();
}
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.MapRazorPages();
});
}
}
}
Actually, it turns out that Rono was correct!
This answer did the trick.
Thanks for your help!