asp.net-core-2.2 - 防止在 asp.net core 2.2 中重定向到/Account/Login

标签 asp.net-core-2.2

我试图阻止应用重定向到 /Account/Login当用户未登录时,在 asp.net core 2.2 中。
即使我写 LoginPath = new PathString("/api/contests");任何未经授权的请求仍会重定向到 /Account/Login这是我的 Startup.cs:

using System;
using System.Reflection;
using AutoMapper;
using Contest.Models;
using Contest.Tokens;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Authorization;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Newtonsoft.Json;
using Swashbuckle.AspNetCore.Swagger;

namespace Contest
{
    public class Startup
    {
        public IConfiguration Configuration { get; }

        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {

            services.AddAutoMapper();

            // In production, the React files will be served from this directory
            services.AddSpaStaticFiles(configuration =>
            {
                configuration.RootPath = "clientapp/build";
            });

            // ===== Add our DbContext ========
            string connection = Configuration.GetConnectionString("DBLocalConnection");
            string migrationAssemblyName = typeof(Startup).GetTypeInfo().Assembly.GetName().Name;
            services.AddDbContext<ContestContext>(options =>
                    options.UseSqlServer(connection,
                    sql => sql.MigrationsAssembly(migrationAssemblyName)));

            // ===== Add Identity ========
            services.AddIdentity<User, IdentityRole>(o =>
            {
                o.User.RequireUniqueEmail = true;
                o.Tokens.EmailConfirmationTokenProvider = "EMAILCONF";
                // I want to be able to resend an `Email` confirmation email
                // o.SignIn.RequireConfirmedEmail = true; 
            }).AddRoles<IdentityRole>()
                .AddEntityFrameworkStores<ContestContext>()
                .AddTokenProvider<EmailConfirmationTokenProvider<User>>("EMAILCONF")
                .AddDefaultTokenProviders();

            services.Configure<DataProtectionTokenProviderOptions>(o =>
                o.TokenLifespan = TimeSpan.FromHours(3)
            );

            services.Configure<EmailConfirmationTokenProviderOptions>(o =>
                o.TokenLifespan = TimeSpan.FromDays(2)
            );

            // ===== Add Authentication ========

            services.AddAuthentication(o => o.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme)
                .AddCookie(options =>
                {
                    options.Cookie.Name = "auth_cookie";
                    options.Cookie.SameSite = SameSiteMode.None;
                    options.LoginPath = new PathString("/api/contests");
                    options.AccessDeniedPath = new PathString("/api/contests");
                    options.Events = new CookieAuthenticationEvents
                    {
                        OnRedirectToLogin = context =>
                        {
                            context.Response.StatusCode = StatusCodes.Status401Unauthorized;
                            return Task.CompletedTask;
                        },
                    };
                });

            // ===== Add Authorization ========

            services.AddAuthorization(o =>
            {

            });

            services.AddCors();

            // ===== Add MVC ========
            services.AddMvc(config =>
            {
                var policy = new AuthorizationPolicyBuilder()
                                    .RequireAuthenticatedUser()
                                    .Build();
                config.Filters.Add(new AuthorizeFilter(policy));
            })
                .AddJsonOptions(options => options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore)
                .SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

            // ===== Add Swagger ========
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Info
                {
                    Title = "Core API",
                    Description = "Documentation",
                });

                var xmlPath = $"{System.AppDomain.CurrentDomain.BaseDirectory}Contest.xml";
                c.IncludeXmlComments(xmlPath);
            });

        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Error");
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseSpaStaticFiles(new StaticFileOptions()
            {

            });

            app.UseCors(policy =>
            {
                policy.AllowAnyHeader();
                policy.AllowAnyMethod();
                policy.AllowAnyOrigin();
                policy.AllowCredentials();
            });

            app.UseAuthentication();

            app.UseMvc();

            if (env.IsDevelopment())
            {
                app.UseSwagger();
                app.UseSwaggerUI(c =>
                {
                    c.SwaggerEndpoint("/swagger/v1/swagger.json", "Core API");
                });
            }

            app.UseSpa(spa =>
            {
                spa.Options.SourcePath = "clientapp";

                if (env.IsDevelopment())
                {
                    // spa.UseReactDevelopmentServer(npmScript: "start");
                    spa.UseProxyToSpaDevelopmentServer("http://localhost:3000");
                }
            });

        }

    }
}
我设法通过创建一个 Controller 来处理这条路线来绕过这个:
[Route("/")]
[ApiController]
public class UnauthorizedController : ControllerBase
{
    public UnauthorizedController()
    {

    }

    [HttpGet("/Account/Login")]
    [AllowAnonymous]
    public IActionResult Login()
    {
        HttpContext.Response.StatusCode = StatusCodes.Status401Unauthorized;
        return new ObjectResult(new
        {
            StatusCode = StatusCodes.Status401Unauthorized,
            Message = "Unauthorized",
        });
    }

}
我的设置有什么问题?
谢谢

最佳答案

你好,欢迎来到 StackOverflow 👋

您遇到的行为与您使用 ASP.NET Identity 的事实有关。
当您调用 services.AddIdentity ,在后台注册了一个基于 cookie 的身份验证方案并将其设置为默认质询方案,如代码 here on GitHub 中所示.

即使您自己注册了一个 cookie 身份验证方案并将其设置为默认方案,具体的默认方案 — 如 AuthenticateScheme , ChallengeScheme , SignInScheme ,等等……——优先考虑。 DefaultScheme仅当未设置特定时才由身份验证系统使用。

要回答您的问题,您可以使用帮助方法 services.ConfigureApplicationCookie 将配置设置应用于 ASP.NET 身份 cookie 选项。 ,像这样:

// ===== Add Identity ========
services.AddIdentity<User, IdentityRole>(o =>
{
    o.User.RequireUniqueEmail = true;
    o.Tokens.EmailConfirmationTokenProvider = "EMAILCONF";
    // I want to be able to resend an `Email` confirmation email
    // o.SignIn.RequireConfirmedEmail = true; 
}).AddRoles<IdentityRole>()
    .AddEntityFrameworkStores<ContestContext>()
    .AddTokenProvider<EmailConfirmationTokenProvider<User>>("EMAILCONF")
    .AddDefaultTokenProviders();

services.Configure<DataProtectionTokenProviderOptions>(o =>
    o.TokenLifespan = TimeSpan.FromHours(3)
);

services.Configure<EmailConfirmationTokenProviderOptions>(o =>
    o.TokenLifespan = TimeSpan.FromDays(2)
);

// ===== Configure Identity =======
service.ConfigureApplicationCookie(options =>
{
    options.Cookie.Name = "auth_cookie";
    options.Cookie.SameSite = SameSiteMode.None;
    options.LoginPath = new PathString("/api/contests");
    options.AccessDeniedPath = new PathString("/api/contests");

    // Not creating a new object since ASP.NET Identity has created
    // one already and hooked to the OnValidatePrincipal event.
    // See https://github.com/aspnet/AspNetCore/blob/5a64688d8e192cacffda9440e8725c1ed41a30cf/src/Identity/src/Identity/IdentityServiceCollectionExtensions.cs#L56
    options.Events.OnRedirectToLogin = context =>
    {
        context.Response.StatusCode = StatusCodes.Status401Unauthorized;
        return Task.CompletedTask;
    };
});

这也意味着您可以安全地删除添加基于 cookie 的身份验证方案的部分,因为这由 ASP.NET Identity 本身负责。

让我知道你怎样去!

关于asp.net-core-2.2 - 防止在 asp.net core 2.2 中重定向到/Account/Login,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53925609/

相关文章:

c# - 使用多个筛选器的 Azure 搜索

iis - 如何修复错误 "ANCM In-Process Handler Load Failure"?

c# - 如何在 ASP.NET Core MVC 中显示特定的 ModelState 错误?

c# - 未编译的局部 View 不继承自 ViewImports

c# - 无法从派生自 ActionFilterAttribute 的类访问存储库(或 DbContext)

asp.net-core - 带有 ASP.NET Core 2.2 的身份服务器 4

azure - IDX10214 : Audience validation failed. 受众: '[PII is hidden]'

azure-application-insights - 如何使用 Asp.Net-Core HealthChecks 设置 Application Insights

javascript - 根据经度和纬度计算最近位置(来自数据库)的算法

c# - AspNetCore 集成测试多个 WebApplicationFactory 实例?