angular - Visual Studio如何自定义Angular/Asp.NetCore/IdentityServer登录模板?
问题描述
我在 Visual Studio 2019 中使用 Angular 模板创建了一个 .net core Web 应用程序。为了修改默认登录 UI,我在 ASP.NET Core 项目中使用了 Scaffold Identity: https ://docs.microsoft.com/en-us/aspnet/核心/安全/身份验证/支架身份?view=aspnetcore-3.1&tabs=visual-studio
我使用以下方法生成了登录页面:
public async Task<IActionResult> OnPostAsync(string returnUrl = null)
{
returnUrl = returnUrl ?? Url.Content("~/");
if (ModelState.IsValid)
{
// This doesn't count login failures towards account lockout
// To enable password failures to trigger account lockout, set lockoutOnFailure: true
var result = await _signInManager.PasswordSignInAsync(Input.Email, Input.Password, Input.RememberMe, lockoutOnFailure: false);
if (result.Succeeded)
{
_logger.LogInformation("User logged in.");
return LocalRedirect(returnUrl);
}
if (result.RequiresTwoFactor)
{
return RedirectToPage("./LoginWith2fa", new { ReturnUrl = returnUrl, RememberMe = Input.RememberMe });
}
if (result.IsLockedOut)
{
_logger.LogWarning("User account locked out.");
return RedirectToPage("./Lockout");
}
else
{
ModelState.AddModelError(string.Empty, "Invalid login attempt.");
return Page();
}
}
// If we got this far, something failed, redisplay form
return Page();
}
我成功更改了登录 UI。通过登录,_signInManager.PasswordSignInAsync 返回 True。但是重定向功能不起作用。ReturnUrl = ""
如何配置重定向 URL = http://localhost:4200 = Angular client url (as origin) ?
注意:我启动 Angular 项目并使用 Visual Studio 代码对其进行调试,并且 API(Asp.net 核心)在 Visual Studio 中单独运行(不像 VS 中的 Angular 模板)。
角边配置:
let applicationPaths: ApplicationPathsType = {
DefaultLoginRedirectPath: location.origin + '/',
ApiAuthorizationClientConfigurationUrl: `https://localhost:44326/_configuration/${ApplicationName}`,
Login: `authentication/${LoginActions.Login}`,
LoginFailed: `authentication/${LoginActions.LoginFailed}`,
LoginCallback: `authentication/${LoginActions.LoginCallback}`,
Register: `authentication/${LoginActions.Register}`,
Profile: `authentication/${LoginActions.Profile}`,
LogOut: `authentication/${LogoutActions.Logout}`,
LoggedOut: `authentication/${LogoutActions.LoggedOut}`,
LogOutCallback: `authentication/${LogoutActions.LogoutCallback}`,
LoginPathComponents: [],
LoginFailedPathComponents: [],
LoginCallbackPathComponents: [],
RegisterPathComponents: [],
ProfilePathComponents: [],
LogOutPathComponents: [],
LoggedOutPathComponents: [],
LogOutCallbackPathComponents: [],
IdentityRegisterPath: '/Identity/Account/Register',
IdentityManagePath: '/Identity/Account/Manage'
};
Asp.Net 核心启动:
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddCors(options =>
{
options.AddDefaultPolicy(
builder =>
{
builder.AllowAnyOrigin();
builder.AllowAnyMethod();
builder.AllowAnyOrigin();
builder.AllowAnyHeader();
});
});
// configure identity
services.AddDefaultIdentity<ApplicationUser>(options => options.SignIn.RequireConfirmedAccount = true)
.AddEntityFrameworkStores<ApplicationDbContext>();
services.AddIdentityServer()
.AddApiAuthorization<ApplicationUser, ApplicationDbContext>();
services.AddAuthentication()
.AddIdentityServerJwt();
services.AddControllersWithViews()
.AddNewtonsoftJson(options =>
options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver()
);
services.AddRazorPages();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IApiVersionDescriptionProvider provider)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
//app.UseDatabaseErrorPage();
}
else
{
app.UseExceptionHandler("/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseCors();
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseSwagger();
app.UseSwaggerUI(
options =>
{
// build a swagger endpoint for each discovered API version
foreach (var description in provider.ApiVersionDescriptions)
{
options.SwaggerEndpoint($"/swagger/{description.GroupName}/swagger.json", description.GroupName.ToUpperInvariant());
}
});
app.UseRouting();
app.UseAuthentication();
app.UseIdentityServer();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller}/{action=Index}/{id?}");
endpoints.MapRazorPages();
});
}
解决方案
我更改了 appsettings 中的配置,现在它可以工作了:
"IdentityServer": {
"Clients": {
"BauDrApi": {
"Profile": "SPA",
"RedirectUri": "http://localhost:4200/authentication/login-callback",
"logoutUri": "http://localhost:4200/authentication/logout-callback"
}
},
"Key": {
"Type": "Development"
}
},
推荐阅读
- java - 通过触摸屏幕移动矩形
- css - Boostrap 输入和导航栏
- yii2 - 在 Yii2 中创建依赖下拉列表
- php - 使用 Select 表单过滤使用 PHP 从 MySQL 查询的表
- javascript - 在 Python 中读取导出的 Javascript 对象
- struts2 - 如何将变量传递给 s:text?
- node.js - 需要帮助建立 nodejs (NPM) localhost https
- uwp - 升级到 Win10 1803 后无法“dotnet restore”,失败并出现错误 MSB4019,即使在空白项目上也是如此
- javascript - 无法在模式中刺激 Input 的变化:React-Redux
- android - 将按钮更改为以编程方式舍入