【发布时间】:2017-08-12 13:49:29
【问题描述】:
我正在尝试为我的 WCF Rest API 调用实现基本授权。 一切似乎都很好,如果用户是有效用户,他将通过身份验证并将调用发送到相应的 API 进行处理。
此外,如果 Auth 标头不存在,它会引发异常并引发 401 - Not Authorized,这似乎是合法的。
但是,当提供了 Auth 标头但它不正确时,它会返回“FALSE”,我认为这是“CheckAccessCore”方法的设计。
每当重新调整 False 时,它都会向我的调用提出 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-Bad Request 是否正确?如果没有,代码有什么问题以及如何纠正。
谢谢 阿舒托什
【问题讨论】:
标签: c# api wcf httprequest