【问题标题】:-Authorize- not working with 2 ASP.NET MVC controllers-Authorize- 不使用 2 个 ASP.NET MVC 控制器
【发布时间】:2022-01-20 10:25:43
【问题描述】:

我正在构建一个带有 2 个控制器的 ASP.NET MVC Web 应用程序,1 个将请求发送到 API,另一个将处理 身份验证。应用程序构建得很好,但授权标签不起作用,我可以轻松访问秘密页面而无需 cookie。

这是访问控制器:

public class AccessController : Controller
{
    public IActionResult Index()
    {
        return View();
    }

    public IActionResult Login()
    {
        return RedirectToAction("Index");
    }

    [Authorize]
    public IActionResult Secret()
    {
        return View();
    }
}

这是startup.cs 文件:

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        //services.AddControllers();
        // Add session
        services.AddDistributedMemoryCache();
        services.AddSession();

        // Add services to the container.
        services.AddSingleton<IClient, ClientConcessionario>();

        services.AddAuthentication("CookieAuth").AddCookie("CookieAuth", config =>
        {
            config.Cookie.Name = "CookieAuth";
            config.LoginPath = "/Access/Login";
        });

        services.AddControllersWithViews();
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseHttpsRedirection();
        app.UseStaticFiles();
        app.UseSession();

        app.UseRouting();
        app.UseAuthorization();
        app.UseEndpoints(endpoints =>
        {
            endpoints.MapDefaultControllerRoute();
        });
        ;
    }
}

我可以查看两个控制器的所有 url,但如果没有 cookie,我应该无法访问秘密页面。有什么线索吗?

【问题讨论】:

  • 在 app.UseRouting(); 之后添加 app.UseAuthentication();

标签: c# asp.net-mvc api


【解决方案1】:

您应该在 UseRouting 之前在 Configure 方法中调用 UseAuthentication() 和 UseAuthorization()。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多