Search code examples
asp.netasp.net-coreasp.net-identity

User access to login page after authentication


I use identity for authentication in my application, but after authentication the user can access login and register page again!

Login method:


var claims = new List<Claim>()
            {
                new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()),
                new Claim(ClaimTypes.Name, user.Fullname),
            };
            var identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
            var principal = new ClaimsPrincipal(identity);

            var properties = new AuthenticationProperties
            {
                IsPersistent = model.RememberMe
            };
            HttpContext.SignInAsync(principal, properties);

            ViewBag.IsSuccess = true;
            if (ReturnUrl != "/")
            {
                return Redirect(ReturnUrl);
            }

            return Redirect("/dashboard");

startup code:

services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;

            }).AddCookie(options =>
            {
                options.LoginPath = "/login";
                options.LogoutPath = "/logout";
                options.ExpireTimeSpan = TimeSpan.FromMinutes(10080);

            });

note: I added app.UseAuthentication() to configure method


Solution

  • And? Of course they can. There's no authentication/authorization policies for viewing those pages, so anyone can get to them, logged in or not. If you want to stop this, just add a check at the start of the action like:

    if (User.Identity.IsAuthenticated())
        return RedirectToAction("Account");
    

    If you like, you could create also create that as a request filter attribute and apply it to these actions that way. Either way, it's something you must explicitly disallow.