locked
How to catch maintain session UserId Asp.Net.DefaultAuthenticationTypes RRS feed

  • Question

  • User-218090889 posted

    I use Asp.Net Identity in Visual Studio 2015 framework 4.5.1, I want to catch and maintain user's ID as Session [UserId] when user login.

    this is my Login code

     protected void LogIn(object sender, EventArgs e)
            {
                if (IsValid)
                {
                    // Validate the user password
                    var manager = Context.GetOwinContext().GetUserManager<ApplicationUserManager>();
                    var signinManager = Context.GetOwinContext().GetUserManager<ApplicationSignInManager>();
    
                    // This doen't count login failures towards account lockout
                    // To enable password failures to trigger lockout, change to shouldLockout: true
                    var result = signinManager.PasswordSignIn(Email.Text, Password.Text, RememberMe.Checked, shouldLockout: false);
    
                    switch (result)
                    {
                        case SignInStatus.Success:
                            IdentityHelper.RedirectToReturnUrl("/userpage.aspx", Response);
                            break;
                        case SignInStatus.LockedOut:
                            Response.Redirect("/Account/Lockout");
                            break;
                        case SignInStatus.RequiresVerification:
                            Response.Redirect(String.Format("/Account/TwoFactorAuthenticationSignIn?ReturnUrl={0}&RememberMe={1}", 
                                                            Request.QueryString["ReturnUrl"],
                                                            RememberMe.Checked),
                                              true);
                            break;
                        case SignInStatus.Failure:
                        default:
                            FailureText.Text = "Invalid login attempt";
                            ErrorMessage.Visible = true;
                            break;
                    }
                    
                }
            }
        }

    This is my AplicationUser class in Identity.Model

     public class ApplicationUser : IdentityUser
        {
            public ClaimsIdentity GenerateUserIdentity(ApplicationUserManager manager)
            {
                // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
                var userIdentity = manager.CreateIdentity(this, DefaultAuthenticationTypes.ApplicationCookie);
                // Add custom user claims here
                userIdentity.AddClaim(new Claim("UserId", this.Id));
    
                return userIdentity;
            }
    
            public Task<ClaimsIdentity> GenerateUserIdentityAsync(ApplicationUserManager manager)
            {
                return Task.FromResult(GenerateUserIdentity(manager));
            }
        }

    This is My Startup Auth

     public void ConfigureAuth(IAppBuilder app)
            {
                // Configure the db context, user manager and signin manager to use a single instance per request
                app.CreatePerOwinContext(ApplicationDbContext.Create);
                app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
                app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);
    
                // Enable the application to use a cookie to store information for the signed in user
                // and to use a cookie to temporarily store information about a user logging in with a third party login provider
                // Configure the sign in cookie
    
                app.UseCookieAuthentication(new CookieAuthenticationOptions
                {
                    AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                    LoginPath = new PathString("/Account/Login"),
                    Provider = new CookieAuthenticationProvider
                    {
                        OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
                            validateInterval: TimeSpan.FromMinutes(30),
                            regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
                    }
                });

    So, how do catch the userID and store it for other uses

    Tuesday, January 15, 2019 7:43 AM

Answers

  • User-218090889 posted

    Thanks Ackerly Xu, I took another approach to resolve the issue. I used the code below

    string userId = User.Identity.GetUserId();
    var user = (new ApplicationDbContext()).Users.FirstOrDefault(s => s.Id == userId);

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, January 16, 2019 7:59 AM

All replies

  • User-893317190 posted

    Hi Enzyme,

    If the user has logged in , you could get the username through HttpContext.Current.User.

    IPrincipal principle=   HttpContext.Current.User;
                 IIdentity  identity =  principle.Identity;
                  string name =  identity.Name;

    Then you could get the IdentityUser  by UserManager according to the username.

    Also,it seems you could get the email of the user. You could get the user through UserManger's findXXX method.

    UserManager.FindByEmail

    Finally , you could save it in session.

    Best regards,

    Ackerly Xu

     

    Tuesday, January 15, 2019 9:53 AM
  • User-218090889 posted

    IPrincipal principle=   HttpContext.Current.User;
                 IIdentity  identity =  principle.Identity;
                  string name =  identity.Name;

    Ackerly Xu, thank you for your response, but how do I place this code on my page using my codes in the above page of this post?
    Note, I am still new to this.

    Wednesday, January 16, 2019 3:19 AM
  • User-893317190 posted

    Hi Enzyme,

    After the user has logged in successfully , you could find the user using UserManager and save the found user in Session.

     case SignInStatus.Success:
    // get the user using UserManager
    ApplicationUser user = manager.FindByEmail(the user's email);
    string id = user.Id;
    Session["user_id"] = id; IdentityHelper.RedirectToReturnUrl("/userpage.aspx", Response);

    Best regards,

    Ackerly Xu

    Wednesday, January 16, 2019 5:19 AM
  • User-218090889 posted

    Thanks Ackerly Xu, I took another approach to resolve the issue. I used the code below

    string userId = User.Identity.GetUserId();
    var user = (new ApplicationDbContext()).Users.FirstOrDefault(s => s.Id == userId);

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, January 16, 2019 7:59 AM