.NET Core 2.0 accessing user secrets - c#

I'm trying to setup a .net core 2.0 web application to send an email when user registers and also to recover password. I have followed this tutorial: https://learn.microsoft.com/en-us/aspnet/core/security/app-secrets?tabs=visual-studio.
However, upon reading the comments sections, it seems that the tutorial is not updated for Core 2.0. My question is, when I get to part "Add the user secrets configuration source to the Startup method", I cannot figure out how the startup file should look like since my startup file is different from the one showed there. Can anyone help me by showing me how the startup file should look like? Thanks.
This is my current startup file:
public class Startup
{
string _testSecret = null;
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)
{
_testSecret = Configuration["MySecret"];
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddIdentity<ApplicationUser, IdentityRole>(config =>
{
config.SignIn.RequireConfirmedEmail = true;
})
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
// Add application services.
services.AddTransient<IEmailSender, EmailSender>();
services.AddMvc();
services.Configure<AuthMessageSenderOptions>(Configuration);
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
var builder = new ConfigurationBuilder();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseBrowserLink();
app.UseDatabaseErrorPage();
builder.AddUserSecrets<Startup>();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();
app.UseAuthentication();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
}

In your code I didn't find invoking of build() function of ConfigurationBuilder class. Here is the sample code.
var builder = new ConfigurationBuilder();
builder.AddUserSecrets<Startup>();
var config builder.Build(); //This line is missing from your code
string mySecret = config ['EmailAccount'];
Refernce: https://learn.microsoft.com/en-us/aspnet/core/security/app-secrets?view=aspnetcore-2.1&tabs=windows#access-a-secret

Related

Loading Static Files from Controller ASP Net Core MVC

I have a puzzling problem, my application loads static files from controller folder, but in default route it loads normally
Example:
https://localhost:44369/plugins/bootstrap/js/bootstrap.bundle.min.js (in normal situation) (needs to be work)
In my situation
https://localhost:44369/Order/plugins/bootstrap/js/bootstrap.bundle.min.js
It wants to load from static files from controller folder which does not exist.
I use Admin LTE 3 Template (maybe the template has some issues?)
Thank you :)
Startup.cs
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.AddHttpClient();
services.AddAutoMapper(typeof(Startup));
services.AddControllersWithViews().AddRazorRuntimeCompilation();
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
services.AddSingleton<ICustomerService, CustomerManager>();
services.AddSingleton<ICustomerDal, CustomerDal>();
services.AddSingleton<IInformationResourcesService, InformationResourcesManager>();
services.AddSingleton<IInformationResources, EFInformationResourcesDAL>();
services.AddSingleton<INewOrderService, NewOrderManager>();
services.AddSingleton<INewOrderService, NewOrderManager>();
services.AddSingleton<INewOrderDal, EfNewOrderDalL>();
services.AddSingleton<ICityDal, EFCityDal>();
services.AddSingleton<ICityService, CityManager>();
services.AddSingleton<IDisctrictDal, EFDistrictDal>();
services.AddSingleton<IDistrictService, DistrictManager>();
services.AddSingleton<IVillageDal, EFVillageDal>();
services.AddSingleton<IVillageService, VillageManager>();
services.AddSingleton<IStreetDal, EFStreetDal>();
services.AddSingleton<IStreetService, StreetManager>();
services.AddSingleton<ICustomerAdressService, CustomerAdressManager>();
services.AddSingleton<ICustomerAdressDal, EFCustomerAdressDal>();
//services.AddCors(options =>
//{
// options.AddPolicy("CorsPolicy",
// builder => builder
// .AllowAnyMethod()
// .AllowCredentials()
// .SetIsOriginAllowed((host) => true)
// .AllowAnyHeader());
//});
//services.AddDependencyResolvers(new ICoreModule[] {
// new CoreModule()
//});
}
// 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("/Home/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.UseStaticFiles();
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
//app.UseCors("CorsPolicy");
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Customer}/{action=Index}/{id?}");
});
}
}
Can you specify how you are adding the script to your page.
I am using a template as well and my scripts are located in wwwroot/vendors folder
this is my script tag.
<script src="~/vendors/jquery/dist/jquery.min.js" type="text/javascript"></script>

React asp.net SPA calling API on same app service

I have one solution that includes two projects:
Foo - this an asp.net React site
Bar - this is an asp.net API, which the Foo projects calls
I have deployed both of these projects to one Azure app service using virtual directories.
Virtual Directory Setup
When the Foo app makes a call to https://azureFooapp.com/api/getData all that is returned is the index.html file from the Foo project. Instead of actually calling the endpoint located in the Bar API project.
If I remove the Foo project project from the App Service I am able to hit the endpoint https://azureFooapp.com/api/getData successfully.
Foo Startup.cs
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.AddControllersWithViews();
// In production, the React files will be served from this directory
services.AddSpaStaticFiles(configuration =>
{
configuration.RootPath = "ClientApp/build";
});
services.AddControllers()
.AddNewtonsoftJson();
services.AddMvc().AddNewtonsoftJson(o =>
{
o.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
});
}
// 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();
app.UseSpaStaticFiles();
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller}/{action=Index}/{id?}");
});
app.UseSpa(spa =>
{
spa.Options.SourcePath = "ClientApp";
if (env.IsDevelopment())
{
spa.UseReactDevelopmentServer(npmScript: "start");
}
});
}
}
Bar Startup.cs
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<ConnectionStrings>(Configuration.GetSection("ConnectionStrings"));
services.AddControllers();
services.AddControllersWithViews();
services.AddControllers()
.AddNewtonsoftJson();
services.AddMvc().AddNewtonsoftJson(o =>
{
o.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
});
services.AddCors(options =>
{
options.AddPolicy("AllowSpecificOrigin", builder =>
{
builder.WithOrigins("https://localhost").AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod();
});
});
}
// 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.UseHttpsRedirection();
app.UseRouting();
app.UseCors("AllowSpecificOrigin");
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
Can anyone please help get this working? If anymore information is needed please let me know
I suggest you put the api project under wwwroot and the react project in the virtual directory.
Like :
Virtual path Physical Path Type
/ site\wwwroot Application
/pages site\wwwroot\react_folder Application
Suggestions
Why is it not recommended to put nodejs projects, such as react, angular, and vue projects into the main application?
After a lot of testing, I found that when the main application is put into these three items, the virtual application will not take effect, and it can work normally if they are put into the virtual application.
(Not recommended) After the react project is compiled, if the content of the dist folder is released, the routing access of virtual applications is supported in iis, and this is not recommended.
I have now managed to resolve this issue by modifying the code in Foo Startup.cs with the below
app.MapWhen(x => !x.Request.Path.Value.ToLower().StartsWith("/api"), builder =>
{
builder.UseSpa(spa =>
{
spa.Options.SourcePath = "ClientApp";
if (env.IsDevelopment())
{
spa.UseReactDevelopmentServer(npmScript: "start");
}
});
});
After this I restarted the App Service

How to enable CORS in Asp.Net Core 3.0 WebAPI

I want to enable CORS with Asp.Net Core 3.0 API project. This is the basic generated Asp.Net Core Api template. Everything is default from the template, except I added CORS settings from the documentation
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.AddControllers();
services.AddCors(opt =>
{
var origins = Configuration
.GetSection("AllowedHosts")
.Get<string[]>();
opt.AddPolicy("CorsPolicy", builder => builder
.WithOrigins(origins)
.AllowAnyMethod()
.AllowAnyHeader()
.Build());
});
}
// 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.UseHttpsRedirection();
app.UseRouting();
app.UseCors("CorsPolicy");
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
What should I set up for getting corret CORS in .net core web api?
Allowed host is :
The order of precedence for Cors should be before adding controllers. It should be added as define in the official documentation: https://learn.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-3.1
Follow this 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.AddCors(options =>
{
options.AddPolicy("CorsPolicy",
builder => builder.WithOrigins("http://localhost:4200", "http://localhost:44349")
.AllowAnyMethod()
.AllowAnyHeader();
//.AllowCredentials());
});
services.AddControllers();
}
// 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.UseHttpsRedirection();
app.UseRouting();
app.UseCors("CorsPolicy");
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
As per the official documentation, it must be noted that:
Specifying AllowAnyOrigin and AllowCredentials is an insecure
configuration and can result in cross-site request forgery. The CORS
service returns an invalid CORS response when an app is configured
with both methods.

How to drop Angular into an existing .net MVC project

So, I'm working on a project using the .net MVC framework, and we'd like to use Angular for the frontend. Our project is structured as follows:
/Areas
/ClientApp
/Controllers
/Data
/Dto
/Models
/Services
/ViewModels
/Views
It's pretty boiler-plate, and it's auto-generated from Visual Studio.
I'm attempting to add in Angular. I ran ng new and generated the ClientApp directory shown above.
However, when running the app and accessing the home page, I still end up running through Controllers/HomeController and the accompanying Views/Home/Index.cshtml.
We want to keep the controllers for future API work. We have no interest at all in keeping the Views directory.
So, how can I have my project actually use that Angular directory? What's the proper way to structure this thing?
By the way, startup.cs looks like this:
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)
{
// Add framework services.
services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));
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.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(
Configuration.GetConnectionString("DefaultConnection")));
services.AddDefaultIdentity<Models.ApplicationUser>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddUserManager<Services.ApplicationUserManager>();
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
services.AddMvc()
.AddJsonOptions(options =>
{
options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
});
// Add project services.
services.AddSingleton(_ => Configuration); // enables us to inject IConfigurationRoot into service layer class.
// other choices: services.AddScoped, services.AddTransient
}
// 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.UseDatabaseErrorPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseAuthentication();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
app.UseMvc(routes =>
{
routes.MapRoute(
name: "areas",
template: "{area:exists}/{controller}/{action=Index}/{id?}"
);
});
}

ASP.NET Core 2.0 IIS Web Hosting

I created an ASP.NET Core 2.0 MVC Web Application and I need help getting it setup to run with IIS on Windows Server 2016.
So far, I have followed and completed all the steps on https://learn.microsoft.com/en-us/aspnet/core/publishing/iis?tabs=aspnetcore2x up to the section Application configuration. This is the step that I'm stuck at and have not been able to complete the steps below it.
I'm going to post my Startup.cs and Program.cs code as to what I have now. I'm not sure if those two files need modified.
Startup.cs
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<WinTenDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddMvc();
}
// 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.UseBrowserLink();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
}
Program.cs
public class Program
{
public static void Main(string[] args)
{
BuildWebHost(args).Run();
}
public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.Build();
}
The issue that I was having I finally figured it out. It had to do with the account that was setup for me on the Domain that was added to the Security on the SQL Server. Once I provided the correct permissions to that AD account I no longer received the error messages.

Categories

Resources