Ok I'm trying to detect requests source in Custom AuthenticationStateProviderSo here is my tries:
- Session Id not working because every request retrieves tottally new id in same browser because of WebSocket
- Obvioisly HttpContext.Connection.Id is not working because it's changes for every refresh page
- builder.Services.AddSingleton is not working because its keeps data whole application's life cycle
- So as you know builder.Services.AddTransient and builder.Services.AddScoped also changing for every single request regardless of browser or pc
- Well I think HttpContext.Connection.Ip can not be used because of it uses same IP that PCs in same LAN
So how can I Distinguish which request belongs to which pc or browserHow can I Keep Logged in user In my way without using The Blazor's Authentication
Here is sample code
/// <summary> /// https://learn.microsoft.com/en-us/aspnet/core/blazor/security/?view=aspnetcore-6.0#authenticationstateprovider-service /// https://learn.microsoft.com/en-us/aspnet/core/blazor/security/?view=aspnetcore-6.0#implement-a-custom-authenticationstateprovider /// https://www.indie-dev.at/2020/04/06/custom-authentication-with-asp-net-core-3-1-blazor-server-side/ /// https://learn.microsoft.com/en-us/aspnet/core/fundamentals/app-state?view=aspnetcore-6.0 /// https://learn.microsoft.com/en-us/aspnet/core/fundamentals/app-state?view=aspnetcore-6.0#session-state /// https://learn.microsoft.com/en-us/aspnet/core/blazor/state-management?view=aspnetcore-6.0&pivots=server#where-to-persist-state /// </summary> public class CustomAuthStateProvider : AuthenticationStateProvider { private IHttpContextAccessor context; static ConcurrentDictionary<string, ClaimsPrincipal> logins = new ConcurrentDictionary<string, ClaimsPrincipal>(); public CustomAuthStateProvider(IHttpContextAccessor context) { this.context = context; } public override Task<AuthenticationState> GetAuthenticationStateAsync() { if (logins.TryGetValue(context.HttpContext.Session.Id, out var p)) { return Task.FromResult(new AuthenticationState(p)); // <---- The debugger never stops here becuse Session Id is changes for every reqquest } else { //it will return empty information in real application for force it login //return Task.FromResult(new AuthenticationState(new ClaimsPrincipal(new ClaimsIdentity()))); //This block does not belong here, it will be populated on the Login page in the real application. For now I'm just running it here for testing var identity = new ClaimsIdentity(new[] { new Claim(ClaimTypes.Name, "RandomId"), //It will ger user infos from our custom database. (No MS's Auth Database) new Claim(ClaimTypes.Role, "A") }, "Fake authentication type"); var user = new ClaimsPrincipal(identity); logins[context.HttpContext.Session.Id] = user; return Task.FromResult(new AuthenticationState(user)); } } }