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

放肆的年华 提交于 2019-12-12 01:08:29

问题


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);
        }
    }

回答1:


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);
}


来源:https://stackoverflow.com/questions/20926046/asp-net-web-forms-how-to-combine-wif-authentification-with-membership-provider

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!