我已经设置了一个dotnet角度项目,然后在StartUp.cs文件中实现了身份验证,如下所示。
public void ConfigureServices(IServiceCollection services)
{
services.AddScoped<IPasswordHasher<CustomUser>,
PasswordHasherWithOldMembershipSupport<CustomUser>>();
services.AddIdentity<CustomUser, IdentityRole>()
.AddEntityFrameworkStores<AuthenticationContext<CustomUser>>()
.AddDefaultUI()
.AddDefaultTokenProviders();
var connection = configuration.GetConnection("Authentication");
services.AddDbContext<AuthenticationContext<CustomUser>>(options =>
options.UseSqlServer(connection));
services.AddTransient<IEmailSender, AuthMessageSender>();
services.AddTransient<AuthMessageSender.ISmsSender, AuthMessageSender>();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
...
app.UseAuthentication();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller}/{action=Index}/{id?}");
});
...
}
IdentityHostingStartUp.cs文件,该文件在启动时运行以配置身份验证。
public class IdentityHostingStartup : IHostingStartup
{
public void Configure(IWebHostBuilder builder)
{
builder.ConfigureServices((context, services) =>
{
services.AddAuthentication();
services.Configure<IdentityOptions>(options =>
{
// Password settings.
options.Password.RequireDigit = true;
options.Password.RequireLowercase = true;
options.Password.RequireNonAlphanumeric = true;
options.Password.RequireUppercase = true;
options.Password.RequiredLength = 6;
options.Password.RequiredUniqueChars = 1;
// Lockout settings.
options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(5);
options.Lockout.MaxFailedAccessAttempts = 5;
options.Lockout.AllowedForNewUsers = true;
// User settings.
options.User.RequireUniqueEmail = false;
});
services.ConfigureApplicationCookie(options =>
{
// Cookie settings
options.Cookie.HttpOnly = true;
options.ExpireTimeSpan = TimeSpan.FromMinutes(15);
options.LoginPath = "/Identity/Account/Login";
options.AccessDeniedPath = "/Identity/Account/AccessDenied";
options.SlidingExpiration = true;
});
});
}
}
如果用户未登录,则我的角度代码中有一个自定义重定向,可转到身份验证页面。
import { Inject, Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable()
export class AuthService {
constructor(http: HttpClient, @Inject('BASE_URL') baseUrl: string) {
http.get<Boolean>(baseUrl + "api/Home/Status").subscribe((authenticated) => {
if (!authenticated) {
window.location.href = baseUrl + "/Identity/Account/Login";
}
});
}
最后,我的HomeController代码检查登录用户的身份验证状态。
[HttpGet("[action]"), AllowAnonymous]
public Boolean Status()
{
var user = _accessor.HttpContext.User;
return User.Identity.IsAuthenticated;
}
状态(或任何其他称为api控制器操作)操作始终具有空用户名,用户声明,并且即使登录后,IsAuthenticated也始终返回false。
这把我逼到了墙上。我已经阅读了尽可能多的帖子,并尝试了尽可能多的选择,但似乎没有任何效果。
在某个时候,我注意到用户名已按预期填写。我以为它解决了。但是,此后它就停止了工作,即使我没有进行任何更改也无法解决此问题。