2015-11-01 58 views
-1

我想要一個非常簡單的身份驗證在ASP.net 5ASP.net 5 Web API 2密碼驗證

所有你需要進行身份驗證是一個密碼。沒有UserManager或任何這種事情。

如何登錄行動看起來像這樣或我該如何着手實現呢?

編輯: 密碼是一個全局密碼,並非針對每個用戶。

回答

0

我沒有測試此所以它只是一個起點。 你需要實現一個自定義的AuthenticationHandler。

喜歡的東西:

class PasswordAuthenticationHandler : AuthenticationHandler<PasswordAuthenticationOptions> 
{ 
    public PasswordAuthenticationHandler (PasswordAuthenticationOptionsoptions) 
    { 
     //set fields needed from options   
    } 

    protected override async Task<AuthenticationTicket> AuthenticateCoreAsync() 
    { 
     //get the password out of the Request and create claims collection 
     ... 
     var claimsId = new ClaimsIdentity(claims, Options.AuthenticationType); 
     return new AuthenticationTicket(claimsId, new AuthenticationProperties());// can use AuthenticationProperties to set additional propertiues needed in ticket 
    } 

    // override ApplyResponseChallengeAsync 

} 

創建從AuthenticationOptions繼承PasswordAuthenticationOptions。

創建OWIN中間件

public class PasswordAuthenticationMiddleware : AuthenticationMiddleware<PasswordAuthenticationOptions> 
{ 
    public delegate Task<IEnumerable<Claim>> CredentialValidationFunction(string id, string secret); 

    public PasswordAuthenticationMiddleware(OwinMiddleware next, PasswordAuthenticationOptions options) 
     : base(next, options) 
    {} 

    protected override AuthenticationHandler<PasswordAuthenticationOptions> CreateHandler() 
    { 
     return new PasswordAuthenticationHandler(Options); 
    } 
} 

然後在Startup.cs你會使用它想:

app.Use<PasswordAuthenticationMiddleware>(options); 

你應該能夠鎖定下來的東西與授權的類,方法或屬性添加它作爲一個全局過濾器。

我建議你看看:
http://leastprivilege.com/2015/10/12/the-state-of-security-in-asp-net-5-and-mvc-6-authorization/
https://github.com/leastprivilege/AspNet5AuthorizationPlayground/tree/master/src/Authentication

0

你可以嘗試實現最簡單的方法:API控制器的動作裏面

  1. 檢查密碼。
  2. 設置一些生成或預定義的cookie或使用令牌返回響應。
  3. 創建自定義ActionFilter,並檢查您的Cookie或令牌(查詢字符串或HTTP請求頭中)爲Authorization