Asp.net core 我面临的问题是在注册时设置重定向url以从identityserver4响应页面
我将IdentityServer4(3.1.1)和ASP.NET Core 3.1与Razor页面一起使用 下面是我的startup.cs代码Asp.net core 我面临的问题是在注册时设置重定向url以从identityserver4响应页面,asp.net-core,react-router,identityserver4,asp.net-core-3.1,Asp.net Core,React Router,Identityserver4,Asp.net Core 3.1,我将IdentityServer4(3.1.1)和ASP.NET Core 3.1与Razor页面一起使用 下面是我的startup.cs代码 public void ConfigureServices(IServiceCollection services) { var migrationsAssembly = typeof(Startup).GetTypeInfo().Assembly.GetName().Name; var connectionSt
public void ConfigureServices(IServiceCollection services)
{
var migrationsAssembly = typeof(Startup).GetTypeInfo().Assembly.GetName().Name;
var connectionString = Configuration.GetConnectionString("DefaultConnection");
services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(connectionString));
services.AddIdentity<ApplicationUser, IdentityRole>(option =>
{
option.User = new UserOptions { RequireUniqueEmail = true };
option.Password.RequireDigit = false;
option.Password.RequiredLength = 8;
option.Password.RequiredUniqueChars = 0;
option.Password.RequireLowercase = false;
option.Password.RequireNonAlphanumeric = false;
option.Password.RequireUppercase = false;
option.User.RequireUniqueEmail = true;
option.Tokens.EmailConfirmationTokenProvider = TokenOptions.DefaultEmailProvider;
option.Tokens.PasswordResetTokenProvider = TokenOptions.DefaultEmailProvider;
})
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
services.Configure<IISOptions>(iis =>
{
iis.AuthenticationDisplayName = "Windows";
iis.AutomaticAuthentication = false;
});
services.AddControllersWithViews();
var builder = services.AddIdentityServer(options =>
{
options.Events.RaiseErrorEvents = true;
options.Events.RaiseInformationEvents = true;
options.Events.RaiseFailureEvents = true;
options.Events.RaiseSuccessEvents = true;
options.UserInteraction.LoginUrl = "/Identity/Account/Login";
options.UserInteraction.LogoutUrl = "/Identity/Account/Logout";
options.Authentication = new AuthenticationOptions()
{
CookieLifetime = TimeSpan.FromHours(10), // ID server cookie timeout set to 10 hours
CookieSlidingExpiration = true
};
})
.AddConfigurationStore(options =>
{
options.ConfigureDbContext = b =>
b.UseSqlServer(connectionString, sql => sql.MigrationsAssembly(migrationsAssembly));
})
// this adds the operational data from DB (codes, tokens, consents)
.AddOperationalStore(options =>
{
options.ConfigureDbContext = b =>
b.UseSqlServer(connectionString, sql => sql.MigrationsAssembly(migrationsAssembly));
// this enables automatic token cleanup. this is optional.
options.EnableTokenCleanup = false;
options.TokenCleanupInterval = 3600;
})
.AddAspNetIdentity<ApplicationUser>();
services.AddRazorPages(options =>
{
//options.AllowAreas = true;
options.Conventions.AuthorizeAreaFolder("Identity", "/Account/Manage");
options.Conventions.AuthorizeAreaPage("Identity", "/Account/Logout");
});
//configures the application cookie to redirect on challenge, etc.
services.ConfigureApplicationCookie(options =>
{
options.LoginPath = $"/Identity/Account/Login";
options.LogoutPath = $"/Identity/Account/Logout";
options.AccessDeniedPath = $"/Identity/Account/AccessDenied";
});
builder.AddDeveloperSigningCredential();
services.AddTransient<IEmailSender, EmailSender>();
services.Configure<AuthMessageSenderOptions>(Configuration);
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
InitializeDatabase(app);
app.UseCookiePolicy();
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.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseCors();
app.UseIdentityServer();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapRazorPages();
});
}
下面是Authorize.js代码
var settings = {
authority: "https://localhost:44306",
client_id: "Application.UI",
redirect_uri: "http://localhost:3000/authentication/login-callback",
response_type: "code",
scope: "openid profile WebApi",
post_logout_redirect_uri:
"http://localhost:3000/authentication/logout-callback"
};
单击注册链接时,导航到下面的URL
当最后点击注册表时,将导航到下面的链接
虽然它应该是
因此,它可以导航到正确的URL,返回URL为
使用localhost或其他直接链接时,提示以下错误
An unhandled exception occurred while processing the request.
InvalidOperationException:提供的URL不是本地的。如果没有主机/授权部分,则具有绝对路径的URL被视为本地URL。使用虚拟路径(“~/”)的URL也是本地的。
Microsoft.AspNetCore.Mvc.Infrastructure.LocalRedirectResultExecutor.ExecuteAsync(ActionContext上下文,LocalRedirectResult)
堆栈查询Cookies头路由
InvalidOperationException:提供的URL不是本地的。如果没有主机/授权部分,则具有绝对路径的URL被视为本地URL。使用虚拟路径(“~/”)的URL也是本地的。
Microsoft.AspNetCore.Mvc.Infrastructure.LocalRedirectResultExecutor.ExecuteAsync(ActionContext上下文,LocalRedirectResult)
Microsoft.AspNetCore.Mvc.LocalRedirectResult.ExecuteSultAsync(ActionContext上下文)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g|u Logged | 21|0(ResourceInvoker invoker,IActionResult)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g_|29_0(ResourceInvoker invoker,Task lastTask,State next,Scope Scope,object State,bool isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResultExecutedContextSealed上下文)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.ResultNext(ref状态next、ref范围、ref对象状态、ref bool已完成)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeResultFilters()
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g_|24_0(ResourceInvoker invoker,Task lastTask,State next,Scope Scope,object State,bool isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceExecutedContextSealed上下文)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(ref状态Next、ref作用域、ref对象状态、ref bool已完成)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g_|19_0(ResourceInvoker invoker,Task lastTask,State next,Scope Scope,object State,bool isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g|u Logged|17|u 1(ResourceInvoker invoker)
Microsoft.AspNetCore.Routing.EndpointMiddleware.g_uwaitRequestTask | 6_0(端点端点、任务请求任务、ILogger记录器)
Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext上下文)
IdentityServer4.Hosting.IdentityServerMiddleware.Invoke(HttpContext上下文、IEndpointRouter路由器、IUserSession会话、IEventService事件)
IdentityServer4.Hosting.MutualTlsTokenEndpointMiddleware.Invoke(HttpContext上下文,IAAuthenticationSchemeProvider方案)
Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext上下文)
IdentityServer4.Hosting.BaseUrlMiddleware.Invoke(HttpContext上下文)
Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore.MigrationsEndPointMiddleware.Invoke(HttpContext上下文)
Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore.DatabaseErrorPageMiddleware.Invoke(HttpContext HttpContext)
Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore.DatabaseErrorPageMiddleware.Invoke(HttpContext HttpContext)
Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext上下文)
显示原始异常详细信息
System.InvalidOperationException:提供的URL不是本地URL。如果没有主机/授权部分,则具有绝对路径的URL被视为本地URL。使用虚拟路径(“~/”)的URL也是本地的。
位于Microsoft.AspNetCore.Mvc.Infrastructure.LocalRedirectResultExecutor.ExecuteAsync(ActionContext上下文,LocalRedirectResult)
位于Microsoft.AspNetCore.Mvc.LocalRedirectResult.ExecuteSultAsync(ActionContext上下文)
在Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g|u|21_0(ResourceInvoker invoker,IActionResult)
在Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g_uwaiting | 29_0[TFilter,TFilterAsync](ResourceInvoker invoker,Task lastTask,State next,Scope Scope,Object State,Boolean isCompleted)
位于Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResultExecutedContextSealed上下文)
在Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.ResultNext[TFilter,TFilterAsync](状态和下一步,范围和范围,对象和状态,布尔值和已完成)
在Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeResultFilters()中
---来自引发异常的上一个位置的堆栈结束跟踪---
在Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g_|24_0(ResourceInvoker invoker、Task lastTask、State next、Scope Scope、Object State、Boolean isCompleted)
位于Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceExecutedContextSealed上下文)
位于Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(状态和下一步、范围和范围、对象和状态、布尔值和isCompleted)
在Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g_|19_0(ResourceInvoker invoker、Task lastTask、State next、Scope Scope、Object State、Boolean isCompleted)
在Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g|u记录| 17|u 1(ResourceInvoker invoker)
位于Microsoft.AspNetCore.Routing.EndpointMiddleware.g_uwaitRequestTask | 6_0(端点、任务请求任务、ILogger记录器)
位于Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext上下文)
在IdentityServer4.Hosting.IdentityServerMiddleware.Invoke(HttpContext上下文、IEndpointRouter路由器、IUserSession会话、IEventServic
An unhandled exception occurred while processing the request.
public async Task<IActionResult> OnPostAsync(string returnUrl = null)
{
returnUrl = returnUrl ?? Url.Content("/Identity/Account/Login");
ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();
if (ModelState.IsValid)
{
var user = new ApplicationUser { UserName = Input.Email, Email = Input.Email };
var result = await _userManager.CreateAsync(user, Input.Password);
if (result.Succeeded)
{
_logger.LogInformation("User created a new account with password.");
var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code));
var callbackUrl = Url.Page(
"/Account/ConfirmEmail",
pageHandler: null,
values: new { area = "Identity", userId = user.Id, code = code },
protocol: Request.Scheme);
await _emailSender.SendEmailAsync(Input.Email, "Confirm your email",
$"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.");
if (_userManager.Options.SignIn.RequireConfirmedAccount)
{
return RedirectToPage("RegisterConfirmation", new { email = Input.Email });
}
else
{
// this will redirect mannually to the address where you suppose to redirect
return Redirect("http://localhost:3000");
}
}
foreach (var error in result.Errors)
{
ModelState.AddModelError(string.Empty, error.Description);
}
}
// If we got this far, something failed, redisplay form
return Page();
}