I found a great answer to SO describing customizing user user roles , and I did the same in my project. Therefore, in my login service, I have:
public ActionResult Login() { // password authentication stuff omitted here var roles = GetRoles(user.Type); // returns a string eg "admin,user" var authTicket = new FormsAuthenticationTicket( 1, userName, DateTime.Now, DateTime.Now.AddMinutes(20), // expiry false, roles, "/"); var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(authTicket)); Response.Cookies.Add(cookie); return new XmlResult(xmlDoc); // don't worry so much about this - returns XML as ActionResult }
And in Global.asax.cs I have (copied verbatim from another answer):
protected void Application_AuthenticateRequest(Object sender, EventArgs e) { var authCookie = Context.Request.Cookies[FormsAuthentication.FormsCookieName]; if (authCookie != null) { var authTicket = FormsAuthentication.Decrypt(authCookie.Value); var roles = authTicket.UserData.Split(new Char[] { ',' }); var userPrincipal = new GenericPrincipal(new GenericIdentity(authTicket.Name), roles); Context.User = userPrincipal; } }
Then in my ServicesController class I have:
[Authorize(Roles = "admin")]
I log in as a user with the admin role and this works. Then I call / services / doadminstuff - and I get access to it, although when I set a breakpoint in Global.asax.cs, I see that my roles include "admin". If I comment on the first Authorize attribute (with roles) and just use plain Authorize vanilla, then I can access this service.
I need to miss something important here - but where to start looking?
Shaul Behr Mar 15 '11 at 16:19 2011-03-15 16:19
source share