是否可以阻止所有不是来自网站本身的对我的网络API的调用?
我的意思是如果我的MVC应用程序运行在:http://www.domain.com和web http://www.domain.com/api/service,我希望web api仅接受来自当前应用程序的调用。不允许外部电话。
我猜想在这种情况下,消息处理程序可能是最好的吗?
答案 0 :(得分:0)
为错误页面创建一个Controller并捕获所有垃圾请求:
config.Routes.MapHttpRoute("block", "{*something}", new { controller = "Error", action = "Get" });
答案 1 :(得分:0)
您应该使用委托处理程序实现令牌授权。
public class AuthorizationHeaderHandler : DelegatingHandler
{
public AuthorizationHeaderHandler(HttpConfiguration httpConfiguration)
{
//set the inner handler
InnerHandler = new HttpControllerDispatcher(httpConfiguration);
}
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
IEnumerable<string> apiKeyHeaderValues = null;
if (request.Headers.TryGetValues("X-ApiKey", out apiKeyHeaderValues))
{
var apiKeyHeaderValue = apiKeyHeaderValues.First();
//based on the api-key get username whose session is stil valid.
var username = //code to get user based on apiKeyHeaderValue;
if (!string.IsNullOrEmpty(username))
{
var usernameClaim = new Claim(ClaimTypes.Name, username);
var identity = new ClaimsIdentity(new[] {usernameClaim}, "ApiKey");
var principal = new ClaimsPrincipal(identity);
Thread.CurrentPrincipal = principal;
}
}
else
{
//You don't have an ApiKey from the request... can't proceed
var response = request.CreateResponse(HttpStatusCode.Forbidden,
new {Message = "You are not Authorized to access that resource"}); //new HttpResponseMessage(HttpStatusCode.Forbidden);
var tsc = new TaskCompletionSource<HttpResponseMessage>();
tsc.SetResult(response);
return tsc.Task;
}
return base.SendAsync(request, cancellationToken);
}
}
然后,您可以在WebApiConfig
中注册处理程序 public class WebApiConfig
{
public static void Init(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional },
constraints:null,
handler: new AuthorizationHeaderHandler(GlobalConfiguration.Configuration)
);
}
}
然后,您可以设置登录控制器以授权用户并分配令牌
public class UserController : ApiController
{
public async Task<HttpResponseMessage> Login([FromBody] UserDTO userDTO)
{
// first perform user authentication.
// clear all existing tokens for this authorized user
//create security token and save token of current user
//You can store this in a database and use a repository to create these.
// Tokens can be guids.
// await token creation
return Request.CreateResponse(HttpStatusCode.OK, new {LogingResult = result, token = token});
}
}
一旦该用户拥有该令牌,就可以通过添加到请求头来将其用于Api请求。在Angularjs中,它可以采用以下形式。
'use strict';
(function(){
angular.module('App', ['ngRoute', 'ngCookies']);
//interceptor for server calls
var httpInterceptor = function ($q, $window, $location) {
return function(promise) {
var success = function(response) {
return response;
};
var error = function(response) {
if (response.status === 403) {
$location.url('/login');
}
return $q.reject(response);
};
return promise.then(success, error);
};
}
httpInterceptor['$inject'] = ['$q', '$window', '$location'];
angular.module('App').factory('httpInterceptor', httpInterceptor);
var api = function ($http, $cookies) {
return {
init: function (token) {
$http.defaults.headers.common['X-ApiKey'] = token || $cookies.token;
}
};
}
api['$inject'] = ['$http', '$cookies'];
angular.module('App').factory('api', api);
})();
答案 2 :(得分:0)
是的,这绝对是可能的。您必须为请求中的RemoteIpAddress创建自定义处理程序和筛选器。这是使用Owin Self-Host的实现:
public class CustomerHandler : DelegatingHandler
{
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request,
CancellationToken cancellationToken)
{
if (request?.GetClientIpAddress() != "127.0.0.1")
{
return await Task.FromResult(request.CreateResponse(HttpStatusCode.Unauthorized));
}
return await base.SendAsync(request, cancellationToken);
}
}
public static class HttpReqestMessageExtension
{
public static string GetClientIpAddress(this HttpRequestMessage request)
{
if (!request.Properties.ContainsKey("MS_OwinContext")) return null;
dynamic owinContext = request.Properties["MS_OwinContext"];
return owinContext.Request.RemoteIpAddress;
}
}
如果您在哪里使用ASP.Net,那么您将使用适当的密钥=&gt; MS_HttpContext
现在您只需将其添加到Api的启动中:
var config = new HttpConfiguration();
config.MessageHandlers.Add(new CustomerHandler());