[英]ASP.NET Core 3.1: Web API identity sign in
我正在为我的 Web API 创建CookieAutentecation 登录。
我已阅读并遵循此处的官方文章,就我而言,我已正确完成所有操作。
但是当我在控制器中放置断点并检查HttpContext.User
,一切始终为空,没有用户名,没有声明,什么都没有。
我还需要什么才能完成这项工作? Web API 与 MVC 应用程序是否需要额外的步骤?
启动.cs:
public void ConfigureServices(IServiceCollection services)
{
services.AddCors();
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, act => {
act.LoginPath = "/api/login";
act.AccessDeniedPath = "/api/login";
act.SlidingExpiration = true;
});
services.AddControllers();
services.AddServices(); // <- Own app domain services
services.AddDataAccess(); // <- Own app domain data access
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseCors(
options => options.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()
);
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
api/登录
var user = new SecurityUser()
{
UserID = 123,
CompleteName = "Test user",
FirstName = "Test",
Email = "test.user@123.com"
};
var identity = user.ToClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme, 123);
await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(identity), new AuthenticationProperties()
{
AllowRefresh = true,
ExpiresUtc = DateTime.UtcNow.AddDays(7),
IsPersistent = true,
});
ToClaimsIdentity
扩展方法:
public static ClaimsIdentity ToClaimsIdentity(this SecurityUser user, string authenticantionType, int auditUserID)
{
var claims = new List<Claim>()
{
new Claim(ClaimTypes.NameIdentifier, user.UserID.ToString()),
new Claim(ClaimTypes.Email, user.Email),
new Claim(ClaimTypes.Name, user.FirstName),
new Claim(SecurityUserClaimTypes.AuditUserID, auditUserID.ToString())
};
var identity = new ClaimsIdentity(claims, authenticantionType);
return identity;
}
任何帮助将不胜感激。
谢谢你们的帮助!
我终于意识到这是客户的事情,我做了三件事:
.UseCors
方法中调用我的 Api 我允许凭据: .AllowCredentials()
WebAssemblyHttpMessageHandlerOptions.DefaultCredentials = FetchCredentialsOption.Include;
AddAuthentication...AddCookie
我添加了这个: options.Cookie.SameSite = SameSiteMode.Unspecified;
我不完全了解 SameSite...而且我还遇到了JSON Web Tokens (JWT) 。
但我不感兴趣,只要它有效。 ;-)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.