【发布时间】:2019-08-27 03:29:03
【问题描述】:
我已经使用 httpweb 请求查找了有关 web api 中基本授权的所有问题,但都没有解决我的问题。我有一个 web api(用 C# 编写),我想为 api 建立基本授权。我还有一个用来调用 api 的网页。但是,它一直返回“(401)未经授权”,我不知道我做错了什么。现在我在代码中使用用户名和密码,但我希望有一个弹出窗口询问凭据。
这是我的网页代码,调用 api:
string url = String.Format("http://example.com");
HttpWebRequest requestObj = (HttpWebRequest)WebRequest.Create(url);
requestObj.Method = "Get";
requestObj.Credentials = new NetworkCredential("testing", "123456");
HttpWebResponse responseObj = null;
responseObj = (HttpWebResponse)requestObj.GetResponse();
string strresult = null;
using (Stream stream = responseObj.GetResponseStream())
{
StreamReader sr = new StreamReader(stream);
strresult = sr.ReadToEnd();
sr.Close();
}
在我的 api 中,我打开了一个名为 BasicAuthenticationAttribute 的类并写了这个:
public class BasicAuthenticationAttribute : AuthorizationFilterAttribute
{
public static bool IsAuthorizedUser(string Username, string Password)
{
return Username == "testing" && Password == "123456";
}
public override void OnAuthorization(HttpActionContext actionContext)
{
base.OnAuthorization(actionContext);
if (actionContext.Request.Headers.Authorization != null)
{
var authToken = actionContext.Request.Headers.Authorization.Parameter;
var decodeauthToken = System.Text.Encoding.UTF8.GetString(Convert.FromBase64String(authToken));
var arrUserNameandPassword = decodeauthToken.Split(':');
if (IsAuthorizedUser(arrUserNameandPassword[0], arrUserNameandPassword[1]))
{
Thread.CurrentPrincipal = new GenericPrincipal(new GenericIdentity(arrUserNameandPassword[0]), null);
}
else
{
actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized);
}
}
else
{
actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized);
}
}
}
在我的控制器中,我有这个:
[BasicAuthentication]
public class EventsController : ApiController
{
}
这是我收到的错误: 远程服务器返回错误:(401) Unauthorized.
【问题讨论】:
-
你用调试器检查过
decodeauthToken吗? -
您不需要将“Basic”替换为 String.Empty 吗?我一直认为 Basic Authentication 以 Basic 为名。需要找到我之前复制的例子。
-
@JohnPete22 我的想法完全正确 - 只是想让 OP 使用调试器来解决它:) 假设它完全达到了这一点。
-
@fredrik 我没有,我该怎么做?
-
@JohnPete22 不太确定要替换什么,您认为问题在哪里?
标签: c# html asp.net-web-api httpwebrequest asp.net-authorization