【发布时间】: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