.net core 2.1基于声明的身份验证

时间:2018-10-30 14:55:48

标签: asp.net-core-2.1

我有dotnet core 1.1版本代码可用于身份验证。我有两个Cookie,一个用于用户,一个用于管理员,因此admin可以冒充用户。

  app.UseCookieAuthentication(new CookieAuthenticationOptions()
        {
            AuthenticationScheme = config.Value.AppCookie,
            LoginPath = new PathString("/Login/"),
            AccessDeniedPath = new PathString("/Login/"),
            AutomaticAuthenticate = true,
            CookieSecure = CookieSecurePolicy.SameAsRequest,
            //ExpireTimeSpan = TimeSpan.FromHours(1),
            AutomaticChallenge = true
        });

        app.UseCookieAuthentication(new CookieAuthenticationOptions()
        {
            AuthenticationScheme = config.Value.AdminCookie,
            LoginPath = new PathString("/Login/"),
            AccessDeniedPath = new PathString("/Login/"),
            AutomaticAuthenticate = true,
            CookieSecure = CookieSecurePolicy.SameAsRequest,
            //ExpireTimeSpan = TimeSpan.FromHours(1),
            AutomaticChallenge = true
        });

核心2.1

 services.AddAuthentication(options =>
        {
            options.DefaultScheme = _config.AppCookie;
            options.DefaultChallengeScheme = _config.AppCookie;
        }).AddCookie(_config.AppCookie, options =>
        {
            options.LoginPath = "/Login/";
            options.AccessDeniedPath = "/Login/";
        });


        services.AddAuthentication(options =>
        {
            options.DefaultScheme = _config.AdminCookie;
            options.DefaultChallengeScheme = _config.AdminCookie;
        }).AddCookie(_config.AdminCookie, options =>
        {
           options.LoginPath = "/Login/";
           options.AccessDeniedPath = "/Login/";
        });

如果我查看User.Claims,只有一个声明对象,在这种情况下是AdminCookie。如果我将AddAuthentication AppCookie切换到AdminCookie之后,那么仅User.Claims中的AppCookie。 我需要同时使用两者,如何更改代码。

用户的Singin代码

        List<Claim> userClaims = new List<Claim>();
        userClaims.Add(cl);

        ClaimsPrincipal principal = new ClaimsPrincipal(new ClaimsIdentity(userClaims, _config.AuthType));
        await HttpContext.SignInAsync(_config.AppCookie, principal, new AuthenticationProperties
        {
            IsPersistent = true,
            ExpiresUtc = DateTime.UtcNow.AddMinutes(120)
        });

管理员的Singin代码

 Claim cl = new Claim(ClaimTypes.Role, "Admin", appcon.User.ToString());
        userClaims.Add(cl);

        ClaimsPrincipal principal = new ClaimsPrincipal(new ClaimsIdentity(userClaims, _config.AdminAuthType));
        await HttpContext.SignInAsync(_config.AdminCookie, principal, new AuthenticationProperties
        {
            IsPersistent = true,
            ExpiresUtc = DateTime.UtcNow.AddYears(1)
        });

0 个答案:

没有答案