.NET Core 2.0中Cookie的应用程序处理程序

时间:2018-07-13 02:54:05

标签: c# cookies asp.net-core asp.net-core-2.0

我已经阅读了ASP .NET核心团队基于Cookie的身份验证实现示例。当我实现类似的startup.cs文件并尝试登录时,出现运行时异常

InvalidOperationException: No authentication handler is configured to handle the scheme: Cookies

我应该如何配置应用处理程序以验证我的cookie?

这是我的代码供参考。

从Startup.cs配置方法

    public void ConfigureServices(IServiceCollection services)
    {
        CookieBuilder builder = new RequestPathBaseCookieBuilder()
        {
            HttpOnly = false,
        };
        services.AddSingleton<IConfiguration>(Configuration);
        services.AddSingleton<CookieBuilder>(builder);
        services.AddIdentity<ApplicationUser, ApplicationRole>();
        services.AddAuthentication(options => {
            options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
        })
        .AddCookie(options => {
            options.Cookie = builder;
            options.LoginPath = "/account/login";
            options.LogoutPath = "/account/logout";
            options.Events = new CookieAuthenticationEvents()
            {
                OnValidatePrincipal = ValidateCookiePrincipal,

            };
        });
        services.AddDistributedMemoryCache();

        services.AddSession(options =>
        {
            // Set a short timeout for easy testing.
            options.IdleTimeout = TimeSpan.FromSeconds(10);
            options.Cookie.HttpOnly = true;
        });
        services.AddMvc();
    }

帐户/登录中的登录方法

 [HttpGet("login")]
    public IActionResult Login() => Redirect(RedirectUrl()); //redirects to IdP url

验证IdP响应方法

[HttpPost("/samlACS")]
    public async Task<IActionResult> SamlACSAsync([FromForm] string samlResponse)
    {

        /*
         * if(saml response is successful)
         * {
         *      set cookie
         *      redirect to home url
         * }
         * 
         *  Redirect(OKTA sign in URL)
         * **/
        string nameID = ValidateSAMLResponse(samlResponse);
        var claims = new List<Claim>
        {
            new Claim(ClaimTypes.Name, nameID)
        };
        var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);

        var authProperties = new AuthenticationProperties()
        {
            AllowRefresh = true,
        };
        await HttpContext.Authentication.SignInAsync(
                CookieAuthenticationDefaults.AuthenticationScheme,
                new ClaimsPrincipal(claimsIdentity),
                authProperties
            );
        return LocalRedirect("/home");
    }

0 个答案:

没有答案