Redirect to Login Page if User is not Authenticated (logged in) in ASP.Net Core MVC

trisetia302
 
on Sep 26, 2021 10:58 PM
897 Views

Hi,

I was tried prevent end user to access directly the URL from address bar on browsers. I want all end user must login if end user access directly the URL from address bar on browsers not and not login it will redirect to form login.

When I test this code in my project it works fine but now it not working. When I test the code without Authentication and Authorization work fine but now when I use Authentication and Authorization it not working.

Every time submit button click on login form just redirect result like this "http://localhost:13120/Login/LoginUser?ReturnUrl=%2F".

This is should be if the login successfully will redirect to "return RedirectToAction("Index", "Login");"

Any help could be appreciate.

Startup.cs

namespace Klinik_Apps
{
    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.AddDbContext<KlinikContext>(options =>
                options.UseSqlServer(Configuration.GetConnectionString("Db_Klinik")));
            services.AddControllersWithViews();
            services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie(x => x.LoginPath = "/Login/LoginUser");
            services.AddMvc();
            services.AddControllers().AddJsonOptions(jsonOptions =>
            {
                jsonOptions.JsonSerializerOptions.PropertyNamingPolicy = null;
            });
        }

        // 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.UseAuthorization();
            app.UseAuthentication();
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Login}/{action=Index}/{id?}");
            });
            app.UseCookiePolicy();
        }
    }
}

Login.cshtml

@using Klinik_Apps.Models
@model LoginModel
@{
    ViewBag.Title = "Login";
    Layout = null;
}
<script src="~/lib/jquery/dist/jquery.js"></script>
<script src="~/lib/sweetalert2/sweetalert2.js"></script>
<link href="~/lib/sweetalert2/sweetalert2.css" rel="stylesheet" />
<link href="~/assets/css/fontawesome-free/css/all.css" rel="stylesheet" />
<link href="~/lib/bootstrap/dist/css/bootstrap.css" rel="stylesheet" />
<script src="~/lib/bootstrap/dist/js/bootstrap.js"></script>
<link href="~/css/StyleLogin.css" rel="stylesheet" />
<html>
<head>
    <title>Login</title>
</head>
<body>
    <div id="bg">
        <img src="~/assets/img/GedungRS.jpg" class="img1" />
    </div>
    <form asp-action="LoginUser" asp-controller="Login" method="post">
        @Html.HiddenFor(x => x.ReturnUrl)
        <div asp-validation-summary="ModelOnly" class="text-danger"></div>
        <div class="container mt-2 img2">
            <div class="row">
                <div class="col-md-6">
                </div>
                <div class="col-md-4">
                    <div class="container_form">
                        <img src="~/assets/img/LoginUserIcon.jpg" height="150px" width="295px" />
                        <h6 class="text text-center alert alert-primary">
                            Welcome Back ! <br />
                            Sign In to continue use <br />
                            Klinik Information System
                        </h6>
                        <hr />
                        <div class="form-group">
                            <label for="UserName">
                                User Name
                            </label>
                            <div class="input-group mb-3">
                                <span class="input-group-text"><i class="fa fa-user"></i></span>
                                <input type="text" asp-for="User_Name" class="form-control" placeholder="Enter User Name" required />
                                <br />
                                <span asp-validation-for="User_Name" class="text-danger"></span>
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="Password">
                                Password
                            </label>
                            <div class="input-group mb-3">
                                <span class="input-group-text"><i class="fa fa-key"></i></span>
                                <input type="password" asp-for="Password" class="form-control" placeholder="Enter Password" required />
                                <br />
                                <span asp-validation-for="Password" class="text-danger"></span>
                            </div>
                        </div>
                        <div class="form-group">
                            <div class="checkbox">
                                <label>
                                    <input asp-for="RememberLogin" /> @Html.DisplayNameFor(model => model.RememberLogin)
                                </label>
                            </div>
                        </div>
                        <div class="form-group">
                            <div align="right">
                                <button type="submit" class="btn btn-md btn-success"><i class="fa fa-lock-open"></i> Sign In</button>
                            </div>
                        </div>
                        <i class="fa fa-arrow-alt-circle-right"> @Html.ActionLink("Register New User", "Register")</i>
                    </div>
                </div>
            </div>
        </div>
    </form>

    @if (@ViewBag.Message != null)
    {
        <script type="text/javascript" lang="javascript">
            Swal.fire({
                position: 'top',
                icon: 'error',
                title: 'Oops...',
                text: '@ViewBag.Message'
            });
        </script>
    }
    <script src="~/lib/jquery-validation/dist/jquery.validate.js"></script>
    <script src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.js"></script>
</body>
</html>

LoginController.cs

public IActionResult Login(string ReturnUrl = "/")
{
    LoginModel objLoginModel = new LoginModel();
    objLoginModel.ReturnUrl = ReturnUrl;
    return View(objLoginModel);
}
 
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> LoginUser(LoginModel login)
{
    if (ModelState.IsValid)
    {
        try
        {
            using (SqlConnection con = new SqlConnection(this._configuration.GetConnectionString("Db_Klinik")))
            {
                using (SqlCommand cmd = new SqlCommand())
                {
                    con.Open();
                    cmd.Connection = con;
                    cmd.CommandType = CommandType.Text;
                    cmd.CommandText = "Select * From Tbl_User Where User_Name=@User_Name And Password=@Password";
                    cmd.Parameters.AddWithValue("@User_Name", login.User_Name);
                    cmd.Parameters.AddWithValue("@password", login.Password);
                    cmd.ExecuteNonQuery();
                    DataTable dt = new DataTable();
                    dt.Load(cmd.ExecuteReader());
                    if (dt.Rows.Count > 0)
                    {
                        TempData["pesan"] = "Anda berhasil Login";
                        var claims = new List<Claim>() {
                           new Claim("username", "admin"),
                           new Claim(ClaimTypes.Name, login.User_Name),
                           new Claim(ClaimTypes.Role, "admin"),
                        };
                        var identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
                        var principal = new ClaimsPrincipal(identity);
                        await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal, new AuthenticationProperties()
                        {
                            IsPersistent = login.RememberLogin
                        });
                        return LocalRedirect(login.ReturnUrl);
                    }
                    else
                    {
                        ViewBag.Message = "Login gagal. Username atau Password anda salah !!!";
                        return View(login);
                    }
                }
            }
        }
        catch (Exception)
        {
            throw;
        }
    }
    return RedirectToAction("Index", "Login");
}

 

Download FREE API for Word, Excel and PDF in ASP.Net: Download