Role Management

Sep 23, 2013 at 9:54 PM
Hi, I'm starting an MVC 5 app on VS2013 RC.
Using the template I manage to create a Role and add it to the user, but the claims is not added the Principal. Am I missing some configuration? How does roles works? Can I use the [Authorize(Roles="myRole")] attribute?
Developer
Sep 25, 2013 at 5:41 PM
Yes. This should work. For every request the ClaimsIdentity of the user is created from the cookie. So on first time registration it is not just sufficient if you add/associate roles for the user, but on every successful login, you will have to set the roles of the user in the provider extensibility methods so that the role information is being sent with the cookie. For example if you are using an external auth middleware like Google/Facebook/Twitter/MicrosoftAccount, do this on your middleware setup.

//Demonstrating with google middleware
app.UseGoogleAuthentication(new GoogleAuthenticationOptions()
        {
            SignInAsAuthenticationType = "External",
            Provider = new GoogleAuthenticationProvider()
            {
                OnAuthenticated = context =>
                { 
                OnReturnEndpoint = context =>
                {
                        //Adding the role as a claim here will set this information in the cookie
                        context.Identity.AddClaim(new Claim(context.Identity.RoleClaimType, "myRole", ClaimValueTypes.String));
                        return Task.FromResult(0);
                }
            }
        });
If its Cookie authentication, then
app.UseCookieAuthentication(new CookieAuthenticationOptions()
        {
            Provider = new CookieAuthenticationProvider()
            {
                OnValidateIdentity = context =>
                {
                    //Adding the role as a claim here will set this information in the cookie
                    context.Identity.AddClaim(new Claim(context.Identity.RoleClaimType, "myRole", ClaimValueTypes.String));
                    return Task.FromResult(0);
                }
            }
        });
Sep 25, 2013 at 5:53 PM
Thank you :)