【问题标题】:ASP.NET core API - cookie authASP.NET 核心 API - cookie 身份验证
【发布时间】:2018-02-18 05:42:04
【问题描述】:

我尝试使用 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);
}

【问题讨论】:

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


    【解决方案1】:

    我通过设置 DefaultScheme 得到了它:

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

    【讨论】:

    • 谢谢,成功了!只是我得到的是 404 而不是 401 返回码。
    • cookieoptions 有一个 LoginPath 属性,默认为“/Account/Login” - 如果此路径不存在,由于重定向到不存在的页面,您会得到 404 而不是 401跨度>
    • 我以为我覆盖了这个:options.Events.OnRedirectToLogin...但是没有调用htis。
    • 在 AddIdentity 方法中尝试 options.Cookies.ApplicationCookie.AutomaticChallenge = false 或在 OnRedirectToLogin 中设置位置标头 :-)
    【解决方案2】:

    由于涉及到登录重定向,您将至少收到一次 401。 第二个结果应该有 'true' 作为输出。

    【讨论】:

      猜你喜欢
      • 2021-06-26
      • 2017-01-04
      • 2021-06-11
      • 2021-11-07
      • 2019-08-05
      • 2017-05-11
      • 2017-05-13
      • 2022-01-13
      • 1970-01-01
      相关资源
      最近更新 更多