我有一个只有一个用户的Web API,我正在尝试使用基本身份验证来保护它,但它总是会在未经授权的情况下返回代码401。
这是我的代码:
Class BasicAuthenticationAttribute
using System;
using System.Threading;
using System.Security.Principal;
using System.Text;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;
using System.Net;
using System.Net.Http;
public class BasicAuthenticationAttribute: AuthorizationFilterAttribute
{
public override void OnAuthorization(HttpActionContext actionContext)
{
if (actionContext.Request.Headers.Authorization == null)
{
actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized);
}
else
{
// Gets header parameters
string authenticationString = actionContext.Request.Headers.Authorization.Parameter;
string originalString = Encoding.UTF8.GetString(Convert.FromBase64String(authenticationString));
// Gets username and password
string usrename = originalString.Split(':')[0];
string password = originalString.Split(':')[1];
// Validate username and password
if (!CheckUser.Login(usrename, password))
{
// returns unauthorized error
actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized);
}
}
base.OnAuthorization(actionContext);
}
}
类Checkuser
using System;
public class CheckUser
{
public static bool Login(string username, string password)
{
if (username == "user" && password == "mypassword")
return true;
else
return false;
}
}
API控制器
public class adduserController : ApiController
{
[HttpGet, BasicAuthentication]
[Route("api/user/{email}")]
public string adduser(string email)
{
string country_code = "";
string username = System.Threading.Thread.CurrentPrincipal.Identity.Name;
return "Welcome";
}
这是我的JQuery功能:
var token = '';
var headers = {};
if (token) {
headers.Authorization = 'Basic YWhdZWQer5WhtZWRAMjAxNw==';
}
$.ajax({
type: 'GET',
url: 'http://mywebapi.com',
headers: headers
}).done(function (data) {
self.result(data);
})
我不知道我的代码有什么问题!!请帮忙
提前谢谢
答案 0 :(得分:0)
您创建了一个空令牌,然后您设置了标头,如果该令牌不为空,那么您永远不会设置任何标头......
var token = '';
var headers = {};
if (token) {
headers.Authorization = 'Basic YWhdZWQer5WhtZWRAMjAxNw==';
}
尝试
if (!token) {