1

I need authorization and authentication to be implemented in my MVC4 C# project.

I don't want to implement login logic to input Username and Password; i.e. no login screen.

I have user Id by HttpContext.Current.User.Identity.Name.

All I need if user is of role "admin" he can access all the controller pages and if he is user he can only access user controller and if he try to click Admin's actionlink he will get a message you are not authorized.

Every time a user is accessing any Actionmethod, my authorization logic is to be executed and checked and verified first, independently of which URL he is accessing.

Till now I have done this.

In web config:

<authentication mode="Forms" />
    <forms loginUrl="~/Appauth/appauth" timeout="2880" />
</authentication>

My route table:

routes.MapRoute(
            "Default", // Route name
            "{controller}/{action}/{id}", // URL with parameters*
            new { controller = "Appauth", action = "appauth", id = UrlParameter.Optional });

public class LoginController : Controller
{
    public ActionResult appauth(returnUrl)
    {
        bool userValid = false;
        currentuserID = HttpContext.Current.User.Identity.Name;
        if(currentuserID!=null)
        {
            userValid = true;
        }

        // User valid
        if (userValid)
        {
            FormsAuthentication.SetAuthCookie(username, false);
            if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
                    && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
            {
                return Redirect(returnUrl);
            }
            else
            {
                return RedirectToAction("UserHome", "Home");
            }
        }
        else
        {
            ModelState.AddModelError("", "The user name or password provided is incorrect.");
        }
        return RedirectToAction("Homeview");
    }
}

protected void Application_PostAuthenticateRequest(Object sender, EventArgs e)
{
    if (FormsAuthentication.CookiesSupported == true)
    {
        if (Request.Cookies[FormsAuthentication.FormsCookieName] != null)
        {
            try
            {
                //let us take out the username now                
                string username = FormsAuthentication.Decrypt(Request.Cookies[FormsAuthentication.FormsCookieName].Value).Name;
                string roles = string.Empty;

                role =//roles logic ;

                HttpContext.Current.User  = new System.Security.Principal.GenericPrincipal(
                  new System.Security.Principal.GenericIdentity(username, "Forms"), roles.Split(';'));
            }
            catch (Exception)
            {
                //somehting went wrong
            }
        }
    }
} 

public class AdminHomeController : Controller
{
    [Authorize(Roles="Admin")]
    public ActionResult About()
    {
        //admin logic
        return View("AdminViewHOme");
    }
}

public class UserHomeController : Controller
{
    [Authorize]
    public ActionResult Index()
    {
        //user logic
        return View(userviewhome);
    }
}

When I run this code to goes loop always calling my login logic and setting ticket and then jump to global asax to Facilitating Roles extraction using the authentication ticket and again login logic, i want to do it one time for a user not every time.

PS: If it is asp.net I can achieve it by writing method in Onpageload() event. confused this ticketing system and there flow please help with code.

jkdev
  • 9,037
  • 14
  • 52
  • 75
Manoj Kargeti
  • 141
  • 11

0 Answers0