我在Visual Studio 2019中使用Angular模板创建了.net核心Web应用程序。为了修改默认的登录UI,我在ASP.NET Core项目中使用了Scaffold Identity:https://docs.microsoft.com/en-us/aspnet/core/security/authentication/scaffold-identity?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客户端URL(作为源)?
注意:我启动Angular Project并使用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"
}
},