2017-08-15 39 views
15

我使用API​​製作網站時,API需要驗證,因此用戶只能獲取自己的數據。我已經編寫了以下中間件來驗證登錄。.net-core中間件返回空白結果

public class ApiAuthenticationMiddleware 
{ 
    private readonly RequestDelegate _next; 
    private readonly UserManager<ApplicationUser> _userManager; 
    private readonly SignInManager<ApplicationUser> _signInManager; 

    public ApiAuthenticationMiddleware(RequestDelegate next, 
     SignInManager<ApplicationUser> signInManager, 
     UserManager<ApplicationUser> usermanager) 
    { 
     _next = next; 
     _signInManager = signInManager; 
     _userManager = usermanager; 
    } 

    public async Task Invoke(HttpContext context) 
    { 
     if (!context.Request.Query.ContainsKey("password") || !context.Request.Query.ContainsKey("email")) 
     { 
      context.Response.StatusCode = 401; //UnAuthorized 
      await context.Response.WriteAsync("Invalid User Key"); 
      return; 
     } 
     var email = context.Request.Query["email"]; 
     var password = context.Request.Query["password"]; 

     var result = await _signInManager.PasswordSignInAsync(email, password, false, lockoutOnFailure: false); 
     if (result.Succeeded) 
     { 
      await _next.Invoke(context); 
     } 
     else if (//some more checks) 
      context.Response.StatusCode = 401; //UnAuthorized 
      await context.Response.WriteAsync("Invalid User Key"); 
      return; 
     } 
    } 
} 

我想的是,如果用戶沒有有效的登錄顯示空白頁或「無效的用戶密鑰」的錯誤消息。然而,目前發生的是主頁返回(因爲我的中間件在usemvc之前調用,並且return語句跳過由usemvc完成的控制器請求)。

我在startup.cs的配置方法相關的代碼

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) 
    { 

     app.UseIdentity(); 
     app.UseWhen(x => (x.Request.Path.StartsWithSegments("/api", StringComparison.OrdinalIgnoreCase)), 
      builder => 
      { 
       builder.UseMiddleware<ApiAuthenticationMiddleware>(); 
      }); 
     app.UseStaticFiles(); 
     app.UseMvc(routes => 
     { 
      routes.MapRoute(
       name: "default", 
       template: "{controller=Home}/{action=Index}/{id?}"); 
     }); 
    } 

我怎樣才能讓我的中間件返回一個空白頁,狀態碼?

請解釋downvoting的原因,以便我可以改善問題,並知道我做錯了什麼。

更新

嘗試了很多事情之後,我發現,當我刪除:

context.Response.StatusCode = 401; //UnAuthorized 

它能正常工作,用戶獲得給出的消息:

await context.Response.WriteAsync("Invalid User Key"); 

Howerver我不希望用戶在登錄失敗時獲得200狀態碼,而是獲得401狀態碼。但是,當使用狀態碼行時,用戶將被重定向。那麼我怎樣才能發送狀態碼而不用重定向呢?

+0

爲什麼不使用'Authorize'屬性 – CodeNotFound

+0

授權假定在用戶登錄(經由餅乾如果即時通訊正確)進出口製造用於移動應用的API,因此該應用將它需要從一個有效的用戶的請求。如果沒有登錄,授權將重定向到註冊頁面,這不是我想要的API行爲。 –

+0

我會看看OpenId中間件。這個中間件使用授權屬性 –

回答

4

我有一個預感,app.UseIdentity()有默認的行爲,當403/401發生時,它會攔截響應並啓動重定向。嘗試評論一下,看看它是否有效。

替代解決方案請參見:https://stackoverflow.com/a/43456151/3948882

最新的留言:我強烈建議不傳遞憑據爲每個請求。我建議使用預構建的auth提供程序並將其作爲中間件實現。 Authorize屬性應該足以滿足請求,並且可以執行您正在查找的內容。如果你確實想要返回一些特殊的東西,你可以用中間件覆蓋響應,例如app.UseIdentity()中間件可能會重定向。

0

嘗試在設置StatusCode之前使用.Clear()。

  context.Response.Clear(); 
      context.Response.StatusCode = (int)HttpStatusCode.Unauthorized; 
      await context.Response.WriteAsync("Unauthorized");