Hi guys I am trying to achieve redirections immediately after Login in a .Net Core 2.1 application using Identity Core.
The redirections are dependent on roles of the logged in user.
I am getting a Null Reference exception.
I read a few stack overflow questions and Git Issues and understood that this is because the user is not stored to the database right after sign in:
var result =await _signInManager.PasswordSignInAsync(Input.Email,Input.Password,Input.RememberMe, lockoutOnFailure:true).Result;
I tried the following to retrieve the role of the logged in user:
Method-1:
string userRole =_signInManager.Context.User.FindFirst(ClaimTypes.Role).Value;
Method-2:
To determine if a user exists in a given role:
User.IsInRole("RoleName")
Method-3:
_userManager.GetClaimsAsync(user)
I am getting a Null reference exception in all cases; I understand this is because of the request not being completed.
However I don't understand the fundamentals.
If not a solution, need direction:)
Thank you:)
This my startup.cs:
publicclassStartup{publicStartup(IConfiguration configuration){Configuration= configuration;}publicIConfigurationConfiguration{get;}// This method gets called by the runtime. Use this method to add services to the container.publicvoidConfigureServices(IServiceCollection services){
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddIdentity<IdentityUser,IdentityRole>().AddEntityFrameworkStores<ApplicationDbContext>();
services.Configure<CookiePolicyOptions>(options =>{// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded= context =>true;
options.MinimumSameSitePolicy=SameSiteMode.None;});
services.ConfigureApplicationCookie(options =>{// Cookie settings
options.Cookie.HttpOnly=true;
options.ExpireTimeSpan=TimeSpan.FromMinutes(30);
options.LoginPath="/Identity/Account/Login";
options.LogoutPath="/Identity/Account/Logout";
options.AccessDeniedPath="/Identity/Account/AccessDenied";
options.SlidingExpiration=true;});
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);}// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.publicvoidConfigure(IApplicationBuilder app,IHostingEnvironment env){if(env.IsDevelopment()){
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();}else{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseAuthentication();
app.UseMvc(routes =>{
routes.MapRoute(
name:"default",template:"{Controller=Home}/{action=Index}/{id?}");});}}
Login - Page controller of Identity core:
publicasyncTask<IActionResult>OnPostAsync(string returnUrl =null){
returnUrl = returnUrl ??Url.Content("return path");if(ModelState.IsValid){var result = _signInManager.PasswordSignInAsync(Input.Email,Input.Password,Input.RememberMe, lockoutOnFailure:true).Result;if(result.Succeeded){var usera =User.IsInRole("Role1");var users =User.IsInRole("Role2");//string userEmail = _signInManager.Context.User.FindFirst(ClaimTypes.Name).Value;//string userRole = _signInManager.Context.User.FindFirst(ClaimTypes.Role).Value;if(User.IsInRole("Admin")){returnRedirectToAction("path1");}elseif(User.IsInRole("Supervisor")){returnRedirectToAction("path2");}elseif(User.IsInRole("Member")){returnRedirectToAction("path3");}else{returnRedirectToPage("/Identity/Account/AccessDenied");}}if(result.RequiresTwoFactor){returnRedirectToPage("./LoginWith2fa",new{ReturnUrl= returnUrl,RememberMe=Input.RememberMe});}if(result.IsLockedOut){
_logger.LogWarning("User account locked out.");returnRedirectToPage("./Lockout");}else{ModelState.AddModelError(string.Empty,"Invalid login attempt.");returnPage();}}returnPage();}
</div>