+1-888-365-2779
Try Now
More in this section

Forums / General Discussions / Programmatic Login

Programmatic Login

38 posts, 1 answered
  1. Matt
    Matt avatar
    56 posts
    Registered:
    20 Nov 2009
    21 Oct 2010
    Link to this post
    Is there a way to programmatically login in beta 2?  I've tried the usual methods with no luck so far.  I'm new to SF so maybe I'm missing something obvious.

    Thanks,
    Matt

  2. Ivan Dimitrov
    Ivan Dimitrov avatar
    16072 posts
    Registered:
    19 Sep 2016
    22 Oct 2010
    Link to this post
    Hello Matt,

    We generate our own authentication cookie. You should use SecurityManager.SetAuthenticationCookie method to authenticate an user programmatically.

    Best wishes,
    Ivan Dimitrov
    the Telerik team
    Do you want to have your say when we set our development plans? Do you want to know when a feature you care about is added or when a bug fixed? Explore the Telerik Public Issue Tracking system and vote to affect the priority of the items
    Answered
  3. Matt
    Matt avatar
    56 posts
    Registered:
    20 Nov 2009
    22 Oct 2010
    Link to this post
    Thanks, that did the trick.
    For anyone else looking to do this, here are a couple of specific examples, either of which should work:

    SecurityManager.SetAuthenticationCookie(SystemManager.CurrentHttpContext.Response, user.ProviderName, user, false);

    SecurityManager.SetAuthenticationCookie(SystemManager.CurrentHttpContext.Response, Membership.Provider.Name, username, false);

  4. Andrei
    Andrei avatar
    553 posts
    Registered:
    27 Nov 2008
    08 Nov 2010
    Link to this post
    Matt,

    Thanks for posting the two lines of code. I tried both. It authenticates ok, but when I get to the DestinationPage it shows me as Anonymous. Did you have the same issue?

    1 - I tried:
    SecurityManager.SetAuthenticationCookie(SystemManager.CurrentHttpContext.Response, Membership.Provider.Name, username, False)

    2 - I tried:
    Dim usr As Model.User = DirectCast(Membership.GetUser(username), Model.User)
    SecurityManager.SetAuthenticationCookie(SystemManager.CurrentHttpContext.Response, usr.ProviderName, usr, False)

    Many thanks,
    Andrei
  5. Matt
    Matt avatar
    56 posts
    Registered:
    20 Nov 2009
    09 Nov 2010
    Link to this post
    Andrei,

    Here's the code that's working for me to login after new user registration:

    UserManager userMan = new UserManager();
    user = userMan.GetUser(username);
    string membershipProvider = user.ProviderName;
    HttpResponseBase response = SystemManager.CurrentHttpContext.Response;
    SecurityManager.SetAuthenticationCookie(response, membershipProvider, user, false);
    Response.Redirect("~/secure/index");

    This works for me in this one place, but I'm getting into trouble trying to use it for return user login.  I saw your post in another thread.  If you check the user immediately after setting the auth cookie, I don't think it'll reflect the new user yet. The cookie has to return to the browser and come back in the next request before SF will recognize the identity of the logged in user.  Seems like it should work after the redirect though...

    Sorry for the delayed response... did you already get past this issue?

    Matt


  6. Andrei
    Andrei avatar
    553 posts
    Registered:
    27 Nov 2008
    10 Nov 2010
    Link to this post
    Matt,

    I agree that "it should work after the redirect" but why it does not, I have no idea. Thanks for the code, but I get the same thing. It gets me through to the target page, but still shows 'Anonymous', which is most frustrating. It seems that Sitefinity is not that compatible with the ASP Login control after all. Everything I have tried so far with the <asp:Login control so far has proved to be a waste of time (loads of time).

    So I switched back to the Sitefinity LoginForm control. The first problems I started having was that it would throw Unhandled exceptions. Then I found out that it requires a ScriptManager and the template provided by Sitefinity I was using did not have the ScriptManager. So I created my own template with a ScriptManager inside and used it. The LoginForm worked fine, but all the styling disappeared. So now I am trying to style the LoginForm with relatively low success. I try saying DisplayRememberMe="False" but the front end does not reflect. All I want is for it to stay with its default style, but at runtime it loses that.

    Also the Edit option has disappeared when dropping the LoginForm control on to the page for unknown reasons. Now I cannot edit it or delete it. Good times...

    Many thanks again,
    Andrei
  7. Matt
    Matt avatar
    56 posts
    Registered:
    20 Nov 2009
    11 Nov 2010
    Link to this post
    Andrei,

    I'm still working on our login form, and running up against some of the same issues... also went back to just using the LoginForm control just until I have time to come back to it.  I'll keep you posted if I come up with anything new, because I would really like to get away from this control and use my own form.  Who knows, maybe all our problems will be solved with the RC release today.

    Matt

  8. Matt
    Matt avatar
    56 posts
    Registered:
    20 Nov 2009
    11 Nov 2010
    Link to this post
    Andrei,

    Here's my approach for controlling the styles of the LoginForm and for hiding the "remember me" checkbox, as well as the default title that I couldn't seem to override (you can see where I tried in the control attributes).  Kind of a hack, but it works.

    Matt

    <%@ Control Language="C#" AutoEventWireup="true" CodeBehind="Login.ascx.cs" Inherits="SitefinityWebApp.Custom.Widgets.Login" %>
    <%@ Register TagPrefix="t" Namespace="Telerik.Sitefinity.Security.Web.UI" Assembly="Telerik.Sitefinity" %>

    <style type="text/css">
    div.login ol li
    {
    list-style-type:none;
    }
    div.login h2
    {
    display:none;
    }
    div.login ol li label
    {
    width:200px;
    }
    div.login li.sfCheckBoxWrapper
    {
    display:none;
    }
    </style>

    <h1>Login</h1>

    <div class="login">
    <t:LoginForm runat="server" ID="loginForm1"
    Title="Login" TitleText="Login"
    ShowChangePasswordLink="false" 
    ShowForgotPasswordLink="false"
    ShowHelpLink="false"
    ShowRegisterUserLink="false"
    DisplayRememberMe="false"
    />
    </div>

  9. Ivan Dimitrov
    Ivan Dimitrov avatar
    16072 posts
    Registered:
    19 Sep 2016
    11 Nov 2010
    Link to this post
    Hi Matt, Andrei

    Below is a sample code that illustrates how to log in a user .


    public partial class WebPageTest1 : System.Web.UI.Page
       {
           protected void Page_Load(object sender, EventArgs e)
           {
               // get the login button
               var b = this.LoginControl.FindControl("LoginButton") as Button;
               // subscribe for click event
               b.Click += new EventHandler(b_Click);
               // get the current user
               var user = SecurityManager.GetCurrentUser();
               if (user != null)
               {
                   // get the identity
                   var ident = user.Identity.Name;
                   // force log out for this stest
                   SecurityManager.Logout();
               }
           }
           void b_Click(object sender, EventArgs e)
           {
               // Login the user.
               var now = DateTime.UtcNow;
               var ip = SystemManager.CurrentHttpContext.Request.UserHostAddress;
               var manager = UserManager.GetManager();
               var user = manager.GetUser("admin");
               user.IsLoggedIn = true;
               user.LastLoginIp = ip;
               user.LastLoginDate = now;
               user.LastActivityDate = now;
               SecurityManager.SetAuthenticationCookie(SystemManager.CurrentHttpContext.Response, "Default", user, true);
               manager.Provider.SuppressSecurityChecks = true;
               manager.SaveChanges();
               manager.Provider.SuppressSecurityChecks = false;
               Response.Redirect("~/WebPageTest1.aspx");
     
           }
       }


    You have to use the method
               SecurityManager.SetAuthenticationCookie(SystemManager.CurrentHttpContext.Response, "Default", user, true);

    Where the last parameter here indicates whether "Rembember Me" CheckBox has been checked. In the sample above I am setting this value explicitly. 

    After the user has been authenticated this will call Page_Load again, because of the Response.Redirect and the user identity is "admin", so you will not get "Anonymous" user anymore.

    Kind regards,
    Ivan Dimitrov
    the Telerik team
    Do you want to have your say when we set our development plans? Do you want to know when a feature you care about is added or when a bug fixed? Explore the Telerik Public Issue Tracking system and vote to affect the priority of the items
  10. Andrei
    Andrei avatar
    553 posts
    Registered:
    27 Nov 2008
    11 Nov 2010
    Link to this post
    Ivan saves the day. Just tried it and it works. Thank you very much.
    Matt many thanks again, and yes I am looking forward to the webinar (20 more minutes).

    Andrei

  11. Gerrit
    Gerrit avatar
    30 posts
    Registered:
    28 Jul 2010
    12 Nov 2010
    Link to this post
    Hi guys,

    I want to do the same, but I'm using Sitefinity 3.7 with .Net3.5 and using c#.

    Could you guys help me on  how to login a user programmaticly with c# and my sitefinity version?
    Struggling a bit with this...

    I did try with the code posted above, but I don't think all those methods is available in my version, can't seem to find them.

    Thanks in advanced!
  12. Gerrit
    Gerrit avatar
    30 posts
    Registered:
    28 Jul 2010
    12 Nov 2010
    Link to this post
    This is what I've got, but not sure if I'm on the right track here...

    UserManager manager = new UserManager();
    System.Web.Security.MembershipUser user = manager.GetUser( "username" );
    if( manager.ValidateUser( "username", "password" ) )
    {
    user.LastLoginDate = DateTime.Now;
    manager.SetAuthenticationCookie( new HttpCookie( "sitefinity" ) );
    }


    I'm not sure what should be in the cookie, I also saw there is no property for the user where you can set "IsLoggedIn" to true...so not sure how I should go about this.
  13. Ivan Dimitrov
    Ivan Dimitrov avatar
    16072 posts
    Registered:
    19 Sep 2016
    12 Nov 2010
    Link to this post
    Hello Gerrit,

    In Sitefinity 3.x you should use FormsAuthentication cookie

    HttpCookie cookie = this.Response.Cookies[FormsAuthentication.FormsCookieName];
    UserManager.Default.SetAuthenticationCookie(cookie);


    Greetings,
    Ivan Dimitrov
    the Telerik team
    Do you want to have your say when we set our development plans? Do you want to know when a feature you care about is added or when a bug fixed? Explore the Telerik Public Issue Tracking system and vote to affect the priority of the items
  14. Gerrit
    Gerrit avatar
    30 posts
    Registered:
    28 Jul 2010
    12 Nov 2010
    Link to this post
    Hi Ivan,

    Thank you for your quick reply.

    Oky I see, just one thing, I'm getting this error now :

    "Invalid value for 'encryptedTicket' parameter." 

    This happens when I call this line : "UserManager.Default.SetAuthenticationCookie( cookie );"
    I assume I must set a value in the cookie called "encryptedTicket".
    Where would I get that value?

    Thank you for your help!
  15. Ivan Dimitrov
    Ivan Dimitrov avatar
    16072 posts
    Registered:
    19 Sep 2016
    12 Nov 2010
    Link to this post
    Hi Gerrit,

    Sitefinity uses the standard ASP.NET Login control that comes with the .NET Framework. The error comes from FormsAuthentication.Decrypt ASP.NET static method when it is trying to decrypt authentication ticket which is passed as a string.

    It is possible that encryptedTicketstring is very long, it is string empty or it is not well formated and it could not be decrypted. ASP.NET uses the <machineKey> element for encryption and decryption of
    forms authentication cookie data. By default, both both validationKey and decryptionKey are set to AutoGenerate. There might be  a problem if you are running the website in web farm with AutoGenerated keys.

    Regards,
    Ivan Dimitrov
    the Telerik team
    Do you want to have your say when we set our development plans? Do you want to know when a feature you care about is added or when a bug fixed? Explore the Telerik Public Issue Tracking system and vote to affect the priority of the items
  16. Andrei
    Andrei avatar
    553 posts
    Registered:
    27 Nov 2008
    12 Nov 2010
    Link to this post
    Sorry Gerrit, can't think of anything now.
    Andrei
  17. Gerrit
    Gerrit avatar
    30 posts
    Registered:
    28 Jul 2010
    12 Nov 2010
    Link to this post
    Thank you for your posts guys!

    I saw that the "encryptedTicket" is an empty string for some odd reason.
    I googled it a bit, still can't really get a answer there as on why this is happening.

    Some suggested to clear your cookies and then it should work, but that did not work for me unfortionately.
    Any ideas maby on why this happens?

    I will keep you also posted when I get a solution on this, hopefully soon :)

    Regards,
    Gerrit
  18. Matt
    Matt avatar
    56 posts
    Registered:
    20 Nov 2009
    12 Nov 2010
    Link to this post
    Gerrit,

    It looks to me that Ivan's code snippet assumes you already have placed a forms authentication cookie on the response, and then sitefinity modifies that cookie.  In other words, it assumes you've already authenticated the user via plain old forms authentication.  Otherwise the cookie comes back null, which is what I think you're experiencing.  If you want to do a full programmatic login, try this line just prior to the two lines of code from Ivan:

    FormsAuthentication.SetAuthCookie(username, false);

    Of course this doesn't actually validate the user's credentials... you'll have to do that on your own.  I haven't tested this, but I hope it helps...

    Matt
  19. Gerrit
    Gerrit avatar
    30 posts
    Registered:
    28 Jul 2010
    15 Nov 2010
    Link to this post
    Hi Matt,

    Thank you for your post, that was my problem, I did not set the AuthCookie value, that is why I got the error.

    Here is a code snippet to login programmaticly with c# and version 3.7 and .Net 3.5:

    UserManager manager = new UserManager();
    System.Web.Security.MembershipUser user = manager.GetUser( username );
    if( manager.ValidateUser( username, password ) )
    {
    FormsAuthentication.SetAuthCookie( username, false );
    user.LastLoginDate = DateTime.Now;
    HttpCookie cookie = this.Response.Cookies[ FormsAuthentication.FormsCookieName ];
    UserManager.Default.SetAuthenticationCookie( cookie );
    }

    Thanks all for your help!
  20. Ivan Dimitrov
    Ivan Dimitrov avatar
    16072 posts
    Registered:
    19 Sep 2016
    15 Nov 2010
    Link to this post
    Hello Gerrit,

    You can take a look at this discussion.

    Best wishes,
    Ivan Dimitrov
    the Telerik team
    Do you want to have your say when we set our development plans? Do you want to know when a feature you care about is added or when a bug fixed? Explore the Telerik Public Issue Tracking system and vote to affect the priority of the items
  21. Matt
    Matt avatar
    56 posts
    Registered:
    20 Nov 2009
    16 Nov 2010
    Link to this post
    Getting yet another problem with the programmatic login.  Worked great for a while, but now sometimes it just shows the login form over and over.  Upon closer examination, there's a cookie coming back named .SFLOG with the value UserLoggedFromDifferentComputer.  Is there a way to programmatically logout the user from the other computer?

    Here's the code I'm using, which was suggested above:

    var now = DateTime.UtcNow;
    var ip = SystemManager.CurrentHttpContext.Request.UserHostAddress;
    var manager = UserManager.GetManager();
    var user = manager.GetUser(username);
    user.IsLoggedIn = true;
    user.LastLoginIp = ip;
    user.LastLoginDate = now;
    user.LastActivityDate = now;
    SecurityManager.SetAuthenticationCookie(SystemManager.CurrentHttpContext.Response, "Default", user, false);
    manager.Provider.SuppressSecurityChecks = true;
    manager.SaveChanges();
    manager.Provider.SuppressSecurityChecks = false;

    Thanks,
    Matt

  22. Bob
    Bob avatar
    330 posts
    Registered:
    24 Sep 2012
    16 Nov 2010
    Link to this post
    Hi Matt,

    Yes, there is way to programmatically logout a user from another computer. However, the API has changed for the RC and therefore I won't give you an example right now. I will post some examples, including web service authentication from other applications,  as soon as the RC is out.
     
    You cannot authenticate a request with the same credentials from different machines or browsers at the same time. This restriction applies only to accounts (users) that are members of the built-in BackendUsers role.

    Sincerely yours,
    Bob
    the Telerik team
    Do you want to have your say when we set our development plans? Do you want to know when a feature you care about is added or when a bug fixed? Explore the Telerik Public Issue Tracking system and vote to affect the priority of the items
  23. Phil
    Phil avatar
    89 posts
    Registered:
    19 Oct 2010
    22 Nov 2010
    Link to this post
    Ivan/Bob:

    Bob wrote  " I will post some examples, including web service authentication from other applications,  as soon as the RC is out."

    Would you mind posting this now?

    Thanks
  24. Ivan Dimitrov
    Ivan Dimitrov avatar
    16072 posts
    Registered:
    19 Sep 2016
    22 Nov 2010
    Link to this post
    Hello Phil,

    Please check this forum post.

    Best wishes,
    Ivan Dimitrov
    the Telerik team
    Do you want to have your say when we set our development plans? Do you want to know when a feature you care about is added or when a bug fixed? Explore the Telerik Public Issue Tracking system and vote to affect the priority of the items
  25. mattc
    mattc avatar
    105 posts
    Registered:
    11 Aug 2007
    08 Feb 2011
    Link to this post
    Realise this is old now.

    Trying to log in a user I just created using this but I'm not seeing the SetAuthenticationCookie method in the final release version, did it make it in?, API docs still seem to say so.

     SecurityManager.SetAuthenticationCookie(SystemManager.CurrentHttpContext, user.ProviderName, user, true);

    M
  26. Ivan Dimitrov
    Ivan Dimitrov avatar
    16072 posts
    Registered:
    19 Sep 2016
    11 Feb 2011
    Link to this post
    Hi mattc,

    I sent  reply to your support requests.  The SetAuthenticationCookie was made internal static and it is not possible to use it. Currently you should use SecurityManager.AuthenticateUser method.

    Regards,
    Ivan Dimitrov
    the Telerik team
    Do you want to have your say when we set our development plans? Do you want to know when a feature you care about is added or when a bug fixed? Explore the Telerik Public Issue Tracking system and vote to affect the priority of the items
  27. mattc
    mattc avatar
    105 posts
    Registered:
    11 Aug 2007
    15 Feb 2011
    Link to this post
    Hi Ivan

    Yes thanks for that :)

    So after creating the user I used:
    TextBox Password = (TextBox)CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("Password");
    SecurityManager.AuthenticateUser(user.ProviderName, user.UserName, Password.Text, true);

    Using the AuthenticateUser you need to use the password in clear text as user.Password is already hashed.

    HTH

    Matt
  28. Miles
    Miles avatar
    32 posts
    Registered:
    23 Nov 2011
    05 Mar 2012
    Link to this post
    Hopefully someone will see this at the end of this long thread...

    I've tried to implement the logic mentioned above and I am unable to get it to work using Sitefinity 4. Everything seems fine in the code below but after I redirect the user, the user is not authenticated (I'm seeing this by catching all exceptions in the Global.ascx and the exceptions message is "You are not authorized to access this page").

    Here is my current code block:

    protected void linkButtonLogin_Click(object sender, EventArgs e)
    {
        var manager = UserManager.GetManager();
        string userName = textboxUsername.Text.Trim();
        string password = textboxPassword.Text.Trim();
     
        if (manager.ValidateUser(userName, password))
        {
            DateTime now = DateTime.UtcNow;
            var user = manager.GetUser(userName);
            user.IsLoggedIn = true;
            user.LastLoginIp = SystemManager.CurrentHttpContext.Request.UserHostAddress;
            user.LastLoginDate = now;
            user.LastActivityDate = now;
            var loginReason = SecurityManager.AuthenticateUser(user.ProviderName, userName, password, true);
            manager.Provider.SuppressSecurityChecks = true;
            manager.SaveChanges();
            manager.Provider.SuppressSecurityChecks = false;
     
            FormsAuthentication.SetAuthCookie(userName, true);
     
            if (Request["returnUrl"] == null)
                Response.Redirect(String.Format("{0}://{1}", Request.Url.Scheme, Request.Url.Authority));
            else
                Response.Redirect(Request["returnUrl"]);
            //
        }
        else
            literalErroMessage.Text = "Invalid username/password combination";
        //
    }

    Am I missing something?
  29. Gerrit
    Gerrit avatar
    30 posts
    Registered:
    28 Jul 2010
    06 Mar 2012
    Link to this post
    Hi Miles,

    From my experience with Sitefinity, that error is not because the user is not authenticated, its because the user does not have access to the a certain page.

    Check the user role of the user logging in, and then check which user roles have access to the page you are trying to view.

    Kind Regards,
    Gerrit
  30. Miles
    Miles avatar
    32 posts
    Registered:
    23 Nov 2011
    06 Mar 2012
    Link to this post
    Thanks Gerrit.

    I'm actually logging in as the system administrator and I'm still not being authenticated. I can follow the same steps but use the default login control used to log into the backend and then I'm able to access my specific pages :(
38 posts, 1 answered
1 2