Quantcast
Channel: Active questions tagged blazor - Stack Overflow
Viewing all articles
Browse latest Browse all 4839

Blazor Client Server Interactive Auto mode based application user login session Issue

$
0
0

I have created an Blazor web application having client server interactive mode, I need to create a user login based session for user claim based user identity using authentication state provider helper class. I don't want to off prerendering by making server side for performance purpose.

Issue: Authentication state user identity property became false and resets after navigated to next dashboard page from user login. state became maintain if I will keep my custom authentication provider class as services.AddSingleton<AuthenticationStateProvider, CustomAuthStateProvider>();but I need to make it as AddScoped or AddTransient to make it user specific sessions.

Basically I need to create user session along with user claim based identity on login page button click which is working fine but I could not get it either on MainLayout or dashboard page OnInitialized Event as prerendering does not supports Js Interopablity in this life cycle event.

I have also tried middleware to get and set sessions but it not working as well.I have done lots of google search, many youtubers elaborated this using very complicated way integration of circuit based methodology by Microsoft. Please guide me on this very simple way, I am stuck. no need to integrate any static or singleton thing to share the user sessions.

// Please see my integrations below.

// Custom Auth State Provider Class

private Task<AuthenticationState>? _authenticationStateTask { get; set; } = null;

public ClaimsPrincipal CurrentUser { get; set; }

    var identity = new ClaimsIdentity(new[]    {        new Claim(ClaimTypes.Sid, userDetails.UserId.ToString()),        new Claim(ClaimTypes.Email, userDetails.Email),        new Claim(ClaimTypes.Name, userDetails.FirstName),        new Claim(ClaimTypes.GivenName, userDetails.SearchEngine)}, scheme);    return new ClaimsPrincipal(identity);
 public override Task<AuthenticationState> GetAuthenticationStateAsync() {     var task = Task.FromResult(new AuthenticationState(this.CurrentUser));     _authenticationStateTask = task;     return task; } public Task<AuthenticationState> MarkUserAsAuthenticated(UserDetails userDetails) {     // create user session here.     this.CurrentUser = this.GetUser(userDetails);     bool isWebResponseStarted = IsHttpResponseStarted();     if (isWebResponseStarted)     {         CreateUserBlazorSession(userDetails);         CreateUserLibSession(userDetails);     }     var task = this.GetAuthenticationStateAsync();     _httpContextAccessor.HttpContext.User = this.CurrentUser;     var authProperties = new AuthenticationProperties     {         IsPersistent = true,         AllowRefresh = true     };     _httpContextAccessor.HttpContext.SignInAsync(this.CurrentUser, authProperties);     this.NotifyAuthenticationStateChanged(task);     return task; }

// User Login Razor Page Bu

 public async Task Login(EditContext context) {     bool formIsValid = context.Validate();     if (formIsValid)     {         var userModel = ((UserLoginDTO)context.Model);         if (null != userModel)         {             if (!String.IsNullOrEmpty(user.email) && user.email.Trim() != ""&& !String.IsNullOrEmpty(user.password) && user.password.Trim() != "")             {                 await JS.InvokeVoidAsync("ShowHideLoader", true);                 var userData = await DomainDataProxyService.UserLogin(user);                 await JS.InvokeVoidAsync("ShowHideLoader", false);                 if (null != userData && null != userData.userDetails && userData.success)                 {                     //set session here.                   //  sessionManager.SetSession(CommonConstants.UserSessionName, userData.userDetails);                     int? expTime = 30;                     // CookieService.SetCookie("Test", "Test 123", expTime);                     // StateHasChanged();                     //  loginUserStateContainer.OnStateChange += StateHasChanged;                     var authState = await ((CustomAuthStateProvider)AuthState).MarkUserAsAuthenticated(userData.userDetails);                     // this.loginUser = authState.User;                     // var IsUserMarkedAuthenticated = null != authState && null != authState.User ?                     //            authState.User.Identity.IsAuthenticated : false;                      StateHasChanged();                    // await base.OnInitializedAsync();                     // if (IsUserMarkedAuthenticated)                     // {                     NavManager.NavigateTo(CommonConstants.SiteUrl +"home", true);                     //}                 }                 else                 {                     await JS.InvokeVoidAsync("LoginFailure");                 }             }         }     } }

Please help me out to resolve this issue, I am stuck from last 8 to 10 days.

Regards,Manoj


Viewing all articles
Browse latest Browse all 4839

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>