如何将来自某个路径(网站)的请求重定向到登录页面,但对来自另一个路径(API 路径)的请求进行未经授权的响应? 据我了解,AutomaticChallenge 改变了所有网络应用程序的这种行为。但如何使其成为有条件的呢?
我使用 OpenIddict,它是 OpenId Connect Server 配置库。 一般来说,客户端是移动应用程序。不过,对于某些返回 View 的 Controller 来说,如果有一个类似网站的行为那就太好了。
启动代码如下所示:
// Add a middleware used to validate access
// tokens and protect the API endpoints.
app.UseOAuthValidation();
app.UseCsp(options => options.DefaultSources(directive => directive.Self())
.ImageSources(directive => directive.Self()
.CustomSources("*"))
.ScriptSources(directive => directive.Self()
.UnsafeInline())
.StyleSources(directive => directive.Self()
.UnsafeInline()));
app.UseXContentTypeOptions();
app.UseXfo(options => options.Deny());
app.UseXXssProtection(options => options.EnabledWithBlockMode());
app.UseIdentity();
// Add external authentication middleware below. To configure them please see http://go.microsoft.com/fwlink/?LinkID=532715
app.UseTwitterAuthentication(...);
app.UseFacebookAuthentication(...);
app.UseGoogleAuthentication(...);
app.UseSession();
app.UseOpenIddict();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
app.UseSwagger();
app.UseSwaggerUi();
最佳答案
要更改AutomaticChallenge
,您可以使用MapWhen
或UseWhen :
// ...
app.MapWhen(ctx => ctx.Request.Path.Value.StartsWith("/api"), builder =>
{
builder.UseCookieAuthentication(new CookieAuthenticationOptions()
{
AutomaticChallenge = false,
});
// ...
});
app.MapWhen(ctx => !ctx.Request.Path.Value.StartsWith("/api"), builder =>
{
builder.UseCookieAuthentication(new CookieAuthenticationOptions()
{
AutomaticChallenge = true,
});
// ...
});
但是我认为您的要求与AutomaticChallenge
无关。如果请求是 ajax,则 CookieAuthentication 中间件响应 401,否则重定向到登录路径。所以你不需要条件中间件。
关于asp.net-core - 如何在 ASP.NET Core 中实现条件自动挑战?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38467872/