Copied to clipboard

Flag this post as spam?

This post will be reported to the moderators as potential spam to be looked at


  • Thomas Haggren 29 posts 149 karma points
    Sep 07, 2017 @ 13:05
    Thomas Haggren
    0

    How to validate user in custom login controller

    I have setup custom member provider as stated in the documentation (i.e. "Member Authentication" and "Member Authorization").

    In my custom login controller I'm not sure what "ValidateUser" method I need to call. Currently it is Membership.ValidateUser(model.Username, model.Password) - but this is not working.

    What am I missing here?

    public class ADLoginController : SurfaceController
    {
        [HttpPost]
        public ActionResult Login(ADLoginModel model, string returnUrl)
        {
            if (!ModelState.IsValid)
            {
                return CurrentUmbracoPage();
            }
    
            if (model.Username != null && model.Password != null && Membership.ValidateUser(model.Username, model.Password))
            {
                FormsAuthentication.SetAuthCookie(model.Username, false);
    
                if (System.Web.HttpContext.Current.Session["MemberLoginRedirectURL"] != null)
                {
                    var redirectUrl = (string)System.Web.HttpContext.Current.Session["MemberLoginRedirectURL"];
                    System.Web.HttpContext.Current.Session["MemberLoginRedirectURL"] = null;
                    return Redirect(redirectUrl);
                }
    
                if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/") && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
                {
                    return Redirect(returnUrl);
                }
    
                return Redirect("/");
            }
    
            TempData["Status"] = "Wrong username and/or password!";
            return CurrentUmbracoPage();
        }
    
        [HttpGet]
        public ActionResult Logout()
        {
            Session.Clear();
            Members.Logout();
            return Redirect("/");
        }
    }
    

    Thanks :)

  • Dan Diplo 1554 posts 6205 karma points MVP 6x c-trib
    Sep 07, 2017 @ 14:06
    Dan Diplo
    0

    I normally do something like this, which works:

    MemberLoginService loginService = new MemberLoginService(Services.MemberService);
    
    var validateResponse = loginService.ValidateLogin(model.Username, model.Password, true);
    
    if (validateResponse.IsValid)
    {
        FormsAuthentication.SetAuthCookie(validateResponse.Username, model.StayLoggedIn);
       ....
    }
    
    public class MemberLoginService
    {
        private IMemberService MemberService { get; set; }
    
        /// <summary>
        /// Instantiate the login service. See the <seealso cref="MembershipSurfaceController"/> for actual login processing.
        /// </summary>
        /// <param name="memberService">The Umbraco member service</param>
        public MemberLoginService(IMemberService memberService)
        {
            if (memberService == null)
                throw new ArgumentNullException("memberService");
    
            this.MemberService = memberService;
        }
    
        /// <summary>
        /// Validates the login credentials of a given username and password (but doesn't check whether their account is active or roles are valid)
        /// </summary>
        /// <param name="username">The member username</param>
        /// <param name="password">The member password</param>
        /// <param name="allowEmailAsUsername">Set to true to allow the member to login with their email as well as their username (default true)</param>
        /// <returns>A response that contains whether the credentials where valid and also their correct username (if they logged in with email).</returns>
        public ValidateLoginResponse ValidateLogin(string username, string password, bool allowEmailAsUsername = true)
        {
            ValidateLoginResponse response = new ValidateLoginResponse()
            {
                IsValid = false,
                Username = username
            };
    
            response.IsValid = Membership.ValidateUser(username, password);
    
            if (!response.IsValid && allowEmailAsUsername)
            {
                var mem = this.MemberService.GetByEmail(username);
    
                if (mem != null)
                {
                    response.IsValid = Membership.ValidateUser(mem.Username, password); // incase they enter their email instead of username
                    response.Username = mem.Username;
                }
                else
                {
                    response.IsValid = false;
                }
            }
    
            return response;
        }
    }
    
  • Thomas Haggren 29 posts 149 karma points
    Sep 07, 2017 @ 18:20
    Thomas Haggren
    0

    Hi Dan

    Thank you for your reply.

    From your implementation I can see you ultimately also call Membership.ValidateUser.

    Do your implementation also work with the "Active Directory Providers" package?

    It might be that my LDAP connection is not right although I can verify it work in a test tool.

    Thanks.

  • Dan Diplo 1554 posts 6205 karma points MVP 6x c-trib
    Sep 07, 2017 @ 19:17
    Dan Diplo
    0

    Yes, you are correct - the actual authentication is via the Membership.ValidateUser method (as you do). No, I don't use the Active Directory Providers package, so can't comment on how that works. However, if it is registered as the active membership provider then it should utilise the AD authentication methods that the provider exposes.

    In your web.config in the <membership> section is it registered as the defaultProvider?

  • Thomas Haggren 29 posts 149 karma points
    Sep 08, 2017 @ 07:58
    Thomas Haggren
    0

    This is the settings in web.config

    <!-- Connection Strings -->
    <connectionStrings>
        <add name="MyMembershipConnectionString" connectionString="LDAP://test.dk/OU=Groups,OU=TEST.DK,DC=test,DC=dk" />
    </connectionStrings>
    
    <!-- Membership Provider -->
    <membership defaultProvider="MyMembersMembershipProvider" userIsOnlineTimeWindow="15">
      <providers>
        <clear />
        <add name="UmbracoMembershipProvider" type="Umbraco.Web.Security.Providers.MembersMembershipProvider, Umbraco" minRequiredNonalphanumericCharacters="0" minRequiredPasswordLength="10" useLegacyEncoding="false" enablePasswordRetrieval="false" enablePasswordReset="false" requiresQuestionAndAnswer="false" defaultMemberTypeAlias="Member" passwordFormat="Hashed" allowManuallyChangingPassword="false" />
        <add name="UsersMembershipProvider" type="Umbraco.Web.Security.Providers.UsersMembershipProvider, Umbraco" minRequiredNonalphanumericCharacters="0" minRequiredPasswordLength="10" useLegacyEncoding="false" enablePasswordRetrieval="false" enablePasswordReset="false" requiresQuestionAndAnswer="false" passwordFormat="Hashed" allowManuallyChangingPassword="false" />
        <add name="MyMembersMembershipProvider"
             type="RB.ActiveDirectoryProviders.ActiveDirectoryUmbracoMembersMembershipProvider, RB.ActiveDirectoryProviders"
             connectionStringName="MyMembershipConnectionString"
             connectionUsername="USERNAME"
             connectionPassword="PASSWORD"
             attributeMapUsername="sAMAccountName"
             defaultMemberType="ADMembers" />
      </providers>
    </membership>
    
    <!-- Role Provider -->
    <roleManager enabled="true" defaultProvider="MyMembersRoleProvider">
      <providers>
        <clear />
        <add name="UmbracoRoleProvider" type="Umbraco.Web.Security.Providers.MembersRoleProvider" />
        <add name="MyMembersRoleProvider"
             type="RB.ActiveDirectoryProviders.ActiveDirectoryRoleProvider, RB.ActiveDirectoryProviders"
             connectionStringName="MyMembershipConnectionString"
             connectionUsername="USERNAME"
             connectionPassword="PASSWORD"
             groupsToUse="BackOffice" />
      </providers>
    </roleManager>
    

    In the backoffice I have created a member type called ADMembers and I can also see the BackOffice AD group under roles.

    enter image description here

  • Thomas Haggren 29 posts 149 karma points
    Sep 08, 2017 @ 07:59
    Thomas Haggren
    0

    This is the settings in web.config

    <!-- Connection Strings -->
    <connectionStrings>
        <add name="MyMembershipConnectionString" connectionString="LDAP://test.dk/OU=Groups,OU=TEST.DK,DC=test,DC=dk" />
    </connectionStrings>
    
    <!-- Membership Provider -->
    <membership defaultProvider="MyMembersMembershipProvider" userIsOnlineTimeWindow="15">
      <providers>
        <clear />
        <add name="UmbracoMembershipProvider" type="Umbraco.Web.Security.Providers.MembersMembershipProvider, Umbraco" minRequiredNonalphanumericCharacters="0" minRequiredPasswordLength="10" useLegacyEncoding="false" enablePasswordRetrieval="false" enablePasswordReset="false" requiresQuestionAndAnswer="false" defaultMemberTypeAlias="Member" passwordFormat="Hashed" allowManuallyChangingPassword="false" />
        <add name="UsersMembershipProvider" type="Umbraco.Web.Security.Providers.UsersMembershipProvider, Umbraco" minRequiredNonalphanumericCharacters="0" minRequiredPasswordLength="10" useLegacyEncoding="false" enablePasswordRetrieval="false" enablePasswordReset="false" requiresQuestionAndAnswer="false" passwordFormat="Hashed" allowManuallyChangingPassword="false" />
        <add name="MyMembersMembershipProvider"
             type="RB.ActiveDirectoryProviders.ActiveDirectoryUmbracoMembersMembershipProvider, RB.ActiveDirectoryProviders"
             connectionStringName="MyMembershipConnectionString"
             connectionUsername="USERNAME"
             connectionPassword="PASSWORD"
             attributeMapUsername="sAMAccountName"
             defaultMemberType="ADMembers" />
      </providers>
    </membership>
    
    <!-- Role Provider -->
    <roleManager enabled="true" defaultProvider="MyMembersRoleProvider">
      <providers>
        <clear />
        <add name="UmbracoRoleProvider" type="Umbraco.Web.Security.Providers.MembersRoleProvider" />
        <add name="MyMembersRoleProvider"
             type="RB.ActiveDirectoryProviders.ActiveDirectoryRoleProvider, RB.ActiveDirectoryProviders"
             connectionStringName="MyMembershipConnectionString"
             connectionUsername="USERNAME"
             connectionPassword="PASSWORD"
             groupsToUse="BackOffice" />
      </providers>
    </roleManager>
    

    I have created a member type in the backoffice called ADMembers and I can also see the BackOffice AD group under roles.

    enter image description here

  • Thomas Haggren 29 posts 149 karma points
    Sep 08, 2017 @ 08:07
    Thomas Haggren
    0

    I get an error if the LDAP connection string is not correct and the same goes when not supplying a correct connectionUsername and connectionPassword.

    So I am on some level connected to the AD.

Please Sign in or register to post replies

Write your reply to:

Draft