CookieAuthenticationを使用するasp.net-coreとAngular 2アプリケーションがあります。Asp.net core、Angular 2. CookieAuthの問題
ユーザーがサインインしていない場合、すべてが正常に機能しています。ユーザーが保護されたリソースにアクセスしようとすると、Web APIから401ステータスコードが返されます。
[HttpGet("[action]")]
[Authorize(Policy = "AdminOnly")]
public IEnumerable<WeatherForecast> WeatherForecasts()
{
}
認証は、私がSignInAsyncメソッドを実行渡し
: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()
マイstartup.cs:私は次のエラーを取得するときである
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 });
として構成されています
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" });
});
}
}
私はそれが意味があると思います。 追加情報を提供する必要がある場合はお知らせください。 このエラーを解決するための助けに感謝します。
完璧だそれ!ありがとうございました。問題が解決しました。 –