ASP.NET MVC Single Sign-on and Roles
Asked Answered
U

2

8

I have basic Single Sign-On working across 2 MVC sites (call them SiteA and SiteB) using something along the lines of the following method:

http://forums.asp.net/p/1023838/2614630.aspx

They are on sub-domains of the same domain and share hash\encryption keys etc in web.config. I've modified the cookie so it is accessible to all Sites on the same domain. All of this seems to be working ok.

The sites are on separate servers without access to the same SQL database, so only SiteA actually holds the user login details. SiteB has a membership database, but with empty users.

This works fine for my required scenario which is:

1) User logs into SiteA

2) The application loads data from SiteA (by AJAX) and SiteB (by AJAX using JSONP)

I have the following LogOn Action on my AccountController for SiteA, which is where the "magic" happens:

[HttpPost]
public ActionResult LogOn(LogOnModel model, string returnUrl)
{
    if (ModelState.IsValid)
    {
        if (MembershipService.ValidateUser(model.UserName, model.Password))
        {
            FormsService.SignIn(model.UserName, model.RememberMe);

            //modify the Domain attribute of the cookie to the second level of domain
            // Add roles  
            string[] roles = Roles.GetRolesForUser(model.UserName);
            HttpCookie cookie = FormsAuthentication.GetAuthCookie(User.Identity.Name, false);
            FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(cookie.Value);
            // Store roles inside the Forms cookie.  
            FormsAuthenticationTicket newticket = new FormsAuthenticationTicket(ticket.Version, model.UserName, 
                ticket.IssueDate, ticket.Expiration, ticket.IsPersistent, String.Join("|", roles), ticket.CookiePath);
            cookie.Value = FormsAuthentication.Encrypt(newticket);
            cookie.HttpOnly = false;
            cookie.Domain = ConfigurationManager.AppSettings["Level2DomainName"];
            Response.Cookies.Remove(cookie.Name);
            Response.AppendCookie(cookie);

            if (!String.IsNullOrEmpty(returnUrl))
            {
                return Redirect(returnUrl);
            }
            else
            {
                return RedirectToAction("Index", "Home");
            }
        }
        else
        {
            ModelState.AddModelError("", "The user name or password provided is incorrect.");
        }
    }

This does some stuff which I don't strictly need for the initial scenario, but relates to my question. It inserts the Roles list for the user on login to SiteA into the UserData of the authentication ticket. This is then "restored" on SiteB by the following in global.asax:

protected void Application_AuthenticateRequest(Object sender, EventArgs e)
{
    if (Context.Request.IsAuthenticated)
    {
        FormsIdentity ident = (FormsIdentity) Context.User.Identity;
        string[] arrRoles = ident.Ticket.UserData.Split(new[] {'|'});
        Context.User = new System.Security.Principal.GenericPrincipal(ident, arrRoles);
    }
}

All of the stuff above works until I add Roles into the mix. Things work fine if I only decorate my Controllers\Actions on SiteB with [Authorize] attributes. But as soon as I add [Authorize(roles="TestAdmin")] users can no longer access that Controller Action. Obviously I have added the user to the TestAdmin Role.

If I debug the global.asax code on SiteB, it looks ok as I leave the global.asax code, BUT then when I hit a break point in the controller itself the Controller.User and Controller.HttpContext.User is now a System.Web.Security.RolePrincipal without the roles set anymore.

So my question is: Does anybody have any idea how I can restore the roles on SiteB or another way to do this?

Unweighed answered 30/8, 2010 at 1:18 Comment(0)
K
2

You already worked it out, but here we go:

make it work: turn off the role manager. Its not an odd behavior that asp.net is doing that, since you are explicitly telling it to use look for the user's roles with the configuration specified.

another way to do it: enable the role manager in both. Use the configuration to share the cookie as you are doing in your custom code. Based on your description, you shouldn't need to worry about it trying to get roles for the user, as long as you use a matching configuration for the authentication cookie

should you use Application_AuthorizeRequest to set the roles cookies? imho opinion earlier (Authenticate) is best, I have always done it that way and never ran into issues.

Ketosis answered 6/9, 2010 at 9:10 Comment(1)
Thanks. Yeah, most of that I'd already worked out, but it's good to have confirmation. :) I'll happily accept this as the answer if you can could give some reasons Application_AuthenticateRequest might be better than Application_AuthorizeRequest.Unweighed
U
2

Since this seems to have stagnated I can partially answer this one with some additional findings. After debugging\testing this a bit more, it seems MVC2 is doing something odd after leaving Application_AuthenticateRequest but before entering my Controller. More details here:

http://forums.asp.net/t/1597075.aspx

A workaround is to use Application_AuthorizeRequest instead of Application_AuthenticateRequest.

EDIT: I believe I found the cause of my issues. On my MVC1 project I had roleManager disabled but my test MVC2 project had roleManager enabled. Once I enabled my roleManager in the MVC1 test project, the behaviour between MVC1 and MVC2 is the same. I also have a question to one of the MVC Microsoft team open about this, and will post back here if Application_AuthorizeRequest is the correct place to restore the Roles from Authentication ticket cookie...

Unweighed answered 30/8, 2010 at 22:32 Comment(0)
K
2

You already worked it out, but here we go:

make it work: turn off the role manager. Its not an odd behavior that asp.net is doing that, since you are explicitly telling it to use look for the user's roles with the configuration specified.

another way to do it: enable the role manager in both. Use the configuration to share the cookie as you are doing in your custom code. Based on your description, you shouldn't need to worry about it trying to get roles for the user, as long as you use a matching configuration for the authentication cookie

should you use Application_AuthorizeRequest to set the roles cookies? imho opinion earlier (Authenticate) is best, I have always done it that way and never ran into issues.

Ketosis answered 6/9, 2010 at 9:10 Comment(1)
Thanks. Yeah, most of that I'd already worked out, but it's good to have confirmation. :) I'll happily accept this as the answer if you can could give some reasons Application_AuthenticateRequest might be better than Application_AuthorizeRequest.Unweighed

© 2022 - 2024 — McMap. All rights reserved.