ナンシーで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
にキャストしても、IUserIdentity
を実装UserModel
class UserModel : IUserIdentity
{
public string UserName { get; }
public IEnumerable<string> Claims { get; }
public UserModel(string username)
{
UserName = Uri.EscapeDataString(username);
}
}
自分自身を使用してみました。これによりエラーは発生しませんが、ユーザーは認証されません。ユーザーは、必要なすべての検証を過ぎてそれを作ると、正しいAPIKEYを持つにもかかわらず、私の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 };
};
}
}
アクセスすることはできません。私のテストから、ユーザーは決してnancyコンテキストに割り当てられないように見えます。設定は使用されており、ユーザーはapiKeyで取得されますが、決して設定されません。私が紛失しているものはありますか?プロジェクトをさらに検査したい場合は、フルプロジェクトがhereであることがわかります。
コードを表示します。 –
@MAdeelKhalidコードはリンクされていましたが、インラインで追加しました。 – TheDarkVoid