簡體   English   中英

如何強制啟動 Asp.Net Core 3.0 應用程序以使用身份登錄頁面

[英]How to force start Asp.Net Core 3.0 application to use Identity Login Page

我使用 Asp.Net Core 3.0.1,我需要強制重定向到身份登錄頁面,但是,在我更改啟動配置后它仍然將我重定向到 /Home/Index 頁面,這是我的啟動 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)
{
    //Conection Provider for Identity
    services.AddDbContext<ApplicationDbContext>(options =>
        options.UseSqlServer(Configuration.GetConnectionString("yourConnection")));

    services.AddIdentity<IdentityUser, IdentityRole>(options => options.SignIn.RequireConfirmedAccount = true)
        .AddEntityFrameworkStores<ApplicationDbContext>()
        .AddDefaultTokenProviders();


    services.AddMemoryCache();


    services.Configure<IdentityOptions>(options =>
    {
        //Password Settings
        options.Password.RequireDigit = true;
        options.Password.RequireLowercase = true;
        options.Password.RequireNonAlphanumeric = true;
        options.Password.RequireUppercase = true;
        options.Password.RequiredLength = 8;
        options.Password.RequiredUniqueChars = 1;

        //Lockout Settings
        options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(5);
        options.Lockout.MaxFailedAccessAttempts = 3;
        options.Lockout.AllowedForNewUsers = true;

        //User settings
        options.User.AllowedUserNameCharacters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._@+#";
        options.User.RequireUniqueEmail = true;

    });

    //Configure application cookie
    services.ConfigureApplicationCookie(options =>
    {
        options.Cookie.HttpOnly = true;
        options.ExpireTimeSpan = TimeSpan.FromMinutes(1);
        options.LoginPath = "/Login";
        options.LogoutPath = "/Logout";
        options.AccessDeniedPath = "/AccessDenied";
        options.SlidingExpiration = true;
    });


    services.AddMvc(options =>
    {
        options.EnableEndpointRouting = false;
    })
    .SetCompatibilityVersion(Microsoft.AspNetCore.Mvc.CompatibilityVersion.Version_3_0)
    .AddSessionStateTempDataProvider();


    services.AddDistributedMemoryCache();
    services.AddSession(options => {
        options.IdleTimeout = TimeSpan.FromMinutes(1);
    });


    services.AddTransient<IEmailSender, EmailSender>(i =>
        new EmailSender(
            Configuration["EmailSender:Host"],
            Configuration.GetValue<int>("EmailSender:Port"),
            Configuration.GetValue<bool>("EmailSender:EnableSSL"),
            Configuration["EmailSender:UserName"],
            Configuration["EmailSender:Password"]
        ));

    services.AddControllersWithViews();
    services.AddRazorPages(options =>
    {
        options.Conventions.ConfigureFilter(new IgnoreAntiforgeryTokenAttribute());
    });

}


public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IServiceProvider serviceProvider)
{
    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.UseSession();
    app.UseMvc(routes =>
    {
        //routes.MapRoute(
        //    name: "Identity",
        //    template: "Identity/{controller=Account}/{action=Login}/{id?}");

        routes.MapAreaRoute(
            name: "Identity",
            areaName: "Identity",
            template: "Identity/{controller=Account}/{action=Login}/{id?}");


    });

    app.UseCookiePolicy();

    CreateRoles(serviceProvider).Wait();
    RotativaConfiguration.Setup((Microsoft.AspNetCore.Hosting.IHostingEnvironment) env);

}

如何強制我的應用程序使用身份區域中的 /Account/Login 啟動?

這是我在同一問題中搜索的一些鏈接:

  1. 在 ASP.NET 內核中未經授權時重定向到登錄

  2. https://wakeupandcode.com/authentication-authorization-in-asp-net-core-razor-pages/

  3. https://dotnetcoretutorials.com/2017/09/16/cookie-authentication-asp-net-core-2-0/

我也使用netcore 3.0。

我對你的代碼的區別

        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllerRoute(
                name: "default",
                pattern: "{controller=Home}/{action=Index}/{id?}");
        });

當 cookie 無效時,Mycode 正在處理。 我用這樣的cookie

services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
                .AddCookie(options =>
                {
                    options.Cookie.Name = "<Your cookiename>";
                    options.LoginPath = "auth/login";//This should login page path
                    options.LogoutPath = "auth/logout";//This should logout page path
                    options.ExpireTimeSpan = TimeSpan.FromDays(1);
                    options.SlidingExpiration = false;
                });

我希望它有幫助:)

我有類似的問題,在浪費了幾個小時之后,我通過將 [Authorized] 屬性放在 class 之上解決了這個問題。 我希望我在這方面對某人有所幫助。 :)

[Authorize]
public class IndexModel : PageModel
{
    private readonly ILogger<IndexModel> _logger;

    public IndexModel(ILogger<IndexModel> logger)
    {
        _logger = logger;
    }

    public void OnGet()
    {

    }
}

我之前在 .net 核心 2.2 中遇到過這個問題,我在launchSettings.json文件中修復了它,正如您在Microsoft Docs中看到的那樣

它似乎也適用於版本 3,您可以在下面的示例中看到多個環境:

{
  "iisSettings": {
    "windowsAuthentication": false,
    "anonymousAuthentication": true,
    "iisExpress": {
      "applicationUrl": "http://localhost:54339/",
      "sslPort": 0
    }
  },
  "profiles": {
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "environmentVariables": {
        "ASPNETCORE_My_Environment": "1",
        "ASPNETCORE_DETAILEDERRORS": "1",
        "ASPNETCORE_ENVIRONMENT": "Staging"
      }
    },
    "EnvironmentsSample": {
      "commandName": "Project",
      "launchBrowser": true,
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Staging"
      },
      "applicationUrl": "http://localhost:54340/"
    },
    "Kestrel Staging": {
      "commandName": "Project",
      "launchBrowser": true,
      "environmentVariables": {
        "ASPNETCORE_My_Environment": "1",
        "ASPNETCORE_DETAILEDERRORS": "1",
        "ASPNETCORE_ENVIRONMENT": "Staging"
      },
      "applicationUrl": "http://localhost:51997/"
    }
  }
}

就我而言,我必須添加"launchUrl": "my url"

就像下面的代碼片段:

{
  "$schema": "http://json.schemastore.org/launchsettings.json",
  "iisSettings": {
    "windowsAuthentication": false, 
    "anonymousAuthentication": true,
    "iisExpress": {
      "launchUrl": "[your url here]"
    }
  },
  "profiles": {
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "launchUrl": "[your url here]",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    }
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM