简体   繁体   中英

Can I bypass organizational authentication for a WebAPI controller inside an MVC app?

I have an MVC5, EF6 app which uses organizational authentication (Azure AD) and all is working fine except for one thing. There is a requirement for a WebAPI controller to process requests from unauthenticated clients. The clients are normally Android devices issuing AJAX requests.

Before I added organizational authentication to my MVC app, my WebAPI controller was being called and functioned correctly so I know my routing is correct. Now I've added organizational authentication, my WebAPI controller is no longer called and the client's AJAX request times out.

I understand there are attributes such as [Authorize] to specify access to controllers/methods but when using organizational authentication, it appears that WebAPI controllers without the [Authorize] attribute do not get called.

My question is, can I mark my WebAPI controller to allow requests from unauthenticated clients, if so how can I do it?

Many thanks.

The answer is to allow anonymous connections to a specific controller by entering the xml below into the root Web.config file.

If your controller is called "PersonController", then the name you should enter into the path attribute is "person" NOT "personcontroller".

In my case, because I want to allow anonymous requests to a WebAPI controller, I need to prefix my controller name in the path attribute with "api/".

Hope this helps others who may run into the same issue.

<location path="api/my-controller-name">
  <system.web>
    <authorization>
      <allow users="?" />
    </authorization>
  </system.web>
</location>

If you want to allow anonymous access you can use the [AllowAnonymous] attribute.

You can either add this above the ApiController to mark the whole controller for anonymous acces like:

[AllowAnonymous]
public class MyApiController : ApiController
{
}

Or you can give a specific method this attribute, to allow that method to be called anonymously:

[Authorize]
public class MyApiController : ApiController
{
    [AllowAnonymous]
    public string GetData() 
    {

    }
}

This will block access to all methods when a user is not authorized, except the GetData() method which can be called anonymously.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM