Nancy 无状态身份验证配置不接受 IPrincpal



我正在尝试与南希实现无状态验证,但是在遵循示例无状态项目之后,我遇到了一个问题。当我创建Necestelessauthentication Configuration

    new StatelessAuthenticationConfiguration(nancyContext =>
    {
        var apiKey = JsonConvert.DeserializeObject<ApiKeyModel>(nancyContext.Request.Body.AsString()).ApiKey;
        return GetUserFromApiKey(apiKey);
    });

它给我一个错误,即无法隐式施放Iprincipal

    internal static IPrincipal GetUserFromApiKey(string apiKey)
    {
        using (var con = GetConnection())
        {
            using (var cmd = con.CreateCommand())
            {
                Console.WriteLine($"Key: {apiKey}");
                cmd.CommandText = $"SELECT username FROM apiKeys WHERE apiKey = {apiKey}";
                string username = (string)cmd.ExecuteScalar();
                if (string.IsNullOrWhiteSpace(username))
                    return null;
                else
                    return new ClaimsPrincipal(new GenericIdentity(username, "stateless"));//new UserModel(username);
            }
        }
    }

我给它。我尝试过铸造到 IUserIdentity,甚至使用自己的usermodel

class UserModel : IUserIdentity
{
    public string UserName { get; }
    public IEnumerable<string> Claims { get; }
    public UserModel(string username)
    {
        UserName = Uri.EscapeDataString(username);
    }

}

实施IUserIdentity。这不会产生任何错误,但是用户没有得到身份验证。用户仍然无法访问我的安全模块

public class APIModule : NancyModule
{
    public APIModule() : base("/api")
    {
        StatelessAuthentication.Enable(this, Aoba.StatelessConfig);
        this.RequiresAuthentication();
        Post["/"] = _ =>
        {
            Console.WriteLine(Context.CurrentUser.IsAuthenticated());
            return new Response { StatusCode = HttpStatusCode.OK };
        };
    }
}

尽管它超过了所有必需的验证并具有正确的apikey。从我的测试中,看来用户永远不会分配到南希上下文。正在使用配置,并且用户是通过Apikey获得的,但永远不会设置。我缺少什么吗?如果您想进一步检查该项目,则可以在此处找到完整的项目。

事实证明,错误是我的查询以使用户从apikey获取。以下是校正,现在一切都按预期工作。

    internal static UserModel GetUserFromApiKey(string apiKey)
    {
        using (var con = GetConnection())
        {
            using (var cmd = con.CreateCommand())
            {
                Console.WriteLine($"Key: {apiKey}");
                cmd.CommandText = $"SELECT username FROM apiKeys WHERE apikey = '{apiKey}'";
                using (var reader = cmd.ExecuteReader())
                {
                    if (!reader.HasRows)
                        return null;
                    reader.Read();
                    string username = reader.GetString(0);
                    if (string.IsNullOrWhiteSpace(username))
                        return null;
                    else
                        return new UserModel(username);
                }
            }
        }
    }

最新更新