0
我正在嘗試爲我的WCF Rest API調用實現基本授權。 所有看起來都不錯,如果用戶是有效的用戶,他會被認證,並且調用被髮送到相應的API進行處理。CheckAccessCore返回False引發400錯誤請求
另外,如果Auth頭不存在,它會拋出一個異常並引發401 - 未授權,這看起來合法。
但是,當Auth頭被提供並且它不正確時,它返回「FALSE」,我相信這是「CheckAccessCore
」方法的設計。
每當假被重新調校,它提出了一個400錯誤的請求我的電話,這似乎是不正確的錯誤請求可能是像傳遞不同的參數,然後,API預計等正當理由
下面是我CheckAccessCore
方法
protected override bool CheckAccessCore(OperationContext operationContext)
{
//Extract the Authorization header, and parse out the credentials converting the Base64 string:
var authHeader = WebOperationContext.Current.IncomingRequest.Headers["Authorization"];
if ((authHeader != null) && (authHeader != string.Empty))
{
var svcCredentials = System.Text.ASCIIEncoding.ASCII
.GetString(Convert.FromBase64String(authHeader.Substring(6)))
.Split(':');
var user = new { Name = svcCredentials[0], Password = svcCredentials[1] };
if ((user.Name == "user1" && user.Password == "test"))
{
//User is authrized and originating call will proceed
return true;
}
else
{
//not authorized
return false;
}
}
else
{
//No authorization header was provided, so challenge the client to provide before proceeding:
WebOperationContext.Current.OutgoingResponse.Headers.Add("WWW-Authenticate: Basic realm=\"MyWCFService\"");
//Throw an exception with the associated HTTP status code equivalent to HTTP status 401
throw new WebFaultException(HttpStatusCode.Unauthorized);
}
}
和API呼叫通過如下C#代碼:
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(serviceURL);
//Add a header to the request that contains our credentials
//DO NOT HARDCODE IN PRODUCTION!! Pull credentials real-time from database or other store.
string svcCredentials = Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes("user1" + ":" + "test"));
req.Headers.Add("Authorization", "Basic " + svcCredentials);
//Just some example code to parse the JSON response using the JavaScriptSerializer
try
{
using (WebResponse svcResponse = (HttpWebResponse)req.GetResponse())
{
return svcResponse.GetResponseStream();
}
}
catch (WebException e)
{
using (WebResponse response = e.Response)
{
HttpWebResponse httpResponse = (HttpWebResponse)response;
Console.WriteLine("Error code: {0}", httpResponse.StatusCode);
using (Stream data = response.GetResponseStream())
using (var reader = new StreamReader(data))
{
string text = reader.ReadToEnd();
Console.WriteLine(text);
return null;
}
}
}
這裏的問題是,
CheckAccessCore
方法在身份驗證失敗時引發400錯誤請求是否正確?如果不是,代碼有什麼問題,以及如何糾正。
感謝 Ashutosh說