如何使用ASP.NET的Web API制作私有/受保护的API?

如何使用ASP.NET的Web API制作私有/受保护的API?,asp.net,.net,asp.net-mvc,api,asp.net-web-api,Asp.net,.net,Asp.net Mvc,Api,Asp.net Web Api,我想使用ASP.NET WEB API制作API,这些API应该是私有的或受保护的。 使用API,我计划制作Xamarin应用程序和MVC网站。 只有应用程序可以使用API,否则,如果任何人获得API,则他/她可以使用API检索数据。我不想这样 我怎么做?我需要一些建议。您可以使用api密钥身份验证机制保护您的api。这是一个很好的开始,进入global.asax.cs文件并添加 GlobalConfiguration.Configuration.MessageHandlers.Add(new

我想使用
ASP.NET WEB API
制作API,这些API应该是私有的或受保护的。 使用API,我计划制作Xamarin应用程序和MVC网站。 只有应用程序可以使用API,否则,如果任何人获得API,则他/她可以使用API检索数据。我不想这样


我怎么做?我需要一些建议。

您可以使用api密钥身份验证机制保护您的api。这是一个很好的开始,进入global.asax.cs文件并添加

GlobalConfiguration.Configuration.MessageHandlers.Add(new AuthHandler())
在项目中创建类AuthHandler,并使该类与DelegatingHandler接口:

public class AuthHandler: DelegatingHandler
在AuthHandler类中创建两个名为ValidateCredentials和SendAsync的方法。SendAsync方法被重写

private bool ValidateCredentials(AuthenticationHeaderValue authVal){}
protected override async Task<HttpResponseMessage> SendAsync(HttpResponseMessage request, CancellationToken cancelTok){}
所以剩下的是用户的实际身份验证。您需要获取标题值(由客户端应用程序放置),对其进行解码,并根据您的数据库或您使用的任何内容进行检查

private bool ValidateCredentials(AuthenticationHeaderValue authVal)
{
    try{
        string decodedHeader = new Classes.Strings().decode(authVal);
        this.user = // some query to check against database goes here
        return true;
    }
    catch{
        // some type of error control here
        return false
    }
}
 protected override async Task<HttpResponseMessage> SendAsync(HttpResponseMessage request, CancellationToken cancelTok)
{
    if(ValidateCredentials(request.Headers.Authorization))
    {
        // store user here to use around the api on this request
    }
}
private bool ValidateCredentials(AuthenticationHeaderValue authVal)
{
试一试{
string decodedHeader=新类.Strings().decode(authVal);
this.user=//此处是要检查数据库的查询
返回true;
}
抓住{
//这里有一些类型的错误控制
返回错误
}
}
受保护的覆盖异步任务SendAsync(HttpResponseMessage请求,CancellationToken cancelTok)
{
if(ValidateCredentials(request.Headers.Authorization))
{
//将用户存储在此处,以便在此请求中围绕api使用
}
}

因此,简而言之,HTTP需要存储您的身份验证头值。在每个请求上使用该值来筛选需要验证的任何类或函数。接下来,我将阅读http头,特别是身份验证头值。

OAuth2
也是一个很好的选择,请参阅
private bool ValidateCredentials(AuthenticationHeaderValue authVal)
{
    try{
        string decodedHeader = new Classes.Strings().decode(authVal);
        this.user = // some query to check against database goes here
        return true;
    }
    catch{
        // some type of error control here
        return false
    }
}
 protected override async Task<HttpResponseMessage> SendAsync(HttpResponseMessage request, CancellationToken cancelTok)
{
    if(ValidateCredentials(request.Headers.Authorization))
    {
        // store user here to use around the api on this request
    }
}