I'm fairly new to web development so I've been experimenting with the template code Microsoft has provided through their default .NET Core Application option. I was able to successfully deploy the website using Azure services and connected it to a server with its own database.
One of the things I've been struggling with, however, is setting up Facebook authentication. I followed this guide: https://www.c-sharpcorner.com/article/authentication-using-facebook-in-asp-net-core-2-0/
and was able to successfully login with Facebook locally, but when I try to publish and go to the website with the new code in ConfigureServices function I get a HTTP 500 error.
My website is: vincecoreapp.azurewebsites.net
Here is the snippet that I inserted:
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
services.AddAuthentication().AddFacebook(facebookOptions =>
{
facebookOptions.AppId = Configuration["Authentication:Facebook:AppId"];
facebookOptions.AppSecret = Configuration["Authentication:Facebook:AppSecret"];
});
// Add application services.
services.AddTransient<IEmailSender, EmailSender>();
services.AddMvc();
}
Any advice would be extremely helpful, thank you!
My guess would be that you haven't added the published "something.azurewebsites.net" URL to the Valid OAuth Redirect Settings in your Facebook App Settings
namespace VinceCoreApp
{
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")));
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
services.AddAuthentication().AddFacebook(facebookOptions =>
{
facebookOptions.AppId = "680347028977338";
//Configuration["Authentication:Facebook:AppId"];
facebookOptions.AppSecret = "fc943b8782d7d5d83a4446709f2d903a";
//Configuration["Authentication:Facebook:AppSecret"];
});
// Add application services.
services.AddTransient<IEmailSender, EmailSender>();
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.UseBrowserLink();
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();
app.UseAuthentication();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
}
}
This solved the problem
Related
App in .net core is not redirecting to https
Good Morning. Can someone help me?
I have the following problem. My website is not automatically redirecting to HTTPS. I need to put https: // at the beginning of my application for it to work. When the session goes down or I log out, the site is directed to http instead of https.
These are the settings:
ASPNETCORE_ENVIRONMENT: Development
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.UseMySql(
Configuration.GetConnectionString("DefaultConnection"))
// .UseLazyLoadingProxies()
);
services.AddHealthChecks()
.AddCheck<HealthCheck>("check_smc_app",
failureStatus: HealthStatus.Degraded,
tags: new[] { "smc_tag" });
services.AddMvcCore().AddNewtonsoftJson(
options => options.SerializerSettings.ReferenceLoopHandling =Newtonsoft.Json.ReferenceLoopHandling.Ignore);
//services.AddIdentityCore<ApplicationUser>().AddEntityFrameworkStores<ApplicationDbContext>();
services.AddIdentity<ApplicationUser, ApplicationRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultUI()
.AddDefaultTokenProviders();
services.AddControllersWithViews();
services.AddRazorPages();
services.AddHttpsRedirection(options =>
{
options.RedirectStatusCode = StatusCodes.Status307TemporaryRedirect;
//options.HttpsPort = 8080;
});
InjetorDependencias.Registrar(services);
var config = new AutoMapper.MapperConfiguration(cfg =>
{
cfg.AddProfile(new MappingEntidades());
});
IMapper mapper = config.CreateMapper();
services.AddSingleton(mapper);
}
// 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.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
endpoints.MapRazorPages();
endpoints.MapHealthChecks("/v1/health/live");
endpoints.MapHealthChecks("/v1/health/read");
});
}
}
In development env, application is by default http. if you want to use https for development, use ngrok or you can check the port which is mentioned in launchsettings.json file in Properties directory of your project.for the production, it depends on your cloud but if you want to install SSL to IIS this article is good way to go.
https://www.thesslstore.com/knowledgebase/ssl-install/microsoft-iis-7-ssl-installation/
It looks like you have not defined the https port. Per the documentation you need something like the following in appsettings.json
{
"https_port": 443,
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*"
}
Of course, if you want a different port for development you could override this value in appsettings.development.json. For that matter, you can override the port in a variety of ways.
I also believe that you do not need this in your code
services.AddHttpsRedirection(options =>
{
options.RedirectStatusCode = StatusCodes.Status307TemporaryRedirect;
//options.HttpsPort = 8080;
});
The documentation is here: Enforce HTTPS in ASP.NET Core
My project already has the Identity Folder:
And the database already has the roles tables :
How do I configure LogIn and registeration from here? Is there any tutorial that I can follow. Most of them explain how to do this from the beginig, but I'm having a hard time implementing this into my project.
(Besides the files that the images show, I also have the LoginPartial View, but that's it)
Here is my StartUp class:
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.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(
Configuration.GetConnectionString("DefaultConnection")));
services.AddDefaultIdentity<IdentityUser>()
.AddEntityFrameworkStores<ApplicationDbContext>();
services.AddControllersWithViews().AddNewtonsoftJson(options =>
options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
);
services.AddSignalR();
services.AddTransient<IgnicoesAPIController, IgnicoesAPIController>();
services.AddSingleton<IConfiguration>(Configuration);
}
// 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.UseCookiePolicy();
app.UseAuthentication();
String caminho = Configuration["AppSettings:Servidor"] + "/myHub";
//endpoints.MapHub<MyHub>(caminho);
//app.UseSignalR(route =>
//{
// route.MapHub<MyHub>(caminho);
//});
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapHub<MyHub>("/myHub");
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}
}
It depends on which route you want to take from this point. If you wish to create razor page or view with controller. Either way you will probably use ‘SigninManager’ or ‘UserManager’, thats built-in feature in Identity. Create a page that takes inputs from user, then use controller to verify the information. In the controller, create a readonly props of SigninManager if you want to login feature or UserManger, if its for registering user. Hope this help and sorry for any grammatical mistake as i am typing via phone.
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: Enable Cross-Origin Requests (CORS) in ASP.NET Core
Here it is my 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.AddControllers();
services.AddCors(options =>
{
options.AddPolicy("CorsPolicy",
builder => builder.WithOrigins("localhost", "www.google.com")
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials());
});
}
// 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();
});
}
}
And these are my response headers:
What should I set up for getting corret CORS headers in Response?
Here it is my fetch api test:
Oops, I successed to solve this.
This combination was the only one to me, what is working:
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(); //This needs to let it default
}
// 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(
options => options.SetIsOriginAllowed(x => _ = true).AllowAnyMethod().AllowAnyHeader().AllowCredentials()
); //This needs to set everything allowed
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
If you put the API URL directly in the browser, CORS is not involved.
It isn't a cross-origin request.
That only happens when you have a page hosted at one origin, e.g. localhost:5000, which has JavaScript code that calls an API at origin localhost:5001.
(or otherwise fetches resources from another origin)
But in your case the only origin is the API origin and thus CORS is not needed.
I was developing a Web-App with Asp.Net Core 2.1 . After I added the new identity with scaffolder it generated me these codes:
Code generated in IdentityStartup.cs
[assembly:HostingStartup(typeof(ShareAndCare.Areas.Identity.IdentityHostingStartup))]
namespace ShareAndCare.Areas.Identity
{
public class IdentityHostingStartup : IHostingStartup
{
public void Configure(IWebHostBuilder builder)
{
builder.ConfigureServices((context, services) => {
services.AddDbContext<ShareAndCareContext>(options =>
options.UseLazyLoadingProxies().UseSqlServer(
context.Configuration.GetConnectionString("ShareAndCareContextConnection")));
services.AddIdentity<ShareAndCareUser, IdentityRole>()
.AddEntityFrameworkStores<ShareAndCareContext>()
.AddDefaultTokenProviders();
services.AddSingleton<IEmailSender, EmailSender>();
});
}
}
}
Code generated in Startup.cs
namespace ShareAndCare
{
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.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, IServiceProvider serviceProvider)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseAuthentication();
app.UseCookiePolicy();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
}
}
This was working fine until I wanted to scaffold a model with controller and views using EF. When set up everything and click ok I was getting an error saying : More than one DbContext named 'ShareAndCare.Models.ShareAndCareContext' was found. Specify which one to use by providing its fully qualified name using its exact case. I checked all the folders and namespaces but there was no problem there, there was only one context with that name. So what was the problem ?
I'm leaving that question and answer here so people don't go crazy looking for all possible solutions manually like I did. I found out that adding the context in the Configure method of IdentityHostingStartup.cs was causing the problem. I changed the place where I added the context to the Configure method of Startup.cs and it was working just fine.
namespace ShareAndCare
{
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.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
services.AddDbContext<ShareAndCareContext>(options =>
options.UseLazyLoadingProxies().UseSqlServer(
Configuration.GetConnectionString("ShareAndCareContextConnection")));
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, IServiceProvider serviceProvider)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseAuthentication();
app.UseCookiePolicy();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
}
}
I just deleted the 2 files:
Areas/Identity/Data/APNameIdentityDbContext.cs and
Areas/Identity/IdentityHostingStartup.cs
This fixed the error!
In my Case I was adding
services.AddDbContext<DBContext>
but instead my DBContext name was
ApplicationDBContext.
Changed my Name in Startup.cs and it worked
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddDbContext<ApplicationDBContext>(options => options.UseSqlServer(Configuration["Data:ConnectionStrings:DefaultConnection"]));
}
Hope this helps someone :)
I'd like to enable CORS on an API built with ASP.NET Core MVC, but all the current documents refer to earlier versions of that framework.
The notes on the new Cors features are very light, but I was able to get it working in my solution by looking at the new classes and methods. My Web API startup.cs looks like this. You can see how you can construct your origins and policies her by using the new CorsPolicy class. And enabling CORS with the AddCors and UseCors methods.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
//Add Cors support to the service
services.AddCors();
var policy = new Microsoft.AspNet.Cors.Core.CorsPolicy();
policy.Headers.Add("*");
policy.Methods.Add("*");
policy.Origins.Add("*");
policy.SupportsCredentials = true;
services.ConfigureCors(x=>x.AddPolicy("mypolicy", policy));
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
// Configure the HTTP request pipeline.
app.UseStaticFiles();
//Use the new policy globally
app.UseCors("mypolicy");
// Add MVC to the request pipeline.
app.UseMvc();
}
You can also reference the policy in the controllers with the new attributes like so
[EnableCors("mypolicy")]
[Route("api/[controller]")]
I got it working using the following code:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddCors(options => options.AddPolicy("AllowAll", p => p.AllowAnyOrigin()));
}
You can chain AllowAnyHeader() and/or AllowAnyMethod() to the configure action if needed.
To configure it for the complete app:
public void Configure(IApplicationBuilder app)
{
app.UseCors("AllowAll");
}
Or just for a controller:
[EnableCors("AllowAll")]
public class HomeController : Controller
{
// ...
}
--
Update: configuring CORS for all requests can be done a bit easier:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddCors();
}
public void Configure(IApplicationBuilder app)
{
app.UseCors(builder =>
{
builder.WithOrigins("http://some.origin.com")
.WithMethods("GET", "POST")
.AllowAnyHeader();
});
}
For more information, refer to the docs.
In the most recent RC2 of ASP.NET Core.
The NuGet packages are
"Microsoft.AspNetCore.Owin": "1.0.0-rc2-final",
"Microsoft.AspNetCore.Cors": "1.0.0-rc2-final",
In Startup.cs
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddCors();
services.AddMvc();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
app.UseCors(builder => builder
.AllowAnyOrigin());
app.UseMvc();
}
Support for CORS is currently in development. Following issue is tracking that:
https://github.com/aspnet/Mvc/issues/498
Update (3/28/2015):
This feature has been checked in and should be available in the next release.
cs1929 the method services.ConfigureCors(...) does no more exist. It is combined to AddCors:
services.AddCors(options =>
options.AddPolicy("AllowAllOrigins", builder => builder.AllowAnyOrigin()));
Install : Microsoft.AspNetCore.Cors
In Configure method:
app.UseCors(builder =>
builder.WithOrigins("http://some.origin.com"));