Search code examples
asp.netwifmembership-providerroleprovider

ASP.NET web forms - how to combine WIF authentification with membership provider and role provider


I'm using windows identity foundation with form authentification in ASP.NET Web Forms in .NET 4.5 How can I combine WIF form authentification with my custom membership provider and my custom role provider defined in web.config?

I want to use my custom membership provider for load additional user info from SQL DB such as email, birthday, avatar iamge. I want to use my custom role provider to obtain all roles from SQL DB for authentificated user.

My authentification method Authenticate(userName, password) is called from Login.aspx LoginButtonClick:

    public static ClaimsPrincipal Authenticate(string userName, string password)
    {
        var principal = AuthenticateWindowsUser(userName, password);
        var inputIdentity = (WindowsIdentity)principal.Identity;

        var outputIdentity = new ClaimsIdentity(inputIdentity.AuthenticationType);
        outputIdentity.AddClaim(new Claim(ClaimTypes.Name, inputIdentity.Name));
        return new ClaimsPrincipal(outputIdentity);
    }

    private static WindowsPrincipal AuthenticateWindowsUser(string userName, string password)
    {
        try
        {
            SecurityToken securityToken = new UserNameSecurityToken(userName, password);
            var handlers = FederatedAuthentication.FederationConfiguration.IdentityConfiguration.SecurityTokenHandlers;

            //Uses default WindowsUserNameSecurityTokenHandler
            return new WindowsPrincipal((WindowsIdentity)handlers.ValidateToken(securityToken)[0]);
        }
        catch (SecurityTokenValidationException ex)
        {
            ShowException(ex);
        }
    }

Solution

  • Assuming that the provided code works for you it should be

    public static ClaimsPrincipal Authenticate(string userName, string password)
    {
        var principal = AuthenticateWindowsUser(userName, password);
        var inputIdentity = (WindowsIdentity)principal.Identity;
    
        var outputIdentity = new ClaimsIdentity(inputIdentity.AuthenticationType);
        outputIdentity.AddClaim(new Claim(ClaimTypes.Name, inputIdentity.Name));
    
        // other information from the membership provider
        var user = Membership.GetUser( userName ) );
        outputIdentity.AddClaim( new Claim( ClaimTypes.Email, user.Email ) );
        ...
    
        // roles from role provider
        foreach ( string role in Roles.GetRolesForUser( userName ) )
           outputIdentity.AddClaim( new Claim( ClaimTypes.Role, role ) );
    
        return new ClaimsPrincipal(outputIdentity);
    }