Programmatic Login

Posted by Community Admin on 03-Aug-2018 22:05

Programmatic Login

All Replies

Posted by Community Admin on 21-Oct-2010 00:00

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

Posted by Community Admin on 22-Oct-2010 00:00

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

Posted by Community Admin on 22-Oct-2010 00:00

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

Posted by Community Admin on 08-Nov-2010 00:00

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

Posted by Community Admin on 09-Nov-2010 00:00

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


Posted by Community Admin on 10-Nov-2010 00:00

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

Posted by Community Admin on 11-Nov-2010 00:00

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

Posted by Community Admin on 11-Nov-2010 00:00

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>

Posted by Community Admin on 11-Nov-2010 00:00

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

Posted by Community Admin on 11-Nov-2010 00:00

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

Posted by Community Admin on 12-Nov-2010 00:00

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!

Posted by Community Admin on 12-Nov-2010 00:00

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.

Posted by Community Admin on 12-Nov-2010 00:00

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

Posted by Community Admin on 12-Nov-2010 00:00

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!

Posted by Community Admin on 12-Nov-2010 00:00

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

Posted by Community Admin on 12-Nov-2010 00:00

Sorry Gerrit, can't think of anything now.

Andrei

Posted by Community Admin on 12-Nov-2010 00:00

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

Posted by Community Admin on 12-Nov-2010 00:00

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

Posted by Community Admin on 15-Nov-2010 00:00

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!

Posted by Community Admin on 15-Nov-2010 00:00

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

Posted by Community Admin on 16-Nov-2010 00:00

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

Posted by Community Admin on 16-Nov-2010 00:00

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

Posted by Community Admin on 22-Nov-2010 00:00

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

Posted by Community Admin on 22-Nov-2010 00:00

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

Posted by Community Admin on 08-Feb-2011 00:00

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

Posted by Community Admin on 11-Feb-2011 00:00

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

Posted by Community Admin on 15-Feb-2011 00:00

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

Posted by Community Admin on 05-Mar-2012 00:00

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?

Posted by Community Admin on 06-Mar-2012 00:00

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

Posted by Community Admin on 06-Mar-2012 00:00

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 :(

Posted by Community Admin on 20-Apr-2012 00:00

Hi Miles -

Did you ever find a solution to this?
Having the same exact issue.

David

Posted by Community Admin on 26-Apr-2012 00:00

Yes I was but I'm not 100% how correct this is - I'm never 100% when working with Sitefinity :P

01.protected void linkButtonLogin_Click(object sender, EventArgs e)
02.
03.    var manager = UserManager.GetManager();
04.    string userName = textboxUsername.Text.Trim();
05.    string password = textboxPassword.Text.Trim();
06. 
07.    if (manager.ValidateUser(userName, password))
08.    
09.        DateTime now = DateTime.UtcNow;
10.        var user = manager.GetUser(userName);
11.        user.IsLoggedIn = true;
12.        user.LastLoginIp = SystemManager.CurrentHttpContext.Request.UserHostAddress;
13.        user.LastLoginDate = now;
14.        user.LastActivityDate = now;
15.        var loginReason = SecurityManager.AuthenticateUser(UserManager.GetDefaultProviderName(), userName, password, true);
16. 
17.        if (loginReason == UserLoggingReason.UserAlreadyLoggedIn)
18.        
19.            SecurityManager.Logout(UserManager.GetDefaultProviderName(), user.Id);
20.            loginReason = SecurityManager.AuthenticateUser(UserManager.GetDefaultProviderName(), userName, password, true);
21.        
22. 
23.        if (loginReason == UserLoggingReason.Success)
24.        
25.            manager.Provider.SuppressSecurityChecks = true;
26.            manager.SaveChanges();
27. 
28.            FormsAuthentication.SetAuthCookie(userName, true);
29. 
30.            if (Request["returnUrl"] == null)
31.                Response.Redirect(String.Format("0://1", Request.Url.Scheme, Request.Url.Authority));
32.            else
33.                Response.Redirect(Request["returnUrl"]);
34.            //
35.        
36.        else
37.            literalErrorMessage.Text = loginReason.ToString();
38.        //
39.    
40.    else
41.        literalErrorMessage.Text = "Invalid username or password";
42.    //
43.

Posted by Community Admin on 27-Apr-2012 00:00

Thanks Miles - we give this a try today!

David

Posted by Community Admin on 24-Apr-2015 00:00

Hello. I'm new to Sitefinity and so I decided to learn about it using a sample app from the SDK. I'm using the Telerik.Sitefinity.Samples.Quantum app. I imported it in my Visual Studio and added a web form to the project (ShowClaims.aspx) which is a page that will simply display the identity claims contained in the security token returned to the app by the STS. Here's my question: How does one go about adding a page to the app from the front end UI? I'm currently logged I the dashboard (http://localhost:60876/Sitefinity/dashboard) which is what I call the front end UI, and I assume that would be the way to add my new page to the app. I see where I can create a new page but where do I point it to the code I entered in Studio?

Posted by Community Admin on 29-Apr-2015 00:00

Hello Patrick,

If you have created the .aspx page in the root of your project folder in Visual Studio, you can access it like the following: yourdomain.com/ShowClaims.aspx.

Another option will be to create a user control (.ascx file) and place your logic there and build the solution. Then you can register the user control in the Toolbox using Thunder as described in the following article.

After you register the widget, please restart the application and login to the Sitefinity backend, click on the Pages tab and create a new page or open an existing page in edit mode.

When you open a page in edit mode you will see the Toolbox section on the right hand side of the page. This is the section where you can drag and drop the built-in widgets which come with Sitefinity and your custom widgets as well. You should see your custom widget there under the section where you have registered it. After you find your custom widget, please drop it on the page.

If you would like to add a code behind (the aspx.cs file created in Visual Studio) to a Sitefinity page created through the Sitefinity backend, you can checkout the following blog post for more details on this.

In addition to this, since this forum thread is opened to discuss how to login programatically in Sitefinity, I would kindly ask you to open a new thread or open a support ticket if you have any further questions about creating pages or creating widgets in Sitefinity. Thank you for your kind understanding.

Regards,
Sabrie Nedzhip
Telerik

 
Do you want to have your say in the Sitefinity development roadmap? Do you want to know when a feature you requested is added or when a bug fixed? Explore the Telerik Sitefinity CMS Ideas&Feedback Portal and vote to affect the priority of the items
 

Posted by Community Admin on 11-May-2015 00:00

Hi everyone!

 I have a question related to Programmatic Login. I have a situation in which I should login a user based on 3 fields(ID, username, password). The login process is made against an external REST web API.

I tried to implement my own login widget, with these 3 fields, but I could not set authentication cookie, since SecurityManager.SetAuthenticationCookie  is internal - no luck(.

I tried to implement my own custom MembershipProvider, but  SecurityManager.AuthenticateUser(UserManager.GetDefaultProviderName(), userName, password, true); needs only 2 parameters (username and password).

Actually, my question is: Is there a way to implement a login functionality in Sitefinity based on more than just 2 fields (username and password);

Many thanks!

Posted by Community Admin on 14-May-2015 00:00

Hello Vladimir,

Please note that you should use the overloads of the SecurityManager.AuthenticateUser() method to authenticate the users in Sitefinity.

If you would like to allow users to enter their id when they submit their credentials, before the login you can use the API to get the user who has this id and/or the entered username and then log this user:

UserManager userManager = UserManager.GetManager();
 
User user = // get the user here by username or/and by the entered id
  
UserLoggingReason result = SecurityManager.AuthenticateUser(null, "username", true, out user);

Please also refer to this article for more details about authenticating a user in Sitefinty.

Regards,
Sabrie Nedzhip
Telerik
 
Do you want to have your say in the Sitefinity development roadmap? Do you want to know when a feature you requested is added or when a bug fixed? Explore the Telerik Sitefinity CMS Ideas&Feedback Portal and vote to affect the priority of the items
 

Posted by Community Admin on 15-May-2015 00:00

Hi Sabrie!

 That's great, I didn't noticed that overload of the method. BUT, it returns also a USER(as out parameter). What it actually does - calls my custom membership method GetUser(string username). Here comes the problem. I could not call my API only with username parameter. An access token should also be provided. So my membership provider could not access my web API to get a user.

 I tried a workaround. Created a method SetToken(string token) to membership provider. Than, when I GetUser(string) is called by SecurityManager.AuthenticateUser(string,string,bool,out User), I try to get the User.

I'm not quite sure if it is a good implementation. Is membership implementation is Singleton throughout Sitefinty?(because other users will also supply their tokens to custom provider)

Do you have any ideas?

Many thanks!

This thread is closed