How to access the database data in OnSignedIn .net Core - Entity framework

Viewed 151

When a user signs in to a .net core MVC program, I need to view user-specific data from the database using logged in user id and save those data to current cookie. Following is the path I'm now taking. Show me how to do this if something is wrong.

is there any way access like

dbcontext.footable.where(x=> x.id = "somevalue")

Startup.cs

services.ConfigureIdentitySettings(apiSetting);

ConfigureIdentitySettings.cs

public static class IdentitySettingsExtensions
    {
        // Identity Setup
        public static void ConfigureIdentitySettings(this IServiceCollection services, IConfigurationSection apiSetting)
        {
            services.ConfigureApplicationCookie(options =>
            {
                options.Cookie.Name = "foo";
                options.ExpireTimeSpan = TimeSpan.FromMinutes(Configurations.ExipireTimeSpan);
                options.ReturnUrlParameter = CookieAuthenticationDefaults.ReturnUrlParameter;
                options.LoginPath = Configurations.LoginPath;
                options.LogoutPath = Configurations.LogoutPath;
                options.AccessDeniedPath = Configurations.AccessDeniedPath;
                options.SlidingExpiration = true;
                options.Events = new CookieAuthenticationEvents
                {
                    OnSignedIn = context =>
                    {
                        // Here i got current logged in user id
                        var loggedInUserRole = context.Principal.GetLoggedInUserId();

                        //I need to access database data from here after that adding those data into current cookie
                        return Task.CompletedTask;
                    }                    
                };
            });

            services.Configure<IdentityOptions>(options =>
            {
                // Providers
                //options.Tokens.PasswordResetTokenProvider = PasswordResetTokenProviderName;
                //options.Tokens.EmailConfirmationTokenProvider = ConfirmEmailTokenProviderName;
                options.SignIn.RequireConfirmedEmail = true;
                options.User.RequireUniqueEmail = true;              

                options.Password.RequireUppercase = Configurations.RequireUppercase;
                options.Password.RequireLowercase = Configurations.RequireLowercase;
                options.Password.RequireDigit = Configurations.RequireDigit;
                options.Password.RequiredLength = Configurations.RequireLength;
                options.Password.RequireNonAlphanumeric = Configurations.RequireNonAlphanumeric;
            });

            var firstLifeSpan = Convert.ToInt32(apiSetting["FirstEmailConfirmationLifeSpan"]);
            var secondLifeSpan = Convert.ToInt32(apiSetting["SecondEmailConfirmationLifeSpan"]);
            services.Configure<DataProtectionTokenProviderOptions>(o =>
                o.TokenLifespan = TimeSpan.FromDays(firstLifeSpan > secondLifeSpan ? firstLifeSpan : secondLifeSpan));

        }
    }
1 Answers

You can access database data in OnSignedIn method like below:

services.ConfigureApplicationCookie(options =>
{
    //...
    options.Events = new CookieAuthenticationEvents
    {
        OnSignedIn = context =>
        {

            //Build an intermediate service provider
            var sp = services.BuildServiceProvider();

            //Resolve the services from the service provider
            var myDbContext = sp.GetService<ApplicationDbContext>();

            //access database data...
            var data = myDbContext.footable.Where(x => x.Id== "xxx");

            //...
            return Task.CompletedTask;
        }
    };
});
Related