AspNetCore一起使用cookie和Bearer,并使Authorize属性在默认情况下同时使用

时间:2018-12-30 22:16:41

标签: asp.net-core oauth

我有使用Cookie和Bearer令牌的应用程序。由于我不想通过提供架构来更新每个授权,因此我重写了默认架构:

   services
            .AddAuthorization(options =>
                {
                    options.DefaultPolicy = new AuthorizationPolicyBuilder()
                        .AddAuthenticationSchemes(OAuthValidationDefaults.AuthenticationScheme,
                            CookieAuthenticationDefaults.AuthenticationScheme,
                            "Identity.Application")
                        .RequireAuthenticatedUser()
                        .Build();
                });
            services.AddAuthentication()
                .AddExternalAuthProviders(Configuration)
                .AddFlymarkOpenIdConnectServer()
                .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options =>
                {
                    options.LoginPath = "/Identity/Account/LogIn";
                    options.SlidingExpiration = true;
                    options.Events.OnRedirectToLogin = OnRedirectToLogin;
                })
                .AddOAuthValidation(OAuthValidationDefaults.AuthenticationScheme,
                    o=>o.Events.OnCreateTicket = OnCreateTicket);
            services.ConfigureApplicationCookie(config =>
            {
                config.Events = new CookieAuthenticationEvents
                {
                    OnRedirectToLogin = OnRedirectToLogin
                };
            });

我认为,如果我添加 CookieAuthenticationDefaults.AuthenticationScheme ,那么它将起作用,但直到我添加 Identity.Application

时,cookie才起作用。

所以我的问题是为什么它不起作用或在何处使用常量而不是硬编码字符串

1 个答案:

答案 0 :(得分:1)

ASP.NET Core Identity使用它自己的cookie身份验证处理程序实例,当您调用services.AddIdentity()时为您神奇地注册了它。

如您所知,这些实例不使用默认方案名称,而是以Identity.前缀开头的名称。

在您的代码中,您基本上是在使用默认方案名称注册一个新的cookie处理程序实例。但是由于您的代码中没有任何东西使用它来发布Cookie,所以它无法验证任何东西,并且始终会返回未经身份验证的票证,这就是为什么直到您添加与主cookie对应的神奇的Identity.Application才起作用的原因ASP.NET Core Identity使用的处理程序实例。

您要查找的常数在IdentityConstants中。

注意:添加可同时接受身份验证Cookie和承载令牌的默认策略之前,请格外小心,因为如果您的应用程序不使用防伪,那么它可能容易受到CSRF的攻击(通常在开发API时就是这种情况)。 / p>

相关问题