34

I need to get the UserId Guid directly after a successful login. The following code doesn't work:

if (Membership.ValidateUser(txtUsername.Value, txtPassword.Value))
{
    FormsAuthentication.SignOut();
    FormsAuthentication.SetAuthCookie(txtUsername.Value, true);

    if (HttpContext.Current.User.Identity.IsAuthenticated)
    {
        // doesn't run
        Guid puk = (Guid)Membership.GetUser().ProviderUserKey;            
    }
}

The following code does work:

if (Membership.ValidateUser(txtUsername.Value, txtPassword.Value))
{
    FormsAuthentication.SignOut();
    FormsAuthentication.SetAuthCookie(txtUsername.Value, true);

    MembershipUser user = Membership.GetUser(txtUsername.Value);

    if (user != null)
    {
        Guid puk = (Guid)user.ProviderUserKey;
    }
}

Why does this happen? Is there something more to do besides SetAuthCookie?

5 Answers 5

24

I had the same problem too. I forgot to set the web.config configuration.

Maybe you missed too.

   <system.web> 
    <authentication mode="Forms">
      <forms loginUrl="~/user/login" timeout="1000" name="__Auth" />
    </authentication>  
  </system.web> 
19

Because when you call FormsAuthentication.SetAuthCookie(txtUsername.Value, true); you store the key on the client's cookies. For this you need to do a response to the user. And for HttpContext.Current.User.Identity to be filled with cookie you need one more request.

In short your scheme looks like this:

  1. Client sends his UserName and Password.

  2. Server gets and checks it. If they are valid the server sends Set-Cookie header to the client.

  3. Client receives and stores it. For each request client sends cookies back to the server.

UPDATE for @Jake

Adding an example of setting User in HttpContext

var identity = new System.Security.Principal.GenericIdentity(user.UserName);
var principal = new GenericPrincipal(identity, new string[0]);
HttpContext.Current.User = principal;
Thread.CurrentPrincipal = principal;  

Note that you could create your custom principal class inheriting from GenericPrincipal or ClaimsPrincipal

3
  • Is there any way to access User Identity in the same request? Commented Aug 29, 2015 at 7:09
  • 1
    @AhmadAhmadi you can set it manually assigning CustomPrincipal object to User property of HttpContext. Commented Aug 30, 2015 at 19:31
  • 1
    @OleksiiAza Could you possibly update your answer to show how to do this?
    – Jake
    Commented Dec 20, 2017 at 19:01
4

In my development environment case, requireSSL property was set to true, I fixed the problem by changing it to requireSSL = false.

enter image description here

3

I tried all the above solutions ,but the thing that solves my problem was commenting this in web.config

 <modules>
  <remove name="FormsAuthentication"/>
 </modules>
2
  • This would remove forms authentication altogether, so of course that would let the user go by.
    – Synctrex
    Commented Oct 1, 2018 at 19:17
  • This didn't remove forms authentication but I'm not sure what it's doing. The true/false is now working with that module removed;... odd?
    – Gratzy
    Commented Oct 25, 2018 at 13:55
0

I got this error in a Blazor .NET 6 WASM application. I followed the guide below to expose the authentication state as a cascading parameter:

https://learn.microsoft.com/en-us/aspnet/core/blazor/security/?view=aspnetcore-6.0#expose-the-authentication-state-as-a-cascading-parameter

This worked well but when used with OnInitializedAsync user.Identity.IsAuthenticated was set to false after successful login but worked when the page was refreshed.

Changing component lifecycle to OnParametersSetAsync instead fixed the problem.

https://learn.microsoft.com/en-us/aspnet/core/blazor/components/lifecycle?view=aspnetcore-6.0#after-parameters-are-set-onparameterssetasync

Complete code in MainLayout.razor:

@code {
    bool loadData = true;

    [CascadingParameter]
    private Task<AuthenticationState> authenticationStateTask { get; set; }

    protected override async Task OnParametersSetAsync()
    {
        var authState = await authenticationStateTask;
        var user = authState.User;

        if (user.Identity.IsAuthenticated)
        {
            loadData = true;

            await StateContainer.LoadDataAsync();

            loadData = false;
        }
        else
        {
            loadData = false;
        }
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.