gpt4 book ai didi

c# - Blazor 服务器 : Unique Id For Distinguish Clients

转载 作者:行者123 更新时间:2023-12-05 03:32:29 26 4
gpt4 key购买 nike

好的,我正在尝试检测 Custom AuthenticationStateProvider 中的请求源所以这是我的尝试:

  • session ID 不工作,因为每个请求都在同一个浏览器中检索完全新的 ID,因为 WebSocket
  • 显然 HttpContext.Connection.Id 不起作用,因为它会随着每个刷新页面的变化而变化
  • builder.Services.AddSingleton 无法正常工作,因为它会在整个应用程序的生命周期中保留数据
  • 如您所知,builder.Services.AddTransient 和 builder.Services.AddScoped 也会针对每个请求进行更改,无论浏览器或 pc
  • 嗯,我认为 HttpContext.Connection.Ip 不能使用,因为它使用与同一 LAN 中的 PC 相同的 IP

那么我如何区分哪个请求属于哪个电脑或浏览器如何在不使用 Blazor 身份验证的情况下以我的方式保持登录用户

这里是示例代码

    /// <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));
}




}
}

最佳答案

像往常一样,我自己回答我自己的问题。根据我的印象,Blazor 应用程序是为在单个窗口中管理所有期间而创建的我认为最好的解决方案是使用 cookie。所以这是我的解决方案

  1. 创建一个js文件并添加到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);
}
}

  1. 创建用于管理 Cookie 的类

  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);

}

}

}

  1. 将 UserSessionManager 类作为范围添加到服务

var builder = WebApplication.CreateBuilder(args);
...
builder.Services.AddScoped<UserSessionManager>();
...

  1. 创建用于管理 session 的自定义提供程序,并将此提供程序也添加到服务中。

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())));
}





}
}

添加

builder.Services.AddScoped<AuthenticationStateProvider, CustomAuthStateProvider>();

这就是我在同一浏览器中使用具有多个选项卡和多个请求的应用程序的方式。

关于c# - Blazor 服务器 : Unique Id For Distinguish Clients,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70471400/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com