Search code examples
asp.net-mvcmembership-provideradfs

Using Active Directory Membership Provider for Site Authentication


I have an MVC site that I am in the process of converting from Forms to Federated Authentication. I am able to connect to the ADFS server and verify authentication. However the site currently uses an ActiveDirectoryMembershipProvider to verify the roles of the users as different roles permit different access.

I can not figure out how to populate the MembershipProvider so that I can user things such as this:

User.IsInRole(@"MY-ROLE")

and this:

[Authorize(Roles = "MY-ROLE")]

I have this snippet in my web.config which works for forms authentication but isn't working in my federated site:

<membership defaultProvider="ADMembershipProvider">
    <providers>
        <clear />
        <add name="ADMembershipProvider" type="System.Web.Security.ActiveDirectoryMembershipProvider" connectionProtection="Secure" attributeMapUsername="sAMAccountName" connectionStringName="ADConn" connectionUsername="LotusLDAPUser" connectionPassword="LotusLDAPUser" />
    </providers>
</membership>

I have read a lot of MSDN docs and am still having trouble so please don't just answer with a link to docs. I would appreciated some sample code.

UPDATE: I added a RoleProvider to my web.config. The role provider was being used in the forms application version successfully, so I believe the values are correct I just missed adding it to the web.config of the federated version. Here is what I have:

<roleManager enabled="true" defaultProvider="ActiveDirectoryRoleProvider" cacheRolesInCookie="true" cookieName=".ADLibraryROLES" cookiePath="/" cookieTimeout="1440" cookieRequireSSL="false" cookieSlidingExpiration="true" createPersistentCookie="true" cookieProtection="All">
    <providers>
        <clear />
        <add name="ActiveDirectoryRoleProvider" connectionStringName="ADConn" connectionUsername="LotusLDAPUser" connectionPassword="LotusLDAPUser" attributeMapUsername="sAMAccountName" type="MyNamespace.ActiveDirectoryRoleProvider" />
      </providers>
</roleManager>

It is still returning false for

User.IsInRole(@"MY-ROLE")

and

[Authorize(Roles = "MY-ROLE")]

For a user I know to my in "MY-ROLE"


Solution

  • The problem was that I wasn't setting the Session Token Cookie. In the forms authentication version I had the code:

    FormsAuthentication.SetAuthCookie(user.UserName, true);
    

    When testing the Federated version I wasn't setting the authentication cookie, this line is needed:

    FederatedAuthentication.SessionAuthenticationModule.WriteSessionTokenToCookie(token);
    

    Where token is a SessionSecurityToken created from my Claim.