以下是我的工作內容:我學到的大部分內容都來自this microsoft doc,但正如您所說,文檔似乎並未將您帶到這裏。
在startup.cs
public void ConfigureServices(IServiceCollection services)
{
...
services.AddAuthentication("ACE_AUTH")
.AddCookie("ACE_AUTH", options => {
options.AccessDeniedPath = "/api/Auth/Forbidden";
options.LoginPath = "/";
options.Cookie.Expiration = new TimeSpan(7,0,0,0);
});
}
public void Configure(IApplicationBuilder app,
IHostingEnvironment env,
ILoggerFactory loggerFactory)
{
...
app.UseAuthentication();
}
然後在你的控制器處理
認證:
[HttpPost()]
[Route("api/[Controller]/[Action]/")]
public async Task<JsonResult> Login([FromBody]Dictionary<string, string> loginData)
{
try
{
var loggedIn = true;
if (loggedIn)
{
var claims = new List<Claim> {
new Claim(ClaimTypes.Name, "John Doe")
};
var identity = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme);
identity.AddClaims(claims);
ClaimsPrincipal principal = new ClaimsPrincipal(identity);
await HttpContext.SignInAsync(
"ACE_AUTH",
principal,
new AuthenticationProperties
{
IsPersistent = true,
ExpiresUtc = DateTime.UtcNow.AddDays(7)
});
}
return new JsonResult(logRtn);
}
catch (Exception ex)
{
return new JsonResult(ex.Message);
}
}
如果你可以驗證並分配的loggedIn您的身份驗證請求的結果,你應該能夠將聲明存儲在Cookie中。然後,您可以使用以下方式在控制器中回想可能正在執行授權/調用值的聲明:
[HttpGet("[Action]", Name = "GetSomething")]
[Route("[Action]")]
public JsonResult something()
{
try
{
var loggedInUser = HttpContext.User;
var claym = loggedInUser.Claims.FirstOrDefault(x => x.Type == ClaimTypes.Name);
if (claym != null)
{
return new JsonResult(claym.Value);
// returns "John Doe"
}
else
{
return new JsonResult("");
}
}
catch (Exception ex)
{
return new JsonResult(ex.Message);
}
}
面臨同樣的問題。你弄明白了嗎? – Clement
還沒有。我現在不得不轉向其他事情,但我很快就會回頭看看。 –