none
Autologin with forms authentication

    Question

  • Hi All,

    I am trying to figure how to login as another user through code. I am using claims autherntication and I have a custom login page. This is what I have tried...

    On Page load,

        string newPassword = Membership.Provider.ResetPassword(username, String.Empty);

        if (Membership.ValidateUser(userId, newPassword))
        {
                 FormsAuthentication.RedirectFromLoginPage(userId, false);
        }

    This isn't working. I am getting "403 FORBIDDEN" error.

    What is that I am missing here?

    How can we login as another user in Sharepoint 2010 Claims authertication..?

    Thanks in Advance,


    Friday, March 02, 2012 2:36 AM

Answers

  • Hi, 

    This method I've used (sorry, but without comments in code)

            internal enum SPSessionTokenWriteType
            {
                NoCookie,
                WriteDefaultCookie,
                WriteSessionCookie,
                WritePersistentCookie
            }
            private SPIisSettings IisSettings
            {
                get
                {
                    SPWebApplication webApp = SPWebApplication.Lookup(new Uri(SPContext.Current.Web.Url));
                    SPIisSettings settings = webApp.IisSettings[SPUrlZone.Default];
                    return settings;
                }
            }
     
            private SecurityToken GetSecurityToken(string username, string password)
            {
                SecurityToken token = null;
                SPIisSettings iisSettings = IisSettings;
                Uri appliesTo = new Uri(Page.Request.Url.AbsoluteUri);
     
                if (string.IsNullOrEmpty(username) ||
                    string.IsNullOrEmpty(password))
                    return null;
     
                SPFormsAuthenticationProvider authProvider = iisSettings.FormsClaimsAuthenticationProvider;
                token = SPSecurityContext.SecurityTokenForFormsAuthentication(
                    appliesTo,
                    authProvider.MembershipProvider,
                    authProvider.RoleProvider,
                    username,
                    password);
     
                return token;
            }
     
            private void EstablishSessionWithToken(SecurityToken securityToken, SPSessionTokenWriteType sessionCookie)
            {
                if (null == securityToken)
                {
                    throw new ArgumentNullException("securityToken");
                }
                
                SPFederationAuthenticationModule fam = SPFederationAuthenticationModule.Current;
                if (null == fam)
                {
                    throw new ArgumentException(null"FederationAuthenticationModule");
                }
     
                typeof(SPFederationAuthenticationModule).GetMethod("SetPrincipalAndWriteSessionToken"BindingFlags.Instance | BindingFlags.InvokeMethod | BindingFlags.NonPublic)
                        .Invoke(fam, new object[] { securityToken, sessionCookie });
     
                //fam.SetPrincipalAndWriteSessionToken(securityToken);
            }

    And sign in: 

                    bool flag = false;
     
                    using (new SPMonitoredScope("FormsSignInPage.AuthenticateEventHandler: Retrieve security token and establish session."))
                    {
                        string login = loginTextBox.Text;
                        string password = passwordTextBox.Password;
                        SecurityToken securityToken = null;
     
                        try
                        {
                            securityToken = this.GetSecurityToken(login, password);
                            if (securityToken == null)
                            {
                                flag = false;
                            }
                            else
                            {
                                SPSessionTokenWriteType writeDefaultCookie = SPSessionTokenWriteType.WriteDefaultCookie;
                                if (!SPSecurityTokenServiceManager.Local.UseSessionCookies && !rememberMeCheckBox.Checked)
                                {
                                    writeDefaultCookie = SPSessionTokenWriteType.WriteSessionCookie;
                                }
                                this.EstablishSessionWithToken(securityToken, writeDefaultCookie);
                                flag = true;
                            }
                        }
                        catch (Exception ex)
                        {
                            flag = false;
                        }
                    }

    Also you need to add System.IdentityModel.dll, Microsoft.SharePoint.IdentityModel.dll and Microsoft.IdentityModel.dll into project 

    • Marked as answer by Sarath Raj. A Friday, March 02, 2012 4:42 PM
    Friday, March 02, 2012 8:19 AM
  • Thanks Alexander Kovalev...

    Yesterday night, I was trying to figure this same thing by using reflection... I also realized that the FedAuth cookie is the key.. So tried to set it through code... Then I saw this function out there, that actually does what I wanted....

    SPClaimsUtility.AuthenticateFormsUser

    This did the trick.. It actually does pretty much everything that your code does..

    I feel so dump that I didn't look for it at the first place...

    Anyways.. Thank you all for the response...

    • Marked as answer by Sarath Raj. A Friday, March 02, 2012 4:42 PM
    Friday, March 02, 2012 4:42 PM

All replies

  • Hi, 

    This method I've used (sorry, but without comments in code)

            internal enum SPSessionTokenWriteType
            {
                NoCookie,
                WriteDefaultCookie,
                WriteSessionCookie,
                WritePersistentCookie
            }
            private SPIisSettings IisSettings
            {
                get
                {
                    SPWebApplication webApp = SPWebApplication.Lookup(new Uri(SPContext.Current.Web.Url));
                    SPIisSettings settings = webApp.IisSettings[SPUrlZone.Default];
                    return settings;
                }
            }
     
            private SecurityToken GetSecurityToken(string username, string password)
            {
                SecurityToken token = null;
                SPIisSettings iisSettings = IisSettings;
                Uri appliesTo = new Uri(Page.Request.Url.AbsoluteUri);
     
                if (string.IsNullOrEmpty(username) ||
                    string.IsNullOrEmpty(password))
                    return null;
     
                SPFormsAuthenticationProvider authProvider = iisSettings.FormsClaimsAuthenticationProvider;
                token = SPSecurityContext.SecurityTokenForFormsAuthentication(
                    appliesTo,
                    authProvider.MembershipProvider,
                    authProvider.RoleProvider,
                    username,
                    password);
     
                return token;
            }
     
            private void EstablishSessionWithToken(SecurityToken securityToken, SPSessionTokenWriteType sessionCookie)
            {
                if (null == securityToken)
                {
                    throw new ArgumentNullException("securityToken");
                }
                
                SPFederationAuthenticationModule fam = SPFederationAuthenticationModule.Current;
                if (null == fam)
                {
                    throw new ArgumentException(null"FederationAuthenticationModule");
                }
     
                typeof(SPFederationAuthenticationModule).GetMethod("SetPrincipalAndWriteSessionToken"BindingFlags.Instance | BindingFlags.InvokeMethod | BindingFlags.NonPublic)
                        .Invoke(fam, new object[] { securityToken, sessionCookie });
     
                //fam.SetPrincipalAndWriteSessionToken(securityToken);
            }

    And sign in: 

                    bool flag = false;
     
                    using (new SPMonitoredScope("FormsSignInPage.AuthenticateEventHandler: Retrieve security token and establish session."))
                    {
                        string login = loginTextBox.Text;
                        string password = passwordTextBox.Password;
                        SecurityToken securityToken = null;
     
                        try
                        {
                            securityToken = this.GetSecurityToken(login, password);
                            if (securityToken == null)
                            {
                                flag = false;
                            }
                            else
                            {
                                SPSessionTokenWriteType writeDefaultCookie = SPSessionTokenWriteType.WriteDefaultCookie;
                                if (!SPSecurityTokenServiceManager.Local.UseSessionCookies && !rememberMeCheckBox.Checked)
                                {
                                    writeDefaultCookie = SPSessionTokenWriteType.WriteSessionCookie;
                                }
                                this.EstablishSessionWithToken(securityToken, writeDefaultCookie);
                                flag = true;
                            }
                        }
                        catch (Exception ex)
                        {
                            flag = false;
                        }
                    }

    Also you need to add System.IdentityModel.dll, Microsoft.SharePoint.IdentityModel.dll and Microsoft.IdentityModel.dll into project 

    • Marked as answer by Sarath Raj. A Friday, March 02, 2012 4:42 PM
    Friday, March 02, 2012 8:19 AM
  • Hello Sarath Raj,

    As per my understand, you need to make basic authentication enable as you are passing your username and password in clear text.

    Please Mark as answer if it's resolve your issue.

    Friday, March 02, 2012 8:24 AM
  • Thanks Alexander Kovalev...

    Yesterday night, I was trying to figure this same thing by using reflection... I also realized that the FedAuth cookie is the key.. So tried to set it through code... Then I saw this function out there, that actually does what I wanted....

    SPClaimsUtility.AuthenticateFormsUser

    This did the trick.. It actually does pretty much everything that your code does..

    I feel so dump that I didn't look for it at the first place...

    Anyways.. Thank you all for the response...

    • Marked as answer by Sarath Raj. A Friday, March 02, 2012 4:42 PM
    Friday, March 02, 2012 4:42 PM
  • Actually SPClaimsUtility.AuthenticateFormsUser doesn't do exactly what Alexander's code is doing. Specifically, SPClaimsUtility.AuthenticateFormsUser  always generates a persistent cookie, which might not always be desirable (think of someone connecting to SharePoint extranet site on a public machine, for instance).

    Alexander's code is the only way to generate either a persistent or non-persistent cookie, depending on a few factors (whether session cookies are used or not - by default, they're not used - and whether the user checks the "Sign me in automatically" checkbox which only appears if the session cookies are disabled).

    However, Alexander's code breaks in recent SharePoint Cumulative Updates (at least from the December 2011 CU onwards), because the method his code calls by reflection (SetPrincipalAndWriteSessionToken) is now public (most likely because Microsoft realized that was the only way 3rd parties could write a custom sign in page that could replicate the full functionality of SharePoint's default Sign In Page).

    With recent CUs you can now write:

    fam.SetPrincipalAndWriteSessionToken(securityToken, writeOperationType);
    

    instead of:

    typeof(SPFederationAuthenticationModule).GetMethod("SetPrincipalAndWriteSessionToken", BindingFlags.Instance | BindingFlags.InvokeMethod | BindingFlags.NonPublic)
                        .Invoke(fam, new object[] { securityToken, sessionCookie });


    Raphael Londner - www.riolinx.com

    Monday, May 07, 2012 1:12 PM
  • Hi Everyone,

    I am trying the same solution which Alexander has told and it's working as well and I am using persistent cookie. And I have set "FormsTokenLifetime" in SP 2010 to 1000 days. But I am facing a problem that if the user logs in to the site and closes the browser and when trying to access the site after 1 or 2 days then the user is not remembered. But I can see the "FedAuth" is still there.

    Can you please suggest me a solution or if I am going somewhere wrong.

    Friday, December 07, 2012 11:15 AM