2014-02-19 48 views
0

我有一個Web API 2應用程序,它使用Asp.Net身份驗證和授權。我還有一個自定義消息處理程序來執行額外的自定義檢查來完成身份驗證(以及解析連接到多租戶數據存儲上正確模式所需的一些API數據)。Asp.Net身份 - 如何以編程方式設置未經授權?

這裏是消息處理我的工作代碼:

public class AuthenticationHeadersHandler : DelegatingHandler 
{ 
    protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) 
    { 
     if (request.Headers.Contains("Authorization")) 
     { 
      // Authenticate 
      var auth = request.GetOwinContext().Authentication.AuthenticateAsync(OAuthDefaults.AuthenticationType); 

      // Get user ID from token 
      identityId = auth.Result.Identity.GetUserId(); 

      // Please note, the oAuth token would have successfully authenticated by now 

      // ... Do some custom authentication and data gathering 
      if (failedCheck) 
      { 
       // If user fails checks, I would like to force Asp.Net Identity to 
       // return 401 not authorized here, or flag the request as not authorized 
      } 
     } 
    } 
} 

考慮上面的代碼,我怎麼能手動旗請求未經授權,即使它通過了最初的認證?

+0

是否使用IIS集成安全性? –

+0

@BlackFrog我不確定。不是我所知,除非它是默認設置的。 –

回答

1

我認爲這應該工作:

protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) 
{ 
    if (request.Headers.Contains("Authorization")) 
    { 
     // Authenticate 
     var auth = request.GetOwinContext().Authentication.AuthenticateAsync(OAuthDefaults.AuthenticationType); 

     // Get user ID from token 
     identityId = auth.Result.Identity.GetUserId(); 

     // Please note, the oAuth token would have successfully authenticated by now 

     // ... Do some custom authentication and data gathering 
     if (failedCheck) 
     { 
      // Return 401 not authorized here. 
      return new HttpResponseMessage(HttpStatusCode.Unauthorized); 
     } 
    } 
    // If we got here send an HTTP status of 200 
    return new HttpResponsMessage(HttpStatusCode.OK); 
}