How to authorize users against the ASP.Net Role Provider

J.D. Meier, Jason Taylor, Prashant Bansode, Carlos Farre, Madhu Sundararajan, Steve Gregersen.

Use the following steps to declaratively authorize users with the ASP.NET role provider:
  1. Configure the Role provider in the service app.config or web.config file as follows:
  <system.web>
    <!-- Configure the Sql Role Provider -->
    <roleManager enabled ="true" 
                 defaultProvider ="RoleProvider" >
      <providers>
        <add name ="RoleProvider" 
             type="System.Web.Security.<<providerName>>" 
             connectionStringName="Conn" 
             applicationName="MembershipAndRoleProviderSample"/>
      </providers>
    </roleManager>
  </system.web>
  1. Configure the WCF Service to use the ASP.NET role provider:
    <behaviors>
      <serviceBehaviors>
        <behavior name="CalculatorServiceBehavior">
          <!-- Configure role based authorization to use the Role Provider -->
          <serviceAuthorization principalPermissionMode ="UseAspNetRoles"
                                roleProviderName ="RoleProvider" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
  1. Authorize declaratively by adding the PrincipalPermission attribute above each service method that requires authorization. Specify the Windows user group required to access the method in the Role field.
[PrincipalPermission(SecurityAction.Demand, Role = "accounting")]
public double Add(double a, double b)
{
    return a + b;
}
  1. Authorize imperatively by using the Roles.IsUserInRole method to authorize the client. The role can be contained in a variable and changed dynamically if needed, as shown below:
  string RequiredGroup = “Administrators”;
  try
  {
    if (!Roles.IsUserInRole(User.Identity.Name, “RequiredGroup”))
    {
      Msg.Text = "You are not authorized to view user roles.";
      UsersListBox.Visible = false;
      return;
    }
  }
  catch (HttpException e)
  {
    Msg.Text = "There is no current logged on user. Role membership cannot be verified.";
    return;
  }

Additional Resources

Last edited May 8, 2008 at 12:57 AM by prashantbansode, version 2

Comments

No comments yet.