我跟着this文章在我们的项目中实现了有条件的中间件,它工作得非常好。 但是,当我们将项目从.netcore 1.0升级到.netcore 1.1时,它无效。
我在启动时写了下面的代码。
Func<HttpContext, bool> isApiRequest = (HttpContext context) => context.Request.Path.ToString().StartsWith("/api/");
JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
//For MVC not API
app.UseWhen(context => !isApiRequest(context), appBuilder =>
{
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationScheme = "Cookies",
AutomaticAuthenticate = true
});
app.UseOpenIdConnectAuthentication(new OpenIdConnectOptions
{
AuthenticationScheme = "oidc",
SignInScheme = "Cookies",
AutomaticChallenge = true,
Authority = authority,
RequireHttpsMetadata = false,
ClientId = "sampleClient",
//ClientSecret = "secret",
Scope = { "openid" , "profile" },
ResponseType = "id_token token",//"code id_token",
SaveTokens = true
});
});
//FOR API
app.UseWhen(context => isApiRequest(context), appBuilder =>
{
app.UseIdentityServerAuthentication(new IdentityServerAuthenticationOptions()
{
Authority = authority,
RequireHttpsMetadata = false,
AllowedScopes =
{
"scope1",
"scope2"
}
});
});
现在,当我尝试访问基于View的ActionMethod(意味着不以api开头)时,即使在那种情况下api身份验证工作,也不是基于Cookie的身份验证。基于API的身份验证非常适用。
我们正在使用最新版本的Identity Server 4构建我们的项目。
任何帮助/指示都将不胜感激。
答案 0 :(得分:2)
更改两个条件块以使用appBuilder
而不是app
。
博客文章错了。您现在将它们注册在顶级中间件堆栈而不是子构建器上。
例如:
app.UseWhen(context => !isApiRequest(context), appBuilder =>
{
appBuilder.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationScheme = "Cookies",
AutomaticAuthenticate = true
});
appBuilder.UseOpenIdConnectAuthentication(new OpenIdConnectOptions
{
AuthenticationScheme = "oidc",
SignInScheme = "Cookies",
AutomaticChallenge = true,
Authority = authority,
RequireHttpsMetadata = false,
ClientId = "sampleClient",
//ClientSecret = "secret",
Scope = { "openid" , "profile" },
ResponseType = "id_token token",//"code id_token",
SaveTokens = true
});
});