Home > Back-end >  How to authorize a session in MVC .net core?
How to authorize a session in MVC .net core?

Time:04-05

I want to authorize Create operation only when a user logged in ? How do I acheive that?

ApplicationDBContext.cs


namespace BookReadingEvents.Data
{
    public class ApplicationDbContext : DbContext
    {
        public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
        {

        }
        public DbSet<BookReadingEvent> BookReadingEvents { get; set; }
        public DbSet<Register> RegisterAccount { get; set; }
        public DbSet<Login> LoginAccount { get; set; }
    }
}
  

RegisterController.cs



namespace BookReadingEvents.Controllers
{
    public class RegisterController : Controller
    {
        private readonly ApplicationDbContext _db;
        [ActivatorUtilitiesConstructor]
        public RegisterController(ApplicationDbContext db)
        {
            _db = db;
        }
        public IActionResult Index()
        {
            return RedirectToAction("Register");
        }

        // GET Register
        public IActionResult Register()
        {
            return View();
        }
        //POST Register
       [HttpPost]
        public IActionResult Register(Register user)
        {
            
            if (ModelState.IsValid)
            {
                _db.RegisterAccount.Add(user);
                _db.SaveChanges();
                return RedirectToAction("Index");
            }
            
           
            return View(user);
        }
    }
}

LoginController.cs

   public class LoginController : Controller
    {


        private readonly ApplicationDbContext _db;
        [ActivatorUtilitiesConstructor]
        public LoginController(ApplicationDbContext db)
        {
            _db = db;
        }
        public IActionResult Index()
        {
            return RedirectToAction("Login");
        }

        // GET Login
        public IActionResult Login()
        {
            return View();
        }
        //POST Login
        [HttpPost]
        [ValidateAntiForgeryToken]

        public IActionResult Login(Login user)
        {
            if (ModelState.IsValid)
            {
                var obj = _db.RegisterAccount.Where(u => u.Email.Equals(user.Email) && u.Password.Equals(user.Password)).FirstOrDefault();
                if (obj != null)
                {
                    user.RegisterId = obj.RegisterId;
                    _db.LoginAccount.Add(user);
                    _db.SaveChanges();
                    HttpContext.Session.SetObjectAsJson("Register", obj);
                    return RedirectToAction("LoggedIn");
                }
            }
            ModelState.AddModelError("", "Some Error Occured");
            return RedirectToAction("Login");
        }

        public IActionResult LoggedIn()
        {

            var userDetails = HttpContext.Session.GetObjectFromJson<Register>("Register");
            int? thisUserID = Convert.ToInt32(userDetails.RegisterId);

            if (thisUserID != null)
            {
                return RedirectToAction("Index","Home");
            }
            else
            {
                return RedirectToAction("Login");
            }
        }

        public IActionResult Logout()
        {
            HttpContext.Session.Clear();
            //HttpContext.Session.Abandon();
            return RedirectToAction("Index", "Home");
        }

        public IActionResult MyEvents()
        {
            return View();
        }


    }
}

SessionExtension.cs

  public static class SessionExtension
    {
        public static void SetObjectAsJson(this ISession session, string key, object value)
        {
            session.SetString(key, JsonConvert.SerializeObject(value));
        }

        public static T GetObjectFromJson<T>(this ISession session, string key)
        {
            var value = session.GetString(key);
            return value == null ? default(T) : JsonConvert.DeserializeObject<T>(value);
        }
    }

BookReadingEventController.cs



namespace BookReadingEvents.Controllers
{
    public class BookReadingEventController : Controller
    {
        private readonly ApplicationDbContext _db;
        public BookReadingEventController(ApplicationDbContext db)
        {
            _db = db;
        }
        public IActionResult Index()
        {
            IEnumerable<BookReadingEvent> objList = _db.BookReadingEvents;
            return View(objList);
        }
        // GET Create
         //[Authorize]
         //InvalidOperationException: No authenticationScheme was specified, 
         //and there was no DefaultChallengeScheme found. 
        public IActionResult Create() 
        {
            ViewBag.StartTimeDD = new List<string> {  "00:00", "01:00", "02:00", "03:00" , "04:00", "05:00", "06:00", "07:00", "08:00" , "09:00" ,"10:00", "11:00", "12:00", "13:00", "14:00", "15:00", "16:00","17:00", "18:00", "19:00",
              "20:00", "21:00", "22:00", "23:00"};
            return View();
        }
        // POST Create
        [HttpPost]
        [ValidateAntiForgeryToken]
        public IActionResult Create(BookReadingEvent obj)
        {
            ViewBag.StartTimeDD = new List<string> {  "00:00", "01:00", "02:00", "03:00" , "04:00", "05:00", "06:00", "07:00", "08:00" , "09:00" ,"10:00", "11:00", "12:00", "13:00", "14:00", "15:00", "16:00","17:00", "18:00", "19:00",
              "20:00", "21:00", "22:00", "23:00"};
            if (ModelState.IsValid)
            {
                _db.BookReadingEvents.Add(obj);
                _db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(obj);

        }
        public IActionResult Display(int id)
        {
            var obj = _db.BookReadingEvents.Find(id);
            if (obj == null)
            {
                return NotFound();
            }
            return View(obj);
       }

        // GET Update
          //[Authorize]
         //InvalidOperationException: No authenticationScheme was specified, 
         //and there was no DefaultChallengeScheme found.
        public IActionResult Update(int? id)
        {
            ViewBag.StartTimeDD = new List<string> {  "00:00", "01:00", "02:00", "03:00" , "04:00", "05:00", "06:00", "07:00", "08:00" , "09:00" ,"10:00", "11:00", "12:00", "13:00", "14:00", "15:00", "16:00","17:00", "18:00", "19:00",
              "20:00", "21:00", "22:00", "23:00"};
            if (id == null || id == 0)
            {
                return NotFound();
            }
            var obj = _db.BookReadingEvents.Find(id);
            if (obj == null)
            {
                return NotFound();
            }
            return View(obj);

        }

        // POST Update
        [HttpPost]
        [ValidateAntiForgeryToken]
        public IActionResult Update(BookReadingEvent obj)
        {
            if (ModelState.IsValid)
            {
                _db.BookReadingEvents.Update(obj);
                _db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(obj);

        }
    }
}

I want to authorize the Create and Update Actions such that only when a user has logged in they will be able to create or update the tables. How do I achive that?

CodePudding user response:

I noticed that when user login successfully, You set a session whitch key is Register in your login method, If you want to authorize session. You can use IActionFilter to achieve it. I write a simple demo here.

Filter

public class SessionFilter : Attribute,IActionFilter
{
  

    public void OnActionExecuting(ActionExecutingContext context)
    {
        //if there is no session whitch key is "register", user will not access to specified action and redirect to login page.

        var result = context.HttpContext.Session.GetObjectFromJson<T>("register");
        if (result==null)
        {
            context.Result = new RedirectToActionResult("Login", "Login", null);
        }
    }

    public void OnActionExecuted(ActionExecutedContext context)
    {
        
    }
}

Then you can add [SessionFilter] to the action whitch you want to protected.

        [HttpPost]
        [SessionFilter]
        [ValidateAntiForgeryToken]
        public IActionResult Create(BookReadingEvent obj)
        {.......}
  • Related