[fix]修正UdpServer在接收广播时连续启动接收的错误,在StarAgent中,此时可能收到广播包,SocketFlags是Broadcast,需要清空,否则报错“参考的对象类型不支持尝试的操作”; 无需设置SocketOptionName.PacketInformation,在ReceiveMessageFromAsync时会自动设置,并且支持ipv6;
石头 authored at 2024-10-10 00:36:00 石头 committed at 2024-10-10 00:45:43
1.46 KiB
X
using System;
using System.IO;
using System.Text;
using NewLife;
using NewLife.Security;
using NewLife.Web;
using Xunit;

namespace XUnitTest.Web;

public class TokenProviderTests
{
    [Fact]
    public void Test()
    {
        var prv = new TokenProvider();

        // 加载或生成密钥
        var rs = prv.ReadKey("keys/test.prvkey", true);
        Assert.True(rs);
        Assert.True(File.Exists("keys/test.prvkey".GetFullPath()));
        Assert.True(File.Exists("keys/test.pubkey".GetFullPath()));
        Assert.NotEmpty(prv.Key);

        // 生成令牌
        var user = Rand.NextString(8);
        var time = DateTime.Now.AddHours(2);
        var token = prv.Encode(user, time);

        Assert.NotEmpty(token);
        var data = token.Substring(null, ".").ToBase64().ToStr();
        Assert.Equal($"{user},{time.ToUniversalTime().ToInt()}", data);

        // 解码令牌
        var prv2 = new TokenProvider();
        prv2.ReadKey("keys/test.pubkey", false);
        var rs2 = prv2.TryDecode(token, out var user2, out var time2);

        Assert.True(rs2);
        Assert.Equal(user, user2);
        Assert.Equal(time.Trim(), time2.Trim());

        // 破坏数据
        token = $"Stone,{time.ToUniversalTime().ToInt()}".GetBytes().ToUrlBase64() + "." + token.Substring(".");
        var rs3 = prv2.TryDecode(token, out var user3, out var time3);

        Assert.False(rs3);
        Assert.NotEqual(user, user3);
        Assert.Equal(time.Trim(), time3.Trim());
    }
}