I Had create a MVC4 Web API. But People without authorization also can use it. Example: people type in address bar "/api/product/1" also can get the result. So, How to implement Security and allow authorize person to use the WEB API only ? How to give authorize to the person that allow login to web api ?
-
stackoverflow.com/questions/14365373/…Marthijn– Marthijn2013-12-06 08:36:17 +00:00Commented Dec 6, 2013 at 8:36
-
What type of authorization are you look for? Credentials based? Is your API public? If you are looking to do server-to-server authentication you could look at HMAC based authentication which is quite awesome. This answer speaks about a WebAPI implementation: stackoverflow.com/a/11782361/350933ctrlplusb– ctrlplusb2013-12-06 09:43:06 +00:00Commented Dec 6, 2013 at 9:43
Add a comment
|
2 Answers
More info about Authentication and Authorization
Simply adding the annotation to your controller will do:
// Require authorization for all actions on the controller.
[Authorize]
public class ValuesController : ApiController
{
public HttpResponseMessage Get(int id) { ... }
public HttpResponseMessage Post() { ... }
}
// Restrict by user:
[Authorize(Users="Alice,Bob")]
public class ValuesController : ApiController
{
}
// Restrict by role:
[Authorize(Roles="Administrators")]
public class ValuesController : ApiController
{
}
2 Comments
Calvin Pang
how to authenticate user to gv the authorize to the user.
Sentinel
I'm not sure what you are asking here but I suppose you want a way to authenticate a user or role, those are in the article link, I'll update the answer
you can use MVC4 AspNet.identiy.Usermanager and Microsoft.Owin.Security to authenticate user..
private IAuthenticationManager AuthenticationManager
{
get
{
return HttpContext.Current.GetOwinContext().Authentication;
}
}
public HttpResponseMessage Login(string username, string password)
{
UserManager<TenantUser> userManager=new new UserManager<TenantUser>(new UserStore<TenantUser>(YOUR DBCONTEXT));
var user = UserManager.Find(username, password);
if (user != null)
{
AuthenticationManager.SignOut(DefaultAuthenticationTypes.ApplicatioCookie);
ClaimsIdentity identity = await UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);
AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = true }, identity);
}
else
new HttpResponseMessage(HttpStatusCode.Forbidden) { Content = new ObjectContent<object>(new { Error = "You are not authorized to perform this action" }, Configuration.Formatters.JsonFormatter) };
}
it is working for me....