2017-09-06 4 views
1

Ich versuche, Cookie-Authentifizierung mit Identität und ef zu konfigurieren. Bis jetzt kann ich ein gültiges Set-Cookie in meiner Controller-Antwort haben. Der Browser sendet dieses Cookie zurück, aber der AuthorizeFilter leitet immer zur Anmeldeseite um, daher scheint die Authentifizierung nicht zu funktionieren. Was soll ich konfigurieren? meine ConfigureServices Hier ist bisher in Startup:AuthorizationAttribute in ASP.NET Core 2.0

public void ConfigureServices(IServiceCollection services) 
    { 
     services.AddMvc(); 

     services.AddCors(o => o.AddPolicy("Cors", builder => 
     { 
      builder.WithOrigins(Configuration["AllowedOrigins"].Split(",")) 
       .AllowAnyMethod() 
       .AllowCredentials() 
       .AllowAnyHeader(); 
     })); 

     services.AddDbContext<MyIdentityDbContext>(options => 
       options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))); 

     services.AddIdentity<IdentityUser, IdentityRole>() 
       .AddEntityFrameworkStores<MyIdentityDbContext>() 
       .AddDefaultTokenProviders(); 

     services.ConfigureApplicationCookie(options => { 
      if (!String.IsNullOrEmpty(Configuration["AuthCookieDomain"])) 
      { 
       options.Cookie.Domain = Configuration["AuthCookieDomain"]; 
      } 
      options.Cookie.Name = Configuration["AuthCookieName"]; 
      options.Cookie.HttpOnly = false; 
      options.Cookie.SameSite = SameSiteMode.None; 
     }); 
    } 

Dann meine Configure in Startup:

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

     app.UseCors("Cors"); 

     app.UseMvc(); 

     app.UseAuthentication(); 
    } 

Dann meine Aktion, die tatsächlich setzt erfolgreich das Cookie

// GET api/values 
    [HttpPost] 
    public async Task<ActionResult> Post([FromBody] AuthPost post) 
    { 
     if (post == null || String.IsNullOrEmpty(post.UserName) || String.IsNullOrEmpty(post.Password)) 
     { 
      return BadRequest(); 
     } 

     var result = await signInManager.PasswordSignInAsync(post.UserName, post.Password, true, false); 
     if (result.Succeeded) 
     { 
      return Ok(); 
     } 
     return Unauthorized(); 
    } 

Und schließlich, Mein anderes Attribut Aktion mit Autorisieren, das nicht funktioniert (Immer zur Anmeldung weiterleiten)

[HttpGet] 
    [Authorize] 
    public async Task<ActionResult> Get() 
    { 
     var user = await userManager.GetUserAsync(User); 
     return Ok(new { UserName = user.UserName }); 
    } 

Antwort

3

OK, ConfigureApplicationCookie ist der Weg zur Arbeit. Was verursacht das Problem war die falsche Reihenfolge der app.UseMvc(); und app.UseAuthentication();

app.UseAuthentication() muss vor app.UseMvc() aufgerufen werden!

Verwandte Themen