Search code examples
asp.net-identitycookie-authentication

Can not perform sign in with cookie authentication


I am trying to sign in and HttpContext.User.Identitiy.IsAuthenticated is always false.

Configure service

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

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

Method

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
            }
}

Solution

  • SignInAsync doesn't change the current request's user principal. Check the same property on the next request and it should be true