如何在MVC4 Web API中实现授权?

时间:2013-12-06 08:31:48

标签: asp.net-mvc-4 asp.net-web-api authorization

我创建了一个MVC4 Web API。但未经授权的人也可以使用它。 示例:人们在地址栏中输入“/ api / product / 1”也可以得到结果。 那么,如何实现安全性并允许授权人只使用WEB API? 如何授权允许登录web api的人?

2 个答案:

答案 0 :(得分:0)

有关Authentication and Authorization

的更多信息

只需将注释添加到控制器即可:

// 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
{
}

答案 1 :(得分:0)

您可以使用MVC4 AspNet.identiy.Usermanager和Microsoft.Owin.Security来验证用户..

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) };
       }

它对我有用....