Authorization has been denied for this request - New Web API Project

亡梦爱人 提交于 2020-01-11 15:06:22

问题


I just created new Web API project (using MVC) in visual studio 2015 and for the testing purpose, I ran that project but ended up below error.

After running the project, it brings up Home Page correctly but when I navigated to /api/values or /api/values/5, it gives me below xml message.

<Error>
    <Message>Authorization has been denied for this request.</Message>
</Error>

Can someone please help? I am new to Web API. Please note that I don't want to remove the Authorize attribute. I would like to access the resource after authorization only. So I am looking for what is wrong.


回答1:


In the ValuesController there is an attribute Authorize if you remove it, then it will work as home page.

The Authorize attribute just prevent an anonymous users from accessing the ValuesController.

to work with this attribute, you need first to register a user, and then login to get user's token, then you can use the token to authorize your self and get access .

In this page Individual-accounts-in-web-api is explained all what do you need




回答2:


It happens because you have an Authorize attribute on your ValuesController

[Authorize]
public class ValuesController : ApiController

Just remove [Authorize] and try again

EDIT

According to your edit: You should create a new user and login or use [AllowAnonymous] as mentioned by @Marcus H. Read more about Identity




回答3:


After remove a authorize attribute on you method in a controller like [Authorize] or even a manual authorization attribute like this [BasicAuthentication] that you created (expect you handle it), you have to put this attribute [AllowAnonymous] on you method name.




回答4:


I got the answer here.

https://stackoverflow.com/a/29405794/8107314

And it was very useful to fix my error my error

I just came across the same problem and found the solution:

You need to register the OAuth Token Generator and OAuth Token Consumer things before WebAPI is registered.

Kind of makes sense if you think of this as a pipeline, where Authentication/Authorization should come before any request handling by the controllers.

TL;DR: Change

appBuilder.UseWebApi(config);

this.ConfigureOAuthTokenGenerator(appBuilder);
this.ConfigureOAuthConsumer(appBuilder);

To

this.ConfigureOAuthTokenGenerator(appBuilder);
this.ConfigureOAuthConsumer(appBuilder);

appBuilder.UseWebApi(config);


来源:https://stackoverflow.com/questions/38963435/authorization-has-been-denied-for-this-request-new-web-api-project

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!