I am using ASP.Net core MVC 6, I am trying to get the user redirected to the login page if they are not authenticated.
I cant seem to get it to work, currently the user just gets a blank page.
Below is my ConfigureServices method in Startup.cs
public void ConfigureServices(IServiceCollection services) {
// Add framework services.
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))
);
services.AddIdentity<ApplicationUser, IdentityRole>(options => {
// configure identity options
options.Password.RequireDigit = true;
options.Password.RequireLowercase = true;
options.Password.RequireUppercase = true;
options.Password.RequireNonAlphanumeric = true;
options.Password.RequiredLength = 7;
options.Cookies.ApplicationCookie.AutomaticAuthenticate = true;
options.Cookies.ApplicationCookie.AutomaticChallenge = true;
options.Cookies.ApplicationCookie.LoginPath = "/Account/Login";
// User settings
options.User.RequireUniqueEmail = true;
})
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
services.AddMvc();
// Add application services.
services.AddTransient<IEmailSender, AuthMessageSender>();
services.AddTransient<ISmsSender, AuthMessageSender>();
}
Just for completeness - the following code block is suggested to fill out @Jawand's answer:
Same problem here. A quick fix while this problem is solved:
And then in your controller:
This will redirect you to your login page and afterwards it redirects you to the original page you wanted to access.
Attribute manager code:
I was just wrestling with this myself and I've come to the conclusion that there seems to be an issue in the latest version of the "Microsoft.AspNetCore.Identity.EntityFrameworkCore" dependency.
I was originally using version 1.1.0 but after lots of debugging, owin middleware logging etc, I came to the conclusion that I wasn't doing anything wrong. I checked:
Added event handlers (OnRedirectToLogin) as below to verify the redirect URL (this was only for debugging)
The resolution: I rolled back my package to the version 1.0.1 and then the redirects kicked in as expected - to the URL defined in Startup.cs in the LoginPath setting
To clarify, THIS version works: Microsoft.AspNetCore.Identity.EntityFrameworkCore": "1.0.1"
I'm going to raise a bug with the ASPNETCORE team for investigation as regards to the 1.1.0 version.
OK, as of Asp.Net Core 2.1 . In order to redirect user to login page. this is what you need to do in
ConfigureServices(IserviceCollection services)
method.for more info visit Microsoft identity documentation. https://docs.microsoft.com/en-us/aspnet/core/security/authentication/identity-configuration?view=aspnetcore-2.1#cookie-settings