Asp.net core, Angular 2. CookieAuth issue

本文关键字:CookieAuth issue Angular net core Asp | 更新日期: 2023-09-27 18:15:31

我有一个使用CookieAuthentication的asp.net-core和Angular 2应用程序。

如果用户未登录,则一切正常。当用户试图访问受保护的资源时,我从web api返回401状态码。

    [HttpGet("[action]")]
    [Authorize(Policy = "AdminOnly")]
    public IEnumerable<WeatherForecast> WeatherForecasts()
    {
    }

当认证通过时,我运行SignInAsync方法:

        var claims = new[] {new Claim(ClaimTypes.Role, "Admin")};
        var identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
        HttpContext.Authentication.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme,
                                               new ClaimsPrincipal(identity),
                                               new AuthenticationProperties() { IsPersistent = false });

这是当我得到以下错误:

失败:Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware [0]在执行请求系统时发生了未处理的异常。InvalidOperationException: 类型没有服务"Microsoft.AspNetCore.Identity。ISecurityStampValidator'已被注册。Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService (IServiceProvider提供商,类型serviceType) at(IServiceProvider Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService [T]提供者)Microsoft.AspNetCore.Identity.SecurityStampValidator.ValidatePrincipalAsync (CookieValidatePrincipalContext上下文)Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationHandler.d__12.MoveNext ()

我的startup.cs配置为:

    public class Startup
    {
    public Startup(IHostingEnvironment env)
    {
        var builder = new ConfigurationBuilder()
            .SetBasePath(env.ContentRootPath)
            .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
            .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
            .AddEnvironmentVariables();
        Configuration = builder.Build();
    }
    public IConfigurationRoot Configuration { get; }
    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddAuthentication();
        // Polices
        services.AddAuthorization(options =>
        {
            // inline policies
            options.AddPolicy("AdminOnly", policy =>
            {
                policy.RequireClaim(ClaimTypes.Role, "Admin");
            });
        });
        // Add framework services.
        services.AddMvc();
    }
    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        loggerFactory.AddConsole(Configuration.GetSection("Logging"));
        loggerFactory.AddDebug();
        app.UseStaticFiles();
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
            app.UseWebpackDevMiddleware(new WebpackDevMiddlewareOptions
            {
                HotModuleReplacement = true
            });
        }
        app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            AutomaticAuthenticate = true,
            AutomaticChallenge = true,
            //Don't redirect to /Account/Login.
            Events = new CookieAuthenticationEvents
            {
                OnValidatePrincipal = SecurityStampValidator.ValidatePrincipalAsync,
                OnRedirectToLogin = ctx =>
                {
                    // If request comming from web api
                    // always return Unauthorized (401)
                    if (ctx.Request.Path.StartsWithSegments("/api") &&
                        ctx.Response.StatusCode == (int)HttpStatusCode.OK)
                    {
                        ctx.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
                    }
                    else
                    {
                        ctx.Response.StatusCode = (int)HttpStatusCode.NotFound;
                    }
                    return Task.FromResult(0);
                }
            },
            CookieHttpOnly = true
        });
        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
            routes.MapSpaFallbackRoute(
                name: "spa-fallback",
                defaults: new { controller = "Home", action = "Index" });
        });
    }
}

我希望这是有意义的。如果我需要提供任何额外的信息,请告诉我。

Asp.net core, Angular 2. CookieAuth issue

问题由OnValidatePrincipal = SecurityStampValidator.ValidatePrincipalAsync引起。SecurityStampValidator。ValidatePrincipalAsync是一个扩展方法,它需要ISecurityStampValidator。由于您不使用asp.net身份,因此没有ISecurityStampValidator的注册实现。

删除此代码或实现自己的ISecurityStampValidator并通过依赖注入注册:

public class YourSecurityStampValidator : ISecurityStampValidator
{
    ....
}
// Register it 
services.TryAddScoped<ISecurityStampValidator, YourSecurityStampValidator>();