Redirect to login when unauthorized in ASP.NET Core

后端 未结 6 1285
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-14 06:24

In the previous ASP.NET MVC, there was an option to redirect to the login action, if the user was not authenticated.

I need the same thing with ASP.NET Core, so I:

相关标签:
6条回答
  • 2020-12-14 07:06

    With the current aspnet core version (2.1.0), this has changed, now you can use the extensions:

       services.ConfigureApplicationCookie(options => options.LoginPath = "/login");
    

    or

     services
             .AddAuthentication()
             .AddCookie(options =>
             {
                 options.LoginPath = "/login";
                 options.LogoutPath = "/logout";
             });
    

    You can see more about migrating in to 2.0 in this article.

    0 讨论(0)
  • 2020-12-14 07:10

    You can configure the path using CookieAuthenticationOptions class.

    Something like this.

    app.UseCookieAuthentication(new CookieAuthenticationOptions {
            LoginPath = new PathString("/Login/"),
            AuthenticationType = "My-Magical-Authentication",
            // etc...
            },
    });
    
    0 讨论(0)
  • 2020-12-14 07:10

    For anyone that's interested it can also be done with the AddIdentity service provider.

    services.AddIdentity<User, IdentityRole>(options =>
        {
            options.Cookies.ApplicationCookie.AutomaticAuthenticate = true;
            options.Cookies.ApplicationCookie.AutomaticChallenge = true;
            options.Cookies.ApplicationCookie.LoginPath = "/Auth/Login";
        })
        .AddEntityFrameworkStores<MehandiContext>()
        .AddDefaultTokenProviders();
    

    And as explained here: https://stackoverflow.com/a/41643105/5784635

    I attempted this in April 2017 and "Microsoft.AspNetCore.Identity.EntityFrameworkCore": "1.1.0" doesn't redirect I had to use the 1.0.1 version

    0 讨论(0)
  • 2020-12-14 07:12

    The redirect did not work in my app at all and none of the solutions here fixed it, but using Status Code Pages did:

    app.UseStatusCodePages(async context => 
    {
        var response = context.HttpContext.Response;
    
        if (response.StatusCode == (int)HttpStatusCode.Unauthorized ||
            response.StatusCode == (int)HttpStatusCode.Forbidden)
            response.Redirect("/Authentication");
    });
    
    app.UseMvc(...        
    
    0 讨论(0)
  • 2020-12-14 07:23

    this code block in the startup file works for me in .Net Core 3.1

    services.ConfigureApplicationCookie(options =>
        {
            // Cookie settings
            options.Cookie.HttpOnly = true;
            options.ExpireTimeSpan = TimeSpan.FromMinutes(5);
    
            options.LoginPath = "/Identity/Account/Login";
            options.AccessDeniedPath = "/Identity/Account/AccessDenied";
            options.SlidingExpiration = true;
        });
    
    
    0 讨论(0)
  • 2020-12-14 07:26

    The way that dotnet core scaffolds Cookie Authentication is using the Identity framework. For a fresh project, I recommend going to the command line and doing something like this:

    dotnet new mvc -o ExampleProject --auth Individual
    

    You can gain full control of the authentication process by modifying the folowing method in Startup.cs to look like this:

    public void ConfigureServices(IServiceCollection services)
    {
        services.Configure<CookiePolicyOptions>(options =>
        {
            options.CheckConsentNeeded = context => true;
            options.MinimumSameSitePolicy = SameSiteMode.None;
        });
    
        services.AddDbContext<ApplicationDbContext>(options =>
            options.UseSqlServer(
                Configuration.GetConnectionString("DefaultConnection")));
    
        services.AddIdentity<IdentityUser, IdentityRole>()
            // services.AddDefaultIdentity<IdentityUser>()
            .AddEntityFrameworkStores<ApplicationDbContext>()
            .AddDefaultTokenProviders();
    
        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
            .AddRazorPagesOptions(options =>
            {
                options.AllowAreas = true;
                options.Conventions.AuthorizeAreaFolder("Identity", "/Account/Manage");
                options.Conventions.AuthorizeAreaPage("Identity", "/Account/Logout");
            });
    
        services.ConfigureApplicationCookie(options =>
        {
            options.LoginPath = $"/Identity/Account/Login";
            options.LogoutPath = $"/Identity/Account/Logout";
            options.AccessDeniedPath = $"/Identity/Account/AccessDenied";
        });
    
        // using Microsoft.AspNetCore.Identity.UI.Services;
        services.AddSingleton<IEmailSender, EmailSender>();
    }
    

    Reference: https://docs.microsoft.com/en-us/aspnet/core/security/authentication/scaffold-identity?view=aspnetcore-2.2&tabs=visual-studio#full

    My personal preference for authentication is the hybrid flow of IdentityServer4, gives you a scope for configuring multiple applications using a single sign on.

    0 讨论(0)
提交回复
热议问题