ASP.NET核心API - cookie身份验证

时间:2018-02-13 12:29:51

标签: c# authentication cookies asp.net-core

我尝试使用Cookie令牌保护我的API。

一切正常,我尝试登录我生成一个cookie由浏览器设置cookie,然后我尝试请求/ auth / info2。 cookie已发送但我收到401错误。

你可以给我一个暗示吗?如何解决这个问题呢?

目前我的代码如下:

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<ApplicationDbContext>(options =>
        {
            //options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))
            options.UseInMemoryDatabase("som_tmp");
        }
    );

    services.AddTransient<IEmailSender, EmailSender>();
    services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

    services.AddIdentity<SomUser, IdentityRole>()
        .AddEntityFrameworkStores<ApplicationDbContext>();

    services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
        .AddCookie(o =>
        {
            o.Cookie = new CookieBuilder()
            {
                HttpOnly = false,
                Name = "som_session"
            };
        });

    services.ConfigureApplicationCookie(options =>
    {
        options.Events.OnRedirectToLogin = context =>
        {
            context.Response.StatusCode = 401;
            return Task.CompletedTask;
        };
    });

    services.AddAuthorization();

    services.AddMvc();
    services.AddOData();
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ApplicationDbContext context, UserManager<SomUser> userManager, RoleManager<IdentityRole> roleManager)
{
    var model = GetEdmModel(app.ApplicationServices);

    app.UseDefaultFiles();

    app.UseStaticFiles(new StaticFileOptions
    {
        ServeUnknownFileTypes = true
    });

    app.UseAuthentication();

    app.UseMvc(routebuilder =>
    {
        routebuilder.Count().Filter().OrderBy().Expand().Select().MaxTop(null);
        routebuilder.MapODataServiceRoute("oData", "oData", model);
    });


    DbInitializer.Initialize(context, userManager, roleManager);
}

控制器:

[Authorize]
[HttpGet("info2")]
public async Task<JsonResult> Get2()
{
    return Json("Info2");
    //return Json( await GetCurrentUser() );
}

[AllowAnonymous]
[HttpPost("login2")]
public async Task<JsonResult> Login2([FromBody] LoginDto loginDto)
{
    var user = await _userManager.FindByNameAsync(loginDto.Username);
    if (user == null)
    {
        user = await _userManager.FindByEmailAsync(loginDto.Username);
    }

    if (user != null)
    {
        var passwordHasher = new PasswordHasher<SomUser>();
        if (passwordHasher.VerifyHashedPassword(user, user.PasswordHash, loginDto.Password) == PasswordVerificationResult.Success)
        {
            var identity = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme);
            identity.AddClaim(new Claim(ClaimTypes.Name, user.UserName));
            await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(identity));
            return Json(true);
        }
    }

    return Json(false);
}

2 个答案:

答案 0 :(得分:2)

我使用它来设置DefaultScheme:

services.AddAuthentication(o =>
{
    o.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    o.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    o.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
})

答案 1 :(得分:0)

自从重定向登录后,您将至少收到401次。 第二个结果应该是'true'作为输出。