More in this section
Forums / Developing with Sitefinity / Custom Login Widget (MVC, Razor)

Custom Login Widget (MVC, Razor)

The forums are in read-only mode. In case that you want to directly contact the Progress Sitefinity team use the support center. In our Google Plus group you can find more than one thousand Sitefinity developers discussing different topics. For the Stack Overflow threads don’t forget to use the “Sitefinity” tag.
6 posts, 0 answered
  1. Armin
    Armin avatar
    3 posts
    Registered:
    30 Nov 2010
    26 Jul 2012
    Link to this post
    Hello,
    I'm trying to write my own custom login widget by using MVC and Razor. The problem is that I can perform the login and the first page after the login shows me that I'm logged in, but as soon as I change page it tells me that no user is logged in; when I login again I get from the SecurityManager that the user is already logged in. What am I missing?
    The relevant code in the controller:
    
    
    [HttpPost]
    public ActionResult Index(string username, string password)
    {
        UserManager userManager = UserManager.GetManager();
        if (userManager.ValidateUser(username, password))
        {
            //if you need to get the user instance use the out parameter
            //Telerik.Sitefinity.Security.Model.User userToAuthenticate = null;
            var result = SecurityManager.AuthenticateUser(userManager.Provider.Name, username, password, true);
            if (result == UserLoggingReason.Success)
            {
                         
            }
        }
     
        return View();
    }
     
    public ActionResult Logout()
    {
        SecurityManager.Logout();
        SecurityManager.DeleteAuthCookies();
        return Redirect("~/home");
    }

    The relevant code on the razor page where I check if a user is logged in:
    var profileManager = UserProfileManager.GetManager();
    var currentUserId = SecurityManager.GetCurrentUserId();
    User user1 = null;
    if (currentUserId != Guid.Empty)
    {
        user1 = SecurityManager.GetUser(currentUserId);
    }
     
    if (user1 != null)
    {
        SitefinityProfile userProfile = profileManager.GetUserProfile(user1.Id, typeof(SitefinityProfile).FullName) as SitefinityProfile;
        if (userProfile == null)
        {
    <p>@user1.FirstName @user1.LastName</p>
        }
        else
        {
    <p>@userProfile.FirstName @userProfile.LastName</p>
        }
    }

    It seems to me that the login is not "stored" and that the system forgets that there is a current user.

    Regards
  2. Peter
    Peter avatar
    42 posts
    Registered:
    22 Aug 2011
    31 Jul 2012
    Link to this post
    Hello,

    I have got the same problem here. I created a custom login widget, with a succesfull login I redirect to another page but at this page my login is gone. Anyone?

    Regards,
    Peter
  3. Armin
    Armin avatar
    3 posts
    Registered:
    30 Nov 2010
  4. Peter
    Peter avatar
    42 posts
    Registered:
    22 Aug 2011
    07 Aug 2012
    Link to this post
    Hi Armin,

    That works indeed, thanks!
  5. Swapna
    Swapna avatar
    1 posts
    Registered:
    17 Sep 2013
    25 Sep 2013
    Link to this post
    Hi Armin

       I am new to sitefinity i am trying to build an application for that i need login custom code .. I have seen many sites but dnt get the answer .. Please send the code of login custom control 
  6. Armin
    Armin avatar
    3 posts
    Registered:
    30 Nov 2010
    11 Oct 2013
    Link to this post
    Hello this is the code that I use now:

    public ActionResult PerformLogin(string usernameLoginForm, string passwordLoginForm, bool rememberMe, string redirectUrl = null)
        {
            string strURL = redirectUrl ?? (string)Session["RedirectToUrl"] ?? ((Request.UrlReferrer != null) ? Request.UrlReferrer.AbsoluteUri : "~/");
     
            AuthenticationMode authMode = Config.Get<SecurityConfig>().AuthenticationMode;
            if (AuthenticationMode.Claims != authMode)
            {
                throw new Exception("Only Claims based authentication mode is supported.");
            }
     
            HttpWebRequest tokenRequest = (HttpWebRequest)HttpWebRequest.Create(SitefinityClaimsAuthenticationModule.Current.GetIssuer());
            tokenRequest.Method = "POST";
            var postDataString = string.Format("deflate=true&realm={0}&wrap_name={1}&wrap_password={2}&sf_persistent=true&sf_domain=Default",
                HttpUtility.UrlEncode(SitefinityClaimsAuthenticationModule.Current.GetRealm()),
                HttpUtility.UrlEncode(usernameLoginForm),
                HttpUtility.UrlEncode(passwordLoginForm));
            var postData = Encoding.UTF8.GetBytes(postDataString);
            tokenRequest.ContentLength = postData.Length;
            tokenRequest.ContentType = "application/x-www-form-urlencoded";
     
            var dataStream = tokenRequest.GetRequestStream();
            dataStream.Write(postData, 0, postData.Length);
            dataStream.Close();
            HttpWebResponse issuerResponse = default(HttpWebResponse);
     
            try
            {
                CookieContainer cookieJar = new CookieContainer();
                tokenRequest.CookieContainer = cookieJar;
                issuerResponse = (HttpWebResponse)tokenRequest.GetResponse();
     
                if (rememberMe)
                {
                    foreach (Cookie c in cookieJar.GetCookies(tokenRequest.RequestUri))
                    {
                        var myCookie = new HttpCookie(c.Name, c.Value);
                        Response.Cookies.Add(myCookie);
                    }
                }
     
                using (StreamReader responseStream = new StreamReader(issuerResponse.GetResponseStream()))
                {
                    UserManager manager = UserManager.GetManager();
                    var user = manager.GetUser(usernameLoginForm);
     
                    if (user != null && user.IsLockedOut)
                    {
                        throw new Exception(string.Format("The user {0} is locked out!", user.UserName"));
     
                        //or unlock the user
                        //user.UnlockUser();
                    }
     
                    string token = responseStream.ReadToEnd();
                    if (strURL.Contains("?"))
                    {
                        return Redirect(strURL + "&" + token);
                    }
     
                    return Redirect(strURL + "?" + token);
                }
            }
            catch (Exception ex)
            {
                //login failed
                return Redirect("~/login");
            }
        }
6 posts, 0 answered