Identityserver4 无法联系到控制器
我有一个Angular 6应用程序可在访问,它与另一台服务器进行通信,以便在上进行身份验证和授权 我能够在客户端应用程序和身份验证服务器之间建立通信。但是,在成功验证用户身份而不是重定向到同意页面后,它会返回到服务器登录页面 我正在使用VS 2017,asp.net core 2.1和IdentityServer 4 以下是身份验证服务器的启动类Identityserver4 无法联系到控制器,identityserver4,angular6,asp.net-core-2.1,Identityserver4,Angular6,Asp.net Core 2.1,我有一个Angular 6应用程序可在访问,它与另一台服务器进行通信,以便在上进行身份验证和授权 我能够在客户端应用程序和身份验证服务器之间建立通信。但是,在成功验证用户身份而不是重定向到同意页面后,它会返回到服务器登录页面 我正在使用VS 2017,asp.net core 2.1和IdentityServer 4 以下是身份验证服务器的启动类 public class Startup { private readonly IHostingEnvironment _environmen
public class Startup
{
private readonly IHostingEnvironment _environment;
public Startup(IHostingEnvironment env)
{
JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
_environment = env;
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);
if (env.IsDevelopment())
{
// For more details on using the user secret store see https://go.microsoft.com/fwlink/?LinkID=532709
builder.AddUserSecrets<Startup>();
}
builder.AddEnvironmentVariables();
Configuration = builder.Build();
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
var stsConfig = Configuration.GetSection("stsConfig");
var userDbConnString = Configuration["ConnectionStrings:DefaultConnection"];
var useLocalCertStore = Convert.ToBoolean(Configuration["UseLocalCertStore"]);
var certificateThumbprint = Configuration["CertificateThumbprint"];
var migrationsAssembly = typeof(UserDbContext).GetTypeInfo().Assembly.GetName().Name;
X509Certificate2 cert;
if (_environment.IsProduction())
{
if (useLocalCertStore)
{
using (X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine))
{
store.Open(OpenFlags.ReadOnly);
var certs = store.Certificates.Find(X509FindType.FindByThumbprint, certificateThumbprint, false);
cert = certs[0];
store.Close();
}
}
else
{
// Azure deployment, will be used if deployed to Azure
var vaultConfigSection = Configuration.GetSection("Vault");
var keyVaultService = new KeyVaultCertificateService(vaultConfigSection["Url"], vaultConfigSection["ClientId"], vaultConfigSection["ClientSecret"]);
cert = keyVaultService.GetCertificateFromKeyVault(vaultConfigSection["CertificateName"]);
}
}
else
{
cert = new X509Certificate2(Path.Combine(_environment.ContentRootPath, "localhost.pfx"), "##Rojutet11");
}
services.AddDbContext<UserDbContext>(options =>
options.UseSqlServer(Configuration["ConnectionStrings:DefaultConnection"]));
services.Configure<StsConfig>(Configuration.GetSection("StsConfig"));
services.Configure<EmailSettings>(Configuration.GetSection("EmailSettings"));
services.AddSingleton<LocService>();
services.AddLocalization(options => options.ResourcesPath = "Resources");
//services.AddAuthentication();
services.AddAuthentication(
//o => {
// o.DefaultScheme = IdentityServerAuthenticationDefaults.AuthenticationScheme;
// o.DefaultAuthenticateScheme = IdentityServerAuthenticationDefaults.AuthenticationScheme;
//}
);
services.AddIdentity<ApplicationUser, UserRole>(config =>
{
config.SignIn.RequireConfirmedEmail = true;
}).AddEntityFrameworkStores<UserDbContext>()
.AddDefaultTokenProviders();
services.Configure<RequestLocalizationOptions>(
options =>
{
var supportedCultures = new List<CultureInfo>
{
new CultureInfo("en-US"),
new CultureInfo("de-CH"),
new CultureInfo("fr-CH"),
new CultureInfo("it-CH")
};
options.DefaultRequestCulture = new RequestCulture(culture: "en-US", uiCulture: "en-US");
options.SupportedCultures = supportedCultures;
options.SupportedUICultures = supportedCultures;
var providerQuery = new LocalizationQueryProvider
{
QueryParameterName = "ui_locales"
};
// Cookie is required for the logout, query parameters at not supported with the endsession endpoint
// Only works in the same domain
var providerCookie = new LocalizationCookieProvider
{
CookieName = "defaultLocale"
};
// options.RequestCultureProviders.Insert(0, providerCookie);
options.RequestCultureProviders.Insert(0, providerQuery);
});
//services.AddCors();
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
.AddViewLocalization()
.AddDataAnnotationsLocalization(options =>
{
options.DataAnnotationLocalizerProvider = (type, factory) =>
{
var assemblyName = new AssemblyName(typeof(SharedResource).GetTypeInfo().Assembly.FullName);
return factory.Create("SharedResource", assemblyName.Name);
};
});
//services.AddAntiforgery(
// options =>
// {
// options.Cookie.Name = "_af";
// options.Cookie.HttpOnly = true;
// options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
// options.HeaderName = "X-XSRF-TOKEN";
// });
services.AddTransient<IProfileService, IdentityWithAdditionalClaimsProfileService>();
services.AddTransient<IEmailSender, AuthMessageSender>();
services.AddIdentityServer(
//x=>x.IssuerUri="https://localhost:44338"
).AddSigningCredential(cert)
.AddDefaultEndpoints()
.AddConfigurationStore(options =>
{
options.ConfigureDbContext = builder =>
builder.UseSqlServer(userDbConnString, db => db.MigrationsAssembly(migrationsAssembly));
})
.AddOperationalStore(options => {
options.ConfigureDbContext = builder =>
builder.UseSqlServer(userDbConnString, db => db.MigrationsAssembly(migrationsAssembly));
}).AddProfileService<IdentityWithAdditionalClaimsProfileService>();
services.AddDbContext<UserDbContext>(options =>
options.UseSqlServer(userDbConnString, b => b.MigrationsAssembly("KAMAAG.Data")));
services.Configure<MvcOptions>(options =>
{
options.Filters.Add(new RequireHttpsAttribute());
});
services.AddTransient<IEmailSender, AuthMessageSender>();
services.AddTransient<ISmsSender, AuthMessageSender>();
services.Configure<AuthMessageSenderOptions>(Configuration);
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
loggerFactory.AddConsole(LogLevel.Trace);
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
var locOptions = app.ApplicationServices.GetService<IOptions<RequestLocalizationOptions>>();
app.UseRequestLocalization(locOptions.Value);
app.UseCors(builder =>
builder
.WithOrigins("https://localhost:44391")
.AllowAnyMethod()
.AllowCredentials()
.AllowAnyHeader());
app.UseCsp(opts => opts.DefaultSources(directive => directive.Self())
.ImageSources(directive => directive.Self()
.CustomSources("*"))
.ScriptSources(directive => directive.Self()
.UnsafeInline())
.StyleSources(directive => directive.Self()
.UnsafeInline()));
app.UseStaticFiles();
app.UseAuthentication();
app.UseIdentityServer();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
}
公共类启动
{
私有只读IHostingEnvironment\u环境;
公共启动(IHostingEnvironment环境)
{
JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
_环境=环境;
var builder=new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile(“appsettings.json”,可选:false,reloadOnChange:true)
.AddJsonFile($“appsettings.{env.EnvironmentName}.json”,可选:true);
if(env.IsDevelopment())
{
//有关使用用户机密存储的更多详细信息,请参阅https://go.microsoft.com/fwlink/?LinkID=532709
builder.AddUserSecrets();
}
builder.AddEnvironmentVariables();
Configuration=builder.Build();
}
公共IConfiguration配置{get;}
//此方法由运行时调用。请使用此方法将服务添加到容器中。
public void配置服务(IServiceCollection服务)
{
var stsConfig=Configuration.GetSection(“stsConfig”);
var userDbConnString=Configuration[“ConnectionString:DefaultConnection”];
var useLocalCertStore=Convert.ToBoolean(配置[“useLocalCertStore”]);
var certificateThumbprint=配置[“certificateThumbprint”];
var migrationassembly=typeof(UserDbContext).GetTypeInfo().Assembly.GetName().Name;
X509证书2证书;
if(_environment.IsProduction())
{
如果(使用LocalCertStore)
{
使用(X509Store store=new X509Store(StoreName.My,StoreLocation.LocalMachine))
{
打开(OpenFlags.ReadOnly);
var certs=store.Certificates.Find(X509FindType.FindByThumbprint,certificateThumbprint,false);
证书=证书[0];
store.Close();
}
}
其他的
{
//Azure部署,如果部署到Azure,将使用
var vaultConfigSection=Configuration.GetSection(“Vault”);
var keyVaultService=new KeyVaultCertificateService(vaultConfigSection[“Url”]、vaultConfigSection[“ClientId”]、vaultConfigSection[“ClientSecret”]);
cert=keyVaultService.GetCertificateFromKeyVault(vaultConfigSection[“CertificateName”]);
}
}
其他的
{
cert=new X509Certificate2(Path.Combine(_environment.ContentRootPath,“localhost.pfx”),“##Rojutet11”);
}
services.AddDbContext(选项=>
使用SQLServer(配置[“ConnectionString:DefaultConnection”]);
services.Configure(Configuration.GetSection(“StsConfig”);
services.Configure(Configuration.GetSection(“EmailSettings”);
services.AddSingleton();
services.AddLocalization(options=>options.ResourcesPath=“Resources”);
//services.AddAuthentication();
services.AddAuthentication(
//o=>{
//o.DefaultScheme=IdentityServerAuthenticationDefaults.AuthenticationScheme;
//o.DefaultAuthenticateScheme=IdentityServerAuthenticationDefaults.AuthenticationScheme;
//}
);
服务。额外性。我将整个angularclient项目换成了本教程中的一个项目,进行了必要的改装,出现了我的同意页面,这让我有点失望。我认为AngularCLI方法提供了一个更平滑的过程。也许我只是在做一些看起来非常愚蠢的事情我是唯一有这个问题的人你能发布AccountController登录方法吗?@ademcaglin刚刚添加了登录方法。
public class Clients
{
public static IEnumerable<Client> Get()
{
return new List<Client>
{
new Client
{
ClientName = "kamaagwebclient",
ClientId = "kamaagwebclient",
AccessTokenType = AccessTokenType.Reference,
AccessTokenLifetime = 330,// 330 seconds, default 60 minutes
IdentityTokenLifetime = 30,
AllowedGrantTypes = GrantTypes.Implicit,
AllowAccessTokensViaBrowser = true,
AllowRememberConsent=true,
RedirectUris = new List<string>
{
"https://localhost:44391",
"https://localhost:44391/silent-renew.html"
},
PostLogoutRedirectUris = new List<string>
{
"https://localhost:44391/unauthorized",
"https://localhost:44391"
},
AllowedCorsOrigins = new List<string>
{
"https://localhost:44391",
"http://localhost:44391"
},
AllowedScopes = new List<string>
{
IdentityServerConstants.StandardScopes.OpenId,
IdentityServerConstants.StandardScopes.Email,
IdentityServerConstants.StandardScopes.Profile,
"resourcescope",
"securefilescope",
"kamaagresource",
"securedfiles",
"role"
},
RequireConsent=true
}
};
}
}
[HttpGet]
[AllowAnonymous]
public async Task<IActionResult> Login(string returnUrl = null)
{
var context = await _interaction.GetAuthorizationContextAsync(returnUrl);
if (context?.IdP != null)
{
// if IdP is passed, then bypass showing the login screen
return ExternalLogin(context.IdP, returnUrl);
}
var vm = await BuildLoginViewModelAsync(returnUrl, context);
if (vm.EnableLocalLogin == false && vm.ExternalProviders.Count() == 1)
{
// only one option for logging in
return ExternalLogin(vm.ExternalProviders.First().AuthenticationScheme, returnUrl);
}
return View(vm);
}
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Login(LoginInputModel model)
{
var returnUrl = model.ReturnUrl;
ViewData["ReturnUrl"] = returnUrl;
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(model.Email, model.Password, model.RememberLogin, lockoutOnFailure: false);
if (!result.Succeeded)
{
Console.Write("Failed to authenticate");
}
if (result.Succeeded)
{
_logger.LogInformation(1, "User logged in.");
return RedirectToLocal(returnUrl);
}
if (result.RequiresTwoFactor)
{
return RedirectToAction(nameof(VerifyCode), new { ReturnUrl = returnUrl, RememberMe = model.RememberLogin });
}
if (result.IsLockedOut)
{
_logger.LogWarning(2, "User account locked out.");
return View("Lockout");
}
else
{
ModelState.AddModelError(string.Empty, "Invalid login attempt.");
return View(await BuildLoginViewModelAsync(model));
}
}
// If we got this far, something failed, redisplay form
return View(await BuildLoginViewModelAsync(model));
}