2017-02-24 61 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,甚至用自己的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

+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); 
       } 
      } 
     } 
    } 
相关问题