realtek
realtek

Reputation: 841

How to Setup Authentication for Web API?

I have a asp.net application I wrote which has a lot of Web API controllers.

Currently, when a user logs into my application it uses Sessions, and the user account is authenticated with my own SQL table storing username and password (Hashed) etc...

If the user knows or views the js source/or fiddler they can see the Web API call and get the URL for that Controller which they could potentially call outside the application.

I would like to somehow secure this so it does not allow them to access it outside the application, or even better check the user is allowed to execute the request.

What is the best way of doing this?

Thanks

Upvotes: 1

Views: 96

Answers (2)

Win
Win

Reputation: 62300

I would like to somehow secure this so it does not allow them to access it outside the application.

Based on my understanding of the question, you do not want other applications to access your API except yours.

By default, if client application and Web API are in same domain, it is already protected unless you explicitly enable CORS.

even better check the user is allowed to execute the request

AuthorizeAttribute should take care of the Authentication and Authorization, unless you hand-roll the security by yourself.

Upvotes: 1

Izzy
Izzy

Reputation: 6866

You can use the AuthorizeAttribute to achieve what you're after.

From MSDN

Specifies that access to a controller or action method is restricted to users who meet the authorization requirement.

The following example shows a simplified account controller that restricts or permits access to action methods. The AuthorizeAttribute attribute is applied to the controller so the user must be authorized to access any of the action methods; however, the AllowAnonymousAttribute attribute is applied to the Register method to override the requirement for the user to be authorized. The Manage and LogOff methods are restricted to authorized users.

[Authorize] 
public class AccountController : Controller
{
public AccountController () { . . . }

[AllowAnonymous]
public ActionResult Register() { . . . }

public ActionResult Manage() { . . . }

public ActionResult LogOff() { . . . }
. . .
} 

Upvotes: 1

Related Questions