1

我正在尝试登录,但HttpContext.User.Identitiy.IsAuthenticated总是错误的。

配置服务

services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie(
                options => {

                    options.LoginPath = "/";
                    options.AccessDeniedPath =new PathString("/AccessDenied");
                    options.Events.OnRedirectToLogin = (context) => {
                        context.Response.StatusCode = 401;
                        return Task.CompletedTask;
                    };
                });

方法

public async Task Invoke(HttpContext context) {
            string token = context.Request.Query["token"];
            var claims = new List<Claim> {
                new Claim("token",token,APPLICATION_NAME)
            };

            var claimsIdentity = new ClaimsIdentity(claims,CookieAuthenticationDefaults.AuthenticationScheme);
            var authProperties = new AuthenticationProperties {
                AllowRefresh = true,
                ExpiresUtc = DateTimeOffset.Now.AddSeconds(20),
                IsPersistent = true
            };

            await context.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(claimsIdentity),authProperties);
            if (context.User.Identity.IsAuthenticated) { //always false
            }
}
4

1 回答 1

1

SignInAsync不会更改当前请求的用户主体。在下一个请求中检查相同的属性,它应该是true

于 2019-03-26T19:19:47.627 回答