0

How to use cookie authentication but not ASP.NET Core Identity? It is my controller.It didn't work when I click submit. Can someone give me advice?

public IActionResult Login()
    {
        return View();
    }
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Login(db_user _User)
    {

        if (ModelState.IsValid)
        {   
            if (_User.UserName != "123" && _User.UserPassword != "123")
            {
                ViewData["ErrorMessage"] = "error!!";
                return View();
            }

            
            var claims = new List<Claim>   
            {
                new Claim(ClaimTypes.Name, _User.UserName),
                
            };

            
            var claimsIdentity = new ClaimsIdentity(
                                       claims, CookieAuthenticationDefaults.AuthenticationScheme);

            var authProperties = new AuthenticationProperties
            {
                //AllowRefresh = <bool>,
                // Refreshing the authentication session should be allowed.

                //ExpiresUtc = DateTimeOffset.UtcNow.AddMinutes(10), 
                // The time at which the authentication ticket expires. A 
                // value set here overrides the ExpireTimeSpan option of 
                // CookieAuthenticationOptions set with AddCookie.

                //IsPersistent = true,
                // Whether the authentication session is persisted across 
                // multiple requests. When used with cookies, controls
                // whether the cookie's lifetime is absolute (matching the
                // lifetime of the authentication ticket) or session-based.

                //IssuedUtc = <DateTimeOffset>,
                // The time at which the authentication ticket was issued.

                //RedirectUri = <string>
                // The full path or absolute URI to be used as an http redirect response value.
            };

            // ***  Login *********
            HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme,
                                                    new ClaimsPrincipal(claimsIdentity),
                                                    authProperties);
            #endregion

            return Content("<h3>Welcome</h3>");
        }

        // Something failed. Redisplay the form.
        return View();
    }
    public async Task<IActionResult> Logout()
    {
        
        await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);

         return RedirectToAction("Index", "Home");
    }

It is my model

    namespace Cookie2.Model
{
    public class db_user
    {
        public string UserName { get; set; }
        public string UserPassword { get; set; }
    }
}

It is my .cshtml

 @model Cookie2.Model.db_user
    


@{
    ViewBag.Title = "title";
    Layout = "_Layout";
}


    <h2>Login</h2>
    <form asp-action="Index" asp-controller="Login" method="post">
        <label asp-for="UserName">
            <input asp-for="UserName">
        </label>
        <br />
        <label asp-for="UserPassword">
            <input asp-for="UserPassword">
        </label>
        <br>
        <button>Submit</button>
    </form>

It is startup.cs

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllersWithViews();

        services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
                .AddCookie(options =>
                {
                    options.AccessDeniedPath = "/Home/AccessDeny";
                    options.LoginPath = "/Home/Login";
                }
            
            
            );
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
        }
        app.UseStaticFiles();

        app.UseRouting();

        app.UseAuthentication();

        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllerRoute(
                name: "default",
                pattern: "{controller=Home}/{action=Index}/{id?}");
        });
    }
}

appreciation appreciation appreciation appreciation appreciation appreciation appreciation appreciation appreciation appreciation appreciation appreciation appreciation appreciation

5
  • Hi @Haohao1198, what do you mean for It didn't work? Is the form data passwed to backend? Or any other problems? You may explain more detailed. Commented Sep 9, 2021 at 7:37
  • Hi @Rena, the webpage cannot be found . HTTP404 Commented Sep 9, 2021 at 7:40
  • Hi @Haohao1198, where is the status code get, before hitting the HttpPost method or after HttpPost method running? Does it hit the HttpPost method but cannot return view successfully? Commented Sep 9, 2021 at 7:42
  • Hi @Haohao1198, I saw your LoginPath configure in Startup.cs is Home/Login, but in the login view, the form defines to asp-action="Index" asp-controller="Login", and the tag helper generated url is Login/Index. But your backend action is Login. It should be ControllerName/Login. The url does not match each other. And this will cause 404 error. Commented Sep 9, 2021 at 8:24
  • @Rena .Yes,it can work now...Thanks!! Commented Sep 9, 2021 at 8:36

1 Answer 1

1

In the login view, the form defines to asp-action="Index" asp-controller="Login", and the tag helper generated url is Login/Index.But your backend action is Login.It should be ControllerName/Login.The url does not match each other. And this will cause 404 error.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.