我想使用OpenIddict实现OpenIdConnect / Oauth2服务器,以保护.NET核心API应用程序。我见过的大多数例子都将它们作为单独的项目来实现。
客户端应用程序是SPA,我们使用隐式流程。
我的解决方案基于OpenIddict示例中显示的代码: https://github.com/openiddict/openiddict-samples
对于我正在进行的项目,理想情况下,Auth服务器和API将使用相同的端口并位于同一个项目中。 (客户的要求之一是他们不希望其他服务器配置,因为他们拥有API资源并且它将位于同一服务器上)
我已经配置了OpenIddict并将其与我们的API项目相结合。几乎所有工作都正常 - API端点受[Authorize]属性保护,并阻止访问受保护的API端点。但是,当API资源受到保护时,返回的结果是Auth服务器本身的HTML登录页面,而不是返回401 Unauthorized HTTP状态代码。
以下是我的Startup.cs文件中的相关设置代码:
// 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();
app.UseApplicationInsightsRequestTelemetry();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
app.UseBrowserLink();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseApplicationInsightsExceptionTelemetry();
app.UseStaticFiles();
app.UseIdentity();
app.UseCors("AllowAll");
//app.UseCors(builder =>
//{
// builder.AllowAnyOrigin();//)WithOrigins("http://localhost:9000");
// builder.WithMethods("GET","POST", "PUT", "DELETE", "OPTIONS");
// builder.WithHeaders("Authorization");
//});
app.UseWhen(context => !context.Request.Path.StartsWithSegments("/api"), branch =>
{
branch.UseIdentity();
});
app.UseWhen(context => context.Request.Path.StartsWithSegments("/api"), branch =>
{
branch.UseOAuthValidation();
});
app.UseOpenIddict();
#region Adding resource config here (api)
// Add external authentication middleware below. To configure them please see http://go.microsoft.com/fwlink/?LinkID=532715
app.UseOAuthIntrospection(options =>
{
options.AutomaticAuthenticate = true;
options.AutomaticChallenge = true;
options.Authority = "http://localhost:5000";
options.Audiences.Add("resource-server-1");
options.ClientId = "resource-server-1";
options.ClientSecret = "846B62D0-DEF9-4215-A99D-86E6B8DAB342";
});
//app.UseCors(builder => {
// builder.WithOrigins("http://localhost:9000");
// builder.WithMethods("GET");
// builder.WithHeaders("Authorization");
//});
#endregion
app.UseMvcWithDefaultRoute();
// Seed the database with the sample applications.
// Note: in a real world application, this step should be part of a setup script.
InitializeAsync(app.ApplicationServices, CancellationToken.None).GetAwaiter().GetResult();
}
private async Task InitializeAsync(IServiceProvider services, CancellationToken cancellationToken)
{
// Create a new service scope to ensure the database context is correctly disposed when this methods returns.
using (var scope = services.GetRequiredService<IServiceScopeFactory>().CreateScope())
{
var context = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
//await context.Database.EnsureCreatedAsync();
var manager = scope.ServiceProvider.GetRequiredService<OpenIddictApplicationManager<OpenIddictApplication>>();
if (await manager.FindByClientIdAsync("MySPA", cancellationToken) == null)
{
var application = new OpenIddictApplication
{
ClientId = "MySPA",
DisplayName = "MySPA",
LogoutRedirectUri = "http://localhost:9000/signout-oidc",
RedirectUri = "http://localhost:9000/signin-oidc"
};
await manager.CreateAsync(application, cancellationToken);
}
if (await manager.FindByClientIdAsync("resource-server-1", cancellationToken) == null)
{
var application = new OpenIddictApplication
{
ClientId = "resource-server-1"
};
await manager.CreateAsync(application, "846B62D0-DEF9-4215-A99D-86E6B8DAB342", cancellationToken);
}
}
}
不确定如何在同一个项目中并排实现这些。如上所述,除了API返回HTML登录页面而不是所需的HTTP状态
之外,它都“有效”答案 0 :(得分:3)
app.UseIdentity();
在您的管道中出现两次,这违背了在branch.UseIdentity()
分支构建器中使用app.UseWhen()
的全部目的(即确保不会调用Identity注册的Cookie中间件)您的API端点)。
删除第一个匹配项,它应该可以正常工作。
答案 1 :(得分:1)
您将AutomaticChallenge设置为true
。根据{{3}}
此标志表示当授权失败时,中间件应将浏览器重定向到LoginPath或AccessDeniedPath。
因此,通过将此设置为false,它将不会重定向到登录。