2016-10-30 5 views
0

Ich habe eine asp.net-Kern und Angular 2-Anwendung, die CookieAuthentication verwendet.Asp.net Kern, Angular 2. CookieAuth Problem

Alles funktioniert wie erwartet, wenn der Benutzer nicht angemeldet ist. Ich bekomme einen 401-Statuscode von der Web-API zurück, wenn ein Benutzer versucht, auf eine geschützte Ressource zuzugreifen.

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

    } 

Wenn die Authentifizierung übergibt ich die SignInAsync Methode ausgeführt:

 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 }); 

Das ist, wenn ich die folgende Fehlermeldung erhalten:

fail: Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware[0] An unhandled exception has occurred while executing the request System.InvalidOperationException: No service for type 'Microsoft.AspNetCore.Identity.ISecurityStampValidator' has been registered. at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType) at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService[T](IServiceProvider provider) at Microsoft.AspNetCore.Identity.SecurityStampValidator.ValidatePrincipalAsync(CookieValidatePrincipalContext context) at Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationHandler.d__12.MoveNext()

Mein startup.cs ist konfiguriert als:

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" }); 
     }); 
    } 
} 

Ich hoffe, es macht Sinn. Bitte lassen Sie mich wissen, wenn ich zusätzliche Informationen bereitstellen muss. Jede Hilfe bei der Lösung dieses Fehlers wird sehr geschätzt.

Antwort

0

Das Problem wird von OnValidatePrincipal = SecurityStampValidator.ValidatePrincipalAsync verursacht. SecurityStampValidator.ValidatePrincipalAsync ist eine Erweiterungsmethode und erfordert ISecurityStampValidator. Da Sie keine Aspnet-Identität verwenden, gibt es keine registrierte Implementierung für ISecurityStampValidator.

diesen Code entfernen oder eigene ISecurityStampValidator implementieren und über Dependency Injection registrieren:

public class YourSecurityStampValidator : ISecurityStampValidator 
{ 
    .... 
} 

// Register it 

services.TryAddScoped<ISecurityStampValidator, YourSecurityStampValidator>(); 
+0

Das ist perfekt! Danke Adem. Problem gelöst. –