Question Authorization Question

raysefo

Well-known member
Joined
Feb 22, 2019
Messages
361
Programming Experience
10+
Hi,

I am new to ASP.Net Core. I have an MVC core application that I am trying to implement a login page. I created a table into a database for users. I would like to give an unauthorized message if the user enters the wrong username/password and if the user tries to enter a page without login, the application should redirect to the login page.

Here is my controller:
C#:
namespace GameMonitor.Controllers
{
    public class GameBanksController : Controller
    {
        private readonly GameContext _context;

        public GameBanksController(GameContext context)
        {
            _context = context;
        }

        [Route("")]
        [Route("GameBanks")]
        [Route("GameBanks/Login")]
        public IActionResult Login()
        {
            return View();
        }

        [HttpPost]
        public IActionResult UserLogin(UserLogin loginModel)
        {
            if (Login(loginModel.Username, loginModel.Password))
            {
                
                //Just redirect to our index after logging in.
                return RedirectToAction("Index", "GameBanks");
            }
            
            return RedirectToAction("Error", "Shared"); ;
        }

        public bool Login(string userName, string password)
        {
            var user = _context.UserLogins.FirstOrDefault(u => u.Username.Equals(userName, StringComparison.Ordinal) && u.Password == password);
            if (user == null) return false;
            return true;
        }
        [Authorize]
        [Route("GameBanks/Index")]
        // GET: GameBanks
        public async Task<ActionResult<IList<GameBanks>>> Index()
        {
            //Group By games
            var games = await _context.GameBanks.GroupBy(g =>new {g.ProductCode,g.UnitPrice,g.ProductDescription})
                .Select(gcs => new GameBanks
                {
                    ProductCode = gcs.Key.ProductCode,
                    ProductDescription = gcs.Key.ProductDescription,
                    UnitPrice = gcs.Key.UnitPrice,
                    Quantity = gcs.Sum(g => g.Quantity)


                }).ToListAsync();

            return View(games);
        }
        [Authorize]
        // GET: GameBanks
        public async Task<IActionResult> GamesList()
        {
            return View(await _context.GameBanks.ToListAsync());
        }


        [Authorize]
        // GET: GameBanks/Details/5
        public async Task<IActionResult> Details(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var gameBanks = await _context.GameBanks
                .FirstOrDefaultAsync(m => m.GameBankId == id);
            if (gameBanks == null)
            {
                return NotFound();
            }

            return View(gameBanks);
        }

        
    }
}

Here is the login page:
C#:
@{
    ViewData["Title"] = "Login";
}


    <h2>Login</h2>
 
    <form action="@Url.Action("UserLogin", "GameBanks")" method="post">
        <div class="form-group">
            <label>User Name</label>
            <input type="text" class="form-control" name="Username" value="" />
        </div>
        <div class="form-group">
            <label>Password</label>
            <input type="password" name="Password" class="form-control" value="" />
        </div>
        <div class="form-group">
            <input type="submit" class="btn btn-primary" name="name" value="Submit" />
        </div>
 
    </form>
 
Couldn't implement what I want :) When I write other actions into my browser (details, list), It is not redirected to the Login page.
 
Show us your startup.cs. You should be able to configure authentication and authorization from there.
 
Here is the startup:
C#:
namespace GameMonitor
{
    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.Configure<CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });


            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
            var connection = @"Data Source=(localdb)\MSSQLLocalDB;Database=Game;Integrated Security=True;AttachDbFilename=C:\Users\197199\Documents\Visual Studio 2017\Projects\GameMonitor\GameMonitor\TestGame.mdf;ConnectRetryCount=0";
            services.AddDbContext<GameContext>(options => options.UseSqlServer(connection));
        }

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

            app.UseStaticFiles();
            app.UseCookiePolicy();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Games}/{action=Index}/{id?}");
            });
        }
    }
}
 
How to configure to redirect to login page from [Authorize]?
C#:
namespace GameMonitor.Controllers
{
    public class GameBanksController : Controller
    {
        private readonly GameContext _context;

        public GameBanksController(GameContext context)
        {
            _context = context;
        }

        [Route("")]
        [Route("GameBanks")]
        [Route("GameBanks/Login")]
        public IActionResult Login()
        {
            return View();
        }

        [HttpPost]
        public IActionResult UserLogin(UserLogin loginModel)
        {
            if (Login(loginModel.Username, loginModel.Password))
            {
                //Create the identity for the user 
                var identity = new ClaimsIdentity(new[] {
                    new Claim(ClaimTypes.Name, loginModel.Username)
                }, CookieAuthenticationDefaults.AuthenticationScheme);

                var principal = new ClaimsPrincipal(identity);

                var login = HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal);

                //Just redirect to our index after logging in.
                return RedirectToAction("Index", "GameBanks");
            }

            return RedirectToAction("Login","GameBanks");
        }

        public bool Login(string userName, string password)
        {
            var user = _context.UserLogins.FirstOrDefault(u =>
                u.Username.Equals(userName, StringComparison.Ordinal) && u.Password == password);
            if (user == null) return false;
            return true;
        }

        [Authorize]
        [Route("GameBanks/Index")]
        // GET: GameBanks
        public async Task<ActionResult<IList<GameBanks>>> Index()
        {
            //Group By games
            var games = await _context.GameBanks.GroupBy(g => new {g.ProductCode, g.UnitPrice, g.ProductDescription})
                .Select(gcs => new GameBanks
                {
                    ProductCode = gcs.Key.ProductCode,
                    ProductDescription = gcs.Key.ProductDescription,
                    UnitPrice = gcs.Key.UnitPrice,
                    Quantity = gcs.Sum(g => g.Quantity)
                }).ToListAsync();

            return View(games);
        }

        [Authorize]
        // GET: GameBanks
        public async Task<IActionResult> GamesList()
        {
            return View(await _context.GameBanks.ToListAsync());
        }


        [Authorize]
        // GET: GameBanks/Details/5
        public async Task<IActionResult> Details(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var gameBanks = await _context.GameBanks
                .FirstOrDefaultAsync(m => m.GameBankId == id);
            if (gameBanks == null)
            {
                return NotFound();
            }

            return View(gameBanks);
        }
    }
}

Startup:
C#:
namespace GameMonitor
{
    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.Configure<CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie();
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
            var connection = @"Data Source=(localdb)\MSSQLLocalDB;Database=Game;Integrated Security=True;AttachDbFilename=C:\Users\197199\Documents\Visual Studio 2017\Projects\GameMonitor\GameMonitor\TestGame.mdf;ConnectRetryCount=0";
            services.AddDbContext<GameContext>(options => options.UseSqlServer(connection));
            
        }

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

            app.UseStaticFiles();
            app.UseCookiePolicy();
            app.UseAuthentication();
            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Games}/{action=Index}/{id?}");
            });


        }
    }
}
 
C#:
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
                .AddCookie(options => {
                    options.LoginPath = "/GameBanks/Login/";
                    
                });
 
Whats this doing? return RedirectToAction("Error", "Shared");
You're asking how to redirect but not showing how you are trying to do it.
 
Back
Top Bottom