0
我試圖爲我的API實現無狀態身份驗證與南希,但我遇到後sample stateless project後遇到問題。當我創建我的StatelessAuthenticationConfiguration南希無狀態身份驗證配置不接受IPrincpal
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
。這不會產生錯誤,但用戶不會被認證。用戶仍然可以不是我的secure module
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獲得,但它永遠不會被設置。有什麼我失蹤?如果您想進一步檢查項目,可以找到完整的項目here。
向我們顯示您的代碼。 –
@MAdeelKhalid該代碼已鏈接,但我現在也添加了內聯。 – TheDarkVoid