拨开荷叶行,寻梦已然成。仙女莲花里,翩翩白鹭情。
IMG-LOGO
主页 文章列表 Blazor服务器:用于区分客户端的唯一ID

Blazor服务器:用于区分客户端的唯一ID

白鹭 - 2022-01-23 2186 0 0

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

  • 会话 ID 不起作用,因为 WebSocket 导致每个请求都在同一浏览器中检索完全新的 ID
  • Obvioisly HttpContext.Connection.Id 不起作用,因为每个重绘 页面都会发生变化
  • builder.Services.AddSingleton 不起作用,因为它在整个应用程序的生命周期中保留资料
  • 因此,如您所知,builder.Services.AddTransient 和 builder.Services.AddScoped 也会针对每个请求而更改,而不管浏览器或 PC
  • 好吧,我认为 HttpContext.Connection.Ip 不能使用,因为它使用与同一 LAN 中的 PC 相同的 IP

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

这是示例代码

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



        }
    }

uj5u.com热心网友回复:

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

  1. 创建一个js档案并添加到标题

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. 创建用于管理会话的自定义提供程序并将此提供程序也添加到服务。

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

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

标签:

0 评论

发表评论

您的电子邮件地址不会被公开。 必填的字段已做标记 *