【问题标题】:How is access restricted in the ASP.NET Core web app template when using ASP.NET Core Identity使用 ASP.NET Core 标识时如何在 ASP.NET Core Web 应用模板中限制访问
【发布时间】:2021-12-13 04:44:10
【问题描述】:

我有一个使用 ASP.NET Core Identity 进行授权的 ASP.NET Core 5 Web 应用程序。我已经搭建了所有 Identity UI 的脚手架,以便了解它是如何工作的。

在“身份”区域的脚手架 Razor 页面中,我可以看到几个用[AllowAnonymous] 装饰的页面模型类,但我看不到任何对限制访问的任何内容的引用.

不过,一定有什么东西,因为模板网站中的某些页面在未登录时可以访问(即使它们没有[AllowAnonymous]),但脚手架Identity 区域中的大多数页面都是除非登录,否则无法访问。

这是如何实现的?我希望看到对AuthorizeFolder(或AuthorizeAreaFolder)的调用,但我在项目中的任何地方都看不到。

我想添加一些自己的授权规则,但在开始更改之前我想知道现有规则是什么。

【问题讨论】:

    标签: asp.net-core razor-pages asp.net-core-identity


    【解决方案1】:

    要保持对 Identity UI 的完全控制,请运行 Identity 脚手架并选择覆盖所有文件。

    您可能希望这样做以完全控制身份 UI。

    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()
            .AddRazorPagesOptions(options =>
            {
                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>();
    }
    

    参考:Create full Identity UI source

    Simple authorization in ASP.NET Core

    Razor Pages authorization conventions in ASP.NET Core

    【讨论】:

    • 谢谢。我已经运行了脚手架并生成了所有文件(参见我的第一段)。但是我错过了您第一个链接中的步骤,所以我仍然可以致电AddDefaultIdentity。这 must 是设置授权策略的原因......但是,当我查看该方法的 source 时,我没有看到任何设置任何授权规则的内容(实际上也没有特定于脚手架身份用户界面)。所以,我的问题仍然存在 - 这些规则在哪里应用?
    • 啊,找到了。它在 IdentityDefaultUIConfigureOptions 类中,由 AddDefaultIdentity 间接引用。
    猜你喜欢
    • 1970-01-01
    • 2021-06-23
    • 1970-01-01
    • 2018-04-28
    • 1970-01-01
    • 2020-08-07
    • 2018-11-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多