I have an existing API that has No Authentication. It`s a public Web API which several clients use by making simple requests.
Now, there is the need to authorize access to a certain method.
Is there any way to do this, keeping the rest of the controllers and respective methods "open" for the clients that already use this Web API?
How can i identify if the request has permissions to access this "protected" method?
You can use
[Authorize]
attribute at particular API method as well as at controller level. In case you put the[Authorize]
attribute at controller level then you can use[AllowAnonymous]
attribute for those API method which you want to access without authentication.We solved it using [AllowAnonymous] on the method, who we didn't want to be Authenticated but Authorizated, overriding the Authorization.
By default, authorization is globally disabled on application. You can force your controller to only allow authorized requests by adding the action filter [Authorize].
You can also force only certain methods be authorized:
Or just disable authorization on some methods inside a controller that requires authorization:
You can also set who's allowed to access your method by using:
Or by Rules using:
Or even build a more complex Authorize attribute like in this answer (Based on Claims): Authorization Attribute by Claims
The Execution flow will goes to method level then its goes to Controller Level. So if you mention as "AllowAnonymous" will execute with out Authorization check.
What you'll need to do is add an
[Authorize]
attribute to the methods you want to protect optionally using the overload that accepts one or more role names that the calling user must be in.Then what you'll have to implement is a way to ensure that authentication data of the caller is transformed into a Principal object. Setting the Principal is generally something you don't do yourself, but instead have the framework do for you.
If you do want to provide your own interface, you can using an authentication filter implementing the
System.Web.Http.Filters.IAuthenticationFilter
interface.So what you'll get is this:
And then implement the
MyAuthentication
attribute. Below is an example, the important thing is that you use the context of the incoming request and end up setting thecontext.Principal
property with a new PrincipalI hope this helps you get on the right track. For more information check this post: http://www.asp.net/web-api/overview/security/authentication-filters