问题描述
我想用一个密钥授权我的Web api,但是它总是显示此请求的授权已被拒绝".以下是我尝试过的最后一个代码.
I want to authorize my web api with a key, but it always says "Authorization has been denied for this request." The following is the last code that I tried.
这是Delegating处理程序类:
This is the Delegating handler class:
// Message Handler class
public class APIKeyFilter: DelegatingHandler
{
// Default API Key
private const string APIKEY = "b018a9c5105d427127e";
protected override Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request, CancellationToken cancellationToken)
{
var query = request.RequestUri.ParseQueryString();
string key = query["key"];
if (APIKEY!=key)
{
var response = new HttpResponseMessage(HttpStatusCode.Forbidden);
var tsc = new TaskCompletionSource<HttpResponseMessage>();
tsc.SetResult(response);
return tsc.Task;
}
return base.SendAsync(request, cancellationToken);
}
}
这是全局类:
public class Global : HttpApplication
{
void Application_Start(object sender, EventArgs e)
{
AreaRegistration.RegisterAllAreas();
GlobalConfiguration.Configure(WebApiConfig.Register);
RouteConfig.RegisterRoutes(RouteTable.Routes);
GlobalConfiguration.Configuration.MessageHandlers.Add(new Filter.APIKeyFilter());
}
}
这是我的api控制器:
This is my api controller:
[Authorize]
public class CategoriesController : ApiController
{
private WebAPI2Context db = new WebAPI2Context();
// GET: api/Categories
public IQueryable<Category> GetCategories()
{
return db.Categories;
}
}
有什么办法可以解决这个问题?我尝试用Google搜索它,发现所有结果对我都不起作用.
Is there any way to fix this? I try to google it, all results I found not work for me.
推荐答案
没有什么明显的错误,尽管不要将过滤器与处理程序混淆.
Nothing too obvious wrong although don't confuse filters with handlers.
可能是您试图从运行在另一个进程中的另一个端口上的网站调用Web API控制器.可能是由以下可能的问题1、2或两者引起的.
It might be that you are trying to make calls to the Web API controller from a website running in another process, on a different port. Could be caused by Possible issue 1, 2 or both below.
可能的原因1
也许这是CORS问题.如果没有来自响应的更多信息,很难说出来.尝试将其添加到您的全局:
Perhaps this is a CORS issue. Hard to tell without more info from response. Try adding this to your Global:
var cors = new EnableCorsAttribute("*", "*", "*");
GlobalConfiguration.Configuration.EnableCors(cors);
对于战斗前检查,我将在自定义处理程序中的If
下添加以下内容:
and for pre-fight checks I'd add the following under the If
you have in your custom handler:
if (request.Headers.Contains("Origin") && request.Method.Method == "OPTIONS")
{
var response = new HttpResponseMessage();
response.StatusCode = HttpStatusCode.OK;
response.Headers.Add("Access-Control-Allow-Origin", "*");
response.Headers.Add("Access-Control-Allow-Headers", "Origin, Content-Type, Accept, Authorization");
//Worked before for deletes but CORS came back out of blue for deletes so changed * for DELETE and content doing al CRUD at the moment..
response.Headers.Add("Access-Control-Allow-Methods", "DELETE, POST, PUT, OPTIONS, GET");
}
如果是这样,您都需要安装NuGet:Microsoft.AspNet.WebApi.Cors
If it is this you'll all need to install the NuGet: Microsoft.AspNet.WebApi.Cors
可能的原因2
您还需要确保machineKey
的配置文件设置相同.
You will also need to ensure machineKey
is set the same the config files for both.
按照以下URL中的说明进行操作以匹配应用程序之间的设置,就可以了:
Follow the instructions in the following URL to match up the settings between the applications and you should be fine:
https://msdn.microsoft.com/en-us/library/eb0zx8fc.aspx
这篇关于使用API密钥验证创建ASP.NET Web API时,授权被拒绝的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!