繁体   English   中英

保护MVC4 c#webapi,以便只有我的应用才能访问它

[英]Secure MVC4 c# webapi so that only my app can access it

我在这里看过一些帖子,但似乎找不到合适的答案,希望有人可以提供帮助。

我见过你可以添加

[认证]

mvc控制器的属性。 这在人们可以登录的网站情况下是合理的,但我有一个与Web服务通信的iOS应用程序。 我想限制只访问我的应用程序。

我认为所需的“步骤”是:

  1. 为所有webapi操作添加某种“[authenticate]”属性(或者在全局级别上更好)
  2. 为Web服务创建某种ssl证书
  3. 添加某种身份验证方法并将凭据硬编码到应用程序代码中

如何利用mvc框架完成这个或类似的工作?

(PS:看到喜欢的帖子却是非常不现实添加此逻辑每一段代码的动作,也什么样的“挑战”我会创造?)

有一些简单的方法可以验证您自己的Web服务,并且您不必使用任何花哨的东西,甚至不必遵循某些标准,如OAuth或OpenID(不是这些很糟糕,但听起来你想要站起来在门口用简单的东西)。

您需要做的第一件事是学习如何从AuthorizeAttribute派生( System.Web.Http命名空间中的那个,而不是MVC)。 您重写OnAuthorization函数并将您的身份验证逻辑放在那里。 请参阅此帮助, MVC Api Action&System.Web.Http.AuthorizeAttribute - 如何获取帖子参数?

接下来决定您要如何进行身份验证。 在最基本的形式中,您可以执行诸如为每个名为MyID: [SomeRandomString] Web请求添加标题MyID: [SomeRandomString] 然后在OnAuthorization方法中检查请求的标头,如果它不是正确的字符串,则将响应状态代码设置为401(未授权)。

如果您的服务是自托管的,那么您可以将证书绑定到它所托管的端口并使用https://前缀,您现在已经保护了传输层,因此人们无法看到您传递的ID /密码。 如果您在IIS中托管,您可以通过它绑定证书。 这很重要,因为通过普通HTTP传递密码之类的东西并不安全。


创建自定义AuthorizeAttribute

public class PasswordAuthorizeAttribute : System.Web.Http.AuthorizeAttribute
{
    public override void OnAuthorization(System.Web.Http.Controllers.HttpActionContext actionContext)
    {
        try
        {
            string password = actionContext.Request.Headers.GetValues("Password").First();

            // instead of hard coding the password you can store it in a config file, database, etc.
            if (password != "abc123")
            {
                // password is not correct, return 401 (Unauthorized)
                actionContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized);
                return;
            }
        }
        catch (Exception e)
        {
            // if any errors occur, or the Password Header is not present we cannot trust the user
            // log the error and return 401 again
            actionContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized);
            return;
        }
    }
}

[PasswordAuthorize]
public class YourController : ApiController
{
}

生成自签名证书

生成自签名证书的最简单方法是打开IIS,单击服务器证书,然后“生成自签名证书”,如下所示, http://www.sslshopper.com/article-how-to-create-a-self -signed证书,在-IIS-7.html


将证书绑定到端口

http://msdn.microsoft.com/en-us/library/ms733791.aspx

netsh http add sslcert ipport=0.0.0.0:8000 certhash=0000000000003ed9cd0c315bbb6dc1c08da5e6 appid={00112233-4455-6677-8899-AABBCCDDEEFF} 

这里有一个关于如何通过https自助托管api服务的精彩教程, http://pfelix.wordpress.com/2012/02/26/enabling-https-with-self-hosted-asp-net-web -API /


暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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