2016-11-28 56 views
4

我就應該總是返回相同的JSON解析的對象或不的WebAPI返回類型

例子:

在網站上,用戶輸入自己的用戶名和密碼。

當用戶按提交他發送請求/api/logintest/{key}。如果用戶和密碼匹配,該URL所調用的方法是否會返回像{errMsg:null}這樣的JSON對象,如果不匹配,則返回{errMsg:「bad username or password」};或者如果用戶的詳細信息不匹配,我應該返回並顯示錯誤消息,如果找到用戶,則返回JSON中的用戶對象?

這是我的代碼

[ResponseType(typeof(User))] 
    [HttpPost] 
    [Route("api/logintest/{key}")] 
    public IHttpActionResult LoginTest(LoginForm luser , String key) 
    { 
     //test the api key 
     if(key == "jordanisthebest") 
     { 
      //we try to get the user by his username and password 
      User userReturn = UsersManager.getUserByEmailAndPassword(new User { Email = luser.Email, Password = luser.Password }); 

      //if the user is null then we return the err message 
      if (userReturn == null) 
       ModelState.AddModelError("Email", "Bad email or password"); 

      //if model state is not good we send err msg 
      if (!ModelState.IsValid) 
       return Ok(ModelState.getListErrorAndKey(null, typeof(LoginForm))); 

      //if all good we return the user 
      return Ok(userReturn); 
     } 

     return NotFound(); 
    } 
+0

你看到了什麼錯誤? – Prescott

+0

你的問題不清楚。你不確定要返回什麼嗎? – Vinoth

+1

遠離這個問題,您不應該使用這種方式來驗證用戶身份,您應該使用由身份提供者(例如ADFS或Identity Server)發出的令牌來驗證您的API –

回答

1

IMO,它不應該返回一個身體而是返回一個HTTP 401 - 未授權

示例代碼:

//if the user is null then we return the err message 
if (userReturn == null) 
    return Unauthorized(); 
1

另一件事,你可以do會設置一個認證過濾器,以便在請求完成後檢查憑證,但在實際端點被調用之前不久。

public class AuthenticationFilter : AuthorizeAttribute 
{ 
    public override void OnAuthorization(AuthorizationContext filterContext) 
    { 
     // Your validation logic here. 
    } 
} 

然後在FilterConfig.cs配置它:

public class FilterConfig 
{ 
    public static void RegisterGlobalFilters(GlobalFilterCollection filters) 
    { 
     filters.Add(new AuthenticationFilter()); 
    } 
} 

...而你設置!

1

如果你想知道他們是否驗證,那麼你可以返回:

{ "authenticated" : true } // or false 

如果你想知道原因,所以你可以登錄它或將其顯示:

{ "authenticated": false, "reason" : "User account was locked" } 

要更加RESTful,你可以讓你的路線:

GET /api/users/{userName}/authenticate 

你的「快樂的路徑」將返回一個HTTP狀態200和JSON消息作爲響應內容。

如果找不到用戶(因爲API調用正在查找用戶資源),您可能會返回未找到404的HTTP狀態碼,但不需要返回HTTP狀態碼401,因爲資源本身不是調用者未被授權使用的東西。

不暴露給用戶爲什麼他們明確地認證失敗是一個好習慣。您返回給用戶的信息越多,黑客的更多信息也可能不知道他們是否擁有有效的用戶帳戶。