Ayesha
Ayesha

Reputation: 31

Authorization has been denied for this request error when running webapi in MVC project

I have created an ASP.Net MVC project with WebApi option. Then modified the values controller with the code below:

public class ValuesController : ApiController
{
    static List<string> data = initList();

    private static List<string> initList()
    {
        var ret = new List<string>();
        ret.Add("value1");
        ret.Add( "value2" );

        return ret;
    }

    // GET api/values
    public IEnumerable<string> Get()
    {
        return data ;
    }

    // GET api/values/5
    public string Get(int id)
    {
        return data[id];
    }

    // POST api/values
    public void Post([FromBody]string value)
    {
        data.Add(value);
    }

    // PUT api/values/5
    public void Put(int id, [FromBody]string value)
    {
        data[id] = value;
    }

    // DELETE api/values/5
    public void Delete(int id)
    {
        data.RemoveAt(id);
    }
}

When I am running the project and navigating to API/values URL, the following image is showing error.

error when running webapi MVC project.

The error description in text is:

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

Upvotes: 2

Views: 8777

Answers (2)

gspotprod
gspotprod

Reputation: 25

So, I've been dealing with this error for awhile.

I didn't understand it at first, so I just removed and lived with it.

I finally got sick of it, because it's rather stupid. Microsoft wants a user to be authorized before they have signed in.

My error was looking for GET method which asks for HomeTown. In my case, I had changed it to CityCode.

Since the user is not logged in, there is no CityCode to GET. So, you get either a 402 or a 500 Resource Not Found.

I still don't understand it so, I gave CityCode some default data. So, from MeController I put the following code:

Public Function [Get]() As GetViewModel

Dim userInfo As ApplicationUser = UserManager.FindById(User.Identity.GetUserId())

Return New GetViewModel() With {.CityCode = "94110"}

End Function

App loads completely error free now.

This is a quick fix, not a certified solution.

Upvotes: 0

Nkosi
Nkosi

Reputation: 247008

Have a look at the following article about

Authentication and Authorization in ASP.NET Web API

It will explain the different ways of how to use the [Authorize] and [AllowAnonymous] attribute on your controller/actions and any configurations you would need to do.

The following was taken from the linked article above:

Using the [Authorize] Attribute

Web API provides a built-in authorization filter, AuthorizeAttribute. This filter checks whether the user is authenticated. If not, it returns HTTP status code 401 (Unauthorized), without invoking the action.

You can apply the filter globally, at the controller level, or at the level of inidivual actions.

Globally: To restrict access for every Web API controller, add the AuthorizeAttribute filter to the global filter list:

public static void Register(HttpConfiguration config){
    config.Filters.Add(new AuthorizeAttribute());
}

Controller: To restrict access for a specific controller, add the filter as an attribute to the controller:

// Require authorization for all actions on the controller.
[Authorize]
public class ValuesController : ApiController
{
    public HttpResponseMessage Get(int id) { ... }
    public HttpResponseMessage Post() { ... }
}

Action: To restrict access for specific actions, add the attribute to the action method:

public class ValuesController : ApiController
{
    public HttpResponseMessage Get() { ... }

    // Require authorization for a specific action.
    [Authorize]
    public HttpResponseMessage Post() { ... }
}

Alternatively, you can restrict the controller and then allow anonymous access to specific actions, by using the [AllowAnonymous] attribute. In the following example, the Post method is restricted, but the Get method allows anonymous access.

[Authorize] 
public class ValuesController : ApiController {
    [AllowAnonymous]
    public HttpResponseMessage Get() { ... }

    public HttpResponseMessage Post() { ... } 
}

In the previous examples, the filter allows any authenticated user to access the restricted methods; only anonymous users are kept out. You can also limit access to specific users or to users in specific roles:

// Restrict by user:
[Authorize(Users="Alice,Bob")]
public class ValuesController : ApiController
{
}

// Restrict by role:
[Authorize(Roles="Administrators")]
public class ValuesController : ApiController
{
}

Upvotes: 1

Related Questions