我在Visual Studio 2019中用Angular模板创建了一个. net core Webapplication。为了修改默认登录UI,我使用了aspnet核心项目中的Scaffold标识:https://learn . Microsoft . com/en-us/aspnet/Core/security/authentic ation/Scaffold-Identity?view=aspnetcore-3.1
我使用以下方法生成了登录页面:
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();
}
我成功更改了登录用户界面。登录时,_signInManager.PasswordSignInAsync返回True。但是重定向功能不起作用。返回URL=“”
如何配置重定向 URL = http://localhost:4200 = Angular 客户端 URL(作为源)?
注意:我启动 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"
}
},