locked
LoginView - Username is not displayed after successful login (Premature Redirection) (Identity Framework 2) RRS feed

  • Question

  • User397679718 posted

    Problem: For some reason the <LoggedInTemplate> isn't being used to display the logged in status after a successful login after being redirected back to the calling page.  The <AnonymousTemplate> which display a link to Login is always used.  This same behavior continues after each successful login.

    Clue: I commented out the redirect line [IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response); ] on the login,aspx.cs right after the call to SignIn().   After a successful login; the login page is then displayed again. (post back)  Afterward all pages on the site use the <LoggedInTemplate> and display the Username and link to manage account. 

    Thanks in advance for your support!  Have a blessed day!

    web.config (root)

    <system.web>
      ...
      <authentication mode="Forms" />
      ...
    <system.web/>

    web.config (/Accounts)

    <location path="Manage.aspx">
      <system.web>
        <authorization>
          <deny users="?"/>
        </authorization>
      </system.web>
    </location>

    ASPX (in Master Page)

    <asp:LoginView runat="server">
      <AnonymousTemplate>                                                                                                
        <li>
          <%--<a href="javascript:void(0);" onclick="return ShowLogin();"><i class="fa fa-lock fa-fw"></i>Login</a>--%>
          <% Response.Write("<a + href=\"/Account/Login.aspx?ReturnUrl=" + HttpContext.Current.Request.Url.AbsolutePath + "\"" + "><i class=\"fa fa-lock fa-fw\"></i> Login</a>"); %>                                    
        </li>                                
      </AnonymousTemplate>
      <LoggedInTemplate>                            
        <li class="dropdown">                                
          <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false"><i class="fa fa-user fa-fw"></i><%: Web.IdentityHelper.GetUserFullName(Context.User.Identity.GetUserId())  %><span class="caret"></span></a>                                                                                                      
          <ul class="dropdown-menu">
            <li><a runat="server" href="~/Account/Manage" title="Manage your account">Manage Account</a></li>
            <li><asp:LoginStatus runat="server" LogoutAction="Refresh" LogoutText="Log off" LogoutPageUrl="~/" OnLoggingOut="Unnamed_LoggingOut" /></li>              
          </ul>  
        </li>                                                                       
      </LoggedInTemplate>
    </asp:LoginView>

    login.aspx.cs

    protected void LogIn(object sender, EventArgs e)
    {
      if (IsValid)
      {
        // Validate the user password
        var manager = Context.GetOwinContext().GetUserManager<ApplicationUserManager>();
                    
        ApplicationUser user = manager.Find(Email.Text, Password.Text);
        if (user != null)
        {
          if (!user.EmailConfirmed)
          {
            FailureText.Text = "There's just one more step...   Please check your email (" + user.Email + ") to complete your registration.";
            ErrorMessage.Visible = true;
    
            string code = manager.GenerateEmailConfirmationToken(user.Id);
            string callbackUrl = IdentityHelper.GetUserConfirmationRedirectUrl(code, user.Id);
    
            var HtmlEmailTemplateTokenKeys = new List<string>(new string[] { "{Username}", "{ActivateRegistrationUrl}" });
            var HtmlEmailTemplateTokenValues = new List<string>(new string[] { user.Firstname, callbackUrl });
    
            string HtmlEmailMessage = HtmlEmail.LoadFromTemplate("RegistrationActivation.html", HtmlEmailTemplateTokenKeys, HtmlEmailTemplateTokenValues);
            manager.SendEmail(user.Id, "Eagle Research Corporation - Registration Activation", HtmlEmailMessage);                        
                            
          }
          else
          {
            IdentityHelper.SignIn(manager, user, RememberMe.Checked);                        
            IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response);                        
          }
        }
        else
        {                    
          FailureText.Text = "Invalid Username or Password";
          ErrorMessage.Visible = true;
        }
      }
    }

    Friday, May 4, 2018 11:49 AM

Answers

  • User397679718 posted

    IdentityHelper.RedirectToReturnUrl - Original Code

    <div class="comment-right-col comment-body">

    public static void RedirectToReturnUrl(string returnUrl, HttpResponse response)
    {
    if (!String.IsNullOrEmpty(returnUrl) && IsLocalUrl(returnUrl))
    { 
    response.Redirect(returnUrl);
    }
    else
    {
    response.Redirect("~/");
    }
    }

    IdentityHelper.RedirectToReturnUrl - Fixed Code

    public static void RedirectToReturnUrl(string returnUrl, HttpResponse response)
    {
    if (!String.IsNullOrEmpty(returnUrl) && IsLocalUrl(returnUrl))
    { 
    response.Redirect(returnUrl,false); // Do not response end.
    }
    else
    {
    response.Redirect("~/",false); // Do not response end.
    }
    }

    </div>

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, May 9, 2018 5:07 PM

All replies

  • User-166373564 posted

    Since you are using ASP.NET Identity, you do not need to configure the forms-based authentication in your Web.config file. You may need to remove FormsAuthentication as follows:

    <system.webServer>
      <modules>
        <remove name="FormsAuthentication" />
      </modules>
    </system.webServer>

    Based on your code, you may created the ASP.NET Web Forms Site with identity authentication and adjusted some code. Per my test, the LoginView feature could work as expected in a new ASP.NET Web Forms Site project.

    For identity authentication, your project may leverage UseCookieAuthentication middle-ware for authentication. I am not sure why you also enabled forms-based authentication. Per my understanding, you need to disable forms-based authentication.

    For Forms Authentication, you need to generate the forms authentication cookie as follows:

    FormsAuthentication.RedirectFromLoginPage(txtUserName.Value,chkPersistCookie.Checked);

    Additionally, you could follow How To Implement Forms-Based Authentication in Your ASP.NET Application by Using C#.NET and Adding ASP.NET Identity to an Empty or Existing Web Forms Project.

    Monday, May 7, 2018 9:24 AM
  • User397679718 posted

    Sorry for the confusion regarding form authentication in the original post.  Authentication was/is actually set to None. (i.e. <authentication mode="None" />) I'd set it to "Forms" in response to another thread for testing and forgot to set it back to None after it failed to correct the issue.  Also (<remove name="FormsAuthenticationModule" />)  is already in place.

    <system.web>
    ...
      <authentication mode="None" />
    ...
    </system.web>
    
    <system.webServer>    
      <modules>
        <remove name="FormsAuthenticationModule" />
      </modules>
      <validation validateIntegratedModeConfiguration="false" />
      <handlers>
          <add name="Telerik_Web_UI_WebResource_axd" verb="*" preCondition="integratedMode" path="Telerik.Web.UI.WebResource.axd" type="Telerik.Web.UI.WebResource" />
      </handlers>
        <staticContent>
        <remove fileExtension=".mp4"/>
        <mimeMap fileExtension=".mp4" mimeType="video/mp4"/>
      </staticContent>
      <httpProtocol>
        <customHeaders>
          <add name="X-Frame-Options" value="SAMEORIGIN" />
          <add name="X-XSS-Protection" value="1" />
          <add name="X-Content-Type-Options" value="nosniff" />
        </customHeaders>
      </httpProtocol>
    </system.webServer>

    Tuesday, May 8, 2018 12:39 PM
  • User397679718 posted

    IdentityHelper.RedirectToReturnUrl - Original Code

    <div class="comment-right-col comment-body">

    public static void RedirectToReturnUrl(string returnUrl, HttpResponse response)
    {
    if (!String.IsNullOrEmpty(returnUrl) && IsLocalUrl(returnUrl))
    { 
    response.Redirect(returnUrl);
    }
    else
    {
    response.Redirect("~/");
    }
    }

    IdentityHelper.RedirectToReturnUrl - Fixed Code

    public static void RedirectToReturnUrl(string returnUrl, HttpResponse response)
    {
    if (!String.IsNullOrEmpty(returnUrl) && IsLocalUrl(returnUrl))
    { 
    response.Redirect(returnUrl,false); // Do not response end.
    }
    else
    {
    response.Redirect("~/",false); // Do not response end.
    }
    }

    </div>

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, May 9, 2018 5:07 PM