2017-02-24 15 views
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にキャストしても、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であることがわかります。

+0

コードを表示します。 –

+0

@MAdeelKhalidコードはリンクされていましたが、インラインで追加しました。 – TheDarkVoid

答えて

0

私の質問では、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); 
       } 
      } 
     } 
    } 
関連する問題