Ok I'm trying to detect requests source in Custom AuthenticationStateProvider So 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 browser How can I Keep Logged in user In my way without using The Blazor's Authentication
Here is sample code
/// <summary>
/// https://docs.microsoft.com/en-us/aspnet/core/blazor/security/?view=aspnetcore-6.0#authenticationstateprovider-service
/// https://docs.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://docs.microsoft.com/en-us/aspnet/core/fundamentals/app-state?view=aspnetcore-6.0
/// https://docs.microsoft.com/en-us/aspnet/core/fundamentals/app-state?view=aspnetcore-6.0#session-state
/// https://docs.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));
}
}
}
CodePudding user response:
As usually, I answering my own question myself. According to my impressions Blazor applications is created for managing all periods in a single window I think the best solution is using cookies. So here is my solution
- Create a js file and add to header
createBrowserId();
function getCookie(name) {
var dc = document.cookie;
var prefix = name "=";
var begin = dc.indexOf("; " prefix);
if (begin == -1) {
begin = dc.indexOf(prefix);
if (begin != 0) return null;
}
else {
begin = 2;
var end = document.cookie.indexOf(";", begin);
if (end == -1) {
end = dc.length;
}
}
// because unescape has been deprecated, replaced with decodeURI
//return unescape(dc.substring(begin prefix.length, end));
return decodeURI(dc.substring(begin prefix.length, end));
}
function uuidv4() {
return ([1e7] -1e3 -4e3 -8e3 -1e11).replace(/[018]/g, c =>
(c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16)
);
}
function createBrowserId() {
var myCookie = getCookie("fbc-bw-id");
if (myCookie == null) {
var uid = uuidv4();
document.cookie = "fbc-bw-id=" uid;
console.log("Yoktur: " uid)
}
else {
console.log("Vardir: " myCookie);
}
}
- Create classes for managing Cookies
class UserDataHolder
{
public DateTime Created { get; }
public DateTime LastActionDate { get; private set; }
public SysUser User { get; }
public UserDataHolder(SysUser user)
{
Created = LastActionDate = DateTime.Now;
User = user;
}
public void HadAction() => LastActionDate = DateTime.Now;
}
class SessionAIUser
{
public string? UserId { get; }
//public string? UserCreatedDate { get; }
//public string? SessionId { get; }
//public string? SessionCreatedDate { get; }
//public string? SessionUpdatedDate { get; }
public SessionAIUser(HttpContext? context)
{
if (context != null && context.Request != null && context.Request.Cookies != null && context.Request.Cookies.Any())
{
var c = context.Request.Cookies;
if (c.TryGetValue("fbc-bw-id", out string? fbcid))
{
if (!string.IsNullOrEmpty(fbcid))
{
this.UserId = fbcid;
//add ip addr too when only cookie is working
try
{
String ip = context.Connection.RemoteIpAddress.ToString();
if (!string.IsNullOrEmpty(ip))
{
this.UserId = ip;
}
//Console.WriteLine("ip:" ip);
}
catch
{
}
}
}
}
}
}
public class UserSessionManager
{
private static ConcurrentDictionary<string, UserDataHolder> _users;
private static DateTime lastPerodicalIdleChecked = DateTime.Now;
private const long IDLE_TIME_LIMIT_SECONDS = 60 * 5;
private HttpContext? context;
private SessionAIUser aiData;
private const string COOKIE_ERROR = "Bu uygulama çerezleri (cookies) kullanmaktadır. Eğer gizli (private) modda iseniz lütfen normal moda dönünüz, eğer çerezler kapalı ise lütfen açınız. Veya sayfayı yenileyerek tekrar deneyiniz.";
static UserSessionManager()
{
_users = new ConcurrentDictionary<string, UserDataHolder>();
}
private static void PerodicalIdleCheck()
{
if ((DateTime.Now - lastPerodicalIdleChecked).TotalSeconds > 60 * 3)
{
var dead = _users.Where(x =>
x.Value == null
|| (x.Value != null && (DateTime.Now - x.Value.LastActionDate).TotalSeconds > IDLE_TIME_LIMIT_SECONDS)
).Select(x => x.Key).ToList();
if (dead.Any())
{
dead.ForEach(x => _users.TryRemove(x, out UserDataHolder? mahmutHoca));
}
}
}
public UserSessionManager(IHttpContextAccessor contextAccessor)
{
this.context = contextAccessor.HttpContext;
aiData = new SessionAIUser(this.context);
}
public SysUser? GetLoggedInUser()
{
PerodicalIdleCheck();
if (!string.IsNullOrEmpty(aiData.UserId) && _users.TryGetValue(aiData.UserId, out var userDataHolder))
{
if (userDataHolder != null)
{
if ((DateTime.Now - userDataHolder.LastActionDate).TotalSeconds < IDLE_TIME_LIMIT_SECONDS && userDataHolder.User != null)
{
userDataHolder.HadAction();
return userDataHolder.User;
}
else
{
_users.TryRemove(aiData.UserId, out userDataHolder);
}
}
}
return null;
}
public bool Login(string userName, string password)
{
if (!string.IsNullOrEmpty(aiData.UserId))
{
using (var db = new DB())
{
var user = db.Users.Where(x => x.SysUserName == userName && SysUser.ToMD5(password) == x.SysUserPassword).FirstOrDefault();
if (user != null)
{
_users[aiData.UserId] = new UserDataHolder(user);
return true;
}
else
{
return false;
}
}
}
throw new Exception(COOKIE_ERROR);
}
public void Logout()
{
if (!string.IsNullOrEmpty(aiData.UserId))
{
_users.TryRemove(aiData.UserId, out var userDataHolder);
}
else
{
throw new Exception(COOKIE_ERROR);
}
}
}
- Add UserSessionManager class to services as Scope
var builder = WebApplication.CreateBuilder(args);
...
builder.Services.AddScoped<UserSessionManager>();
...
- Create a custom provider for managing session and add this provider too to Services.
public class CustomAuthStateProvider : AuthenticationStateProvider
{
private HttpContext? context;
private UserSessionManager userMgr;
public CustomAuthStateProvider(IHttpContextAccessor context, UserSessionManager userMgr)
{
this.context = context.HttpContext;
this.userMgr = userMgr;
}
public override Task<AuthenticationState> GetAuthenticationStateAsync()
{
var lUser = userMgr.GetLoggedInUser();
if (lUser != null)
{
List<Claim> claims = new List<Claim>();
claims.Add(new Claim(ClaimTypes.Sid, lUser.SysUserName));
claims.Add(new Claim(ClaimTypes.Name, lUser.Name));
claims.Add(new Claim(ClaimTypes.Surname, lUser.Surname));
if (lUser.IsAdmin)
{
claims.Add(new Claim(ClaimTypes.Role, "Admin"));
}
if (lUser.IsCanEditData)
{
claims.Add(new Claim(ClaimTypes.Role, "CanEditData"));
}
if (lUser.CariKartId != null)
{
claims.Add(new Claim("CariKartId", "" lUser.CariKartId));
}
var identity = new ClaimsIdentity(claims, "Database uleyn");
var user = new ClaimsPrincipal(identity);
return Task.FromResult(new AuthenticationState(user));
}
else
{
return Task.FromResult(new AuthenticationState(new ClaimsPrincipal(new ClaimsIdentity())));
}
}
}
Adding
builder.Services.AddScoped<AuthenticationStateProvider, CustomAuthStateProvider>();
So this is my way of using the application with multiple tabs and multiple request in same browser.