如何在不同域的 MVC 前端和 Web Api 之间实现防伪令牌?
How can I implement the Anti-Forgery Token between MVC frontend and Web Api on different domains?
- 我想在
www.example1.com
上安装 MVC 项目
api.example2.com
上的 WebApi 项目
我想限制对 WebApi 的访问。
我已尝试实施防伪令牌:
当我使用防伪令牌创建对 WebApi 的 GET 请求时,出现异常,因为该请求不包含此令牌。
在调用的方法中 ValidateRequestHeader
是变量 cookie = null
。
如何修复以下代码?这是正确的解决方案吗?
MVC 项目(前端)- 开发是 localhost:33635
:
Index.cshtml
<div class="container">
<div class="row">
<div class="col-md-12">
<input id="get-request-button" type="button" class="btn btn-info" value="Create request to API Server" />
<br />
<div id="result"></div>
</div>
</div>
</div>
@section scripts
{
<script type="text/javascript">
@functions{
public string TokenHeaderValue()
{
string cookieToken, formToken;
AntiForgery.GetTokens(null, out cookieToken, out formToken);
return cookieToken + ":" + formToken;
}
}
$(function () {
$("#get-request-button").click(function () {
$.ajax("http://localhost:33887/api/values", {
type: "GET",
contentType: "application/json",
data: {},
dataType: "json",
headers: {
'RequestVerificationToken': '@TokenHeaderValue()'
}
}).done(function (data) {
$("#result").html(data);
});
return false;
});
});
</script>
}
WebApi 项目 - 用于开发的是 localhost:33887
:
WebApiConfig.cs
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
config.EnableCors(new EnableCorsAttribute("http://localhost:33635", "*", "*"));
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
ValidateHttpAntiForgeryTokenAttribute.cs:
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class)]
public sealed class ValidateHttpAntiForgeryTokenAttribute : FilterAttribute, IAuthorizationFilter
{
public Task<HttpResponseMessage> ExecuteAuthorizationFilterAsync(HttpActionContext actionContext, CancellationToken cancellationToken, Func<Task<HttpResponseMessage>> continuation)
{
var request = actionContext.Request;
try
{
if (IsAjaxRequest(request))
{
ValidateRequestHeader(request);
}
else
{
AntiForgery.Validate();
}
}
catch (Exception)
{
actionContext.Response = new HttpResponseMessage
{
StatusCode = HttpStatusCode.Forbidden,
RequestMessage = actionContext.ControllerContext.Request
};
return FromResult(actionContext.Response);
}
return continuation();
}
private Task<HttpResponseMessage> FromResult(HttpResponseMessage result)
{
var source = new TaskCompletionSource<HttpResponseMessage>();
source.SetResult(result);
return source.Task;
}
private bool IsAjaxRequest(HttpRequestMessage request)
{
IEnumerable<string> xRequestedWithHeaders;
if (!request.Headers.TryGetValues("X-Requested-With", out xRequestedWithHeaders)) return false;
var headerValue = xRequestedWithHeaders.FirstOrDefault();
return !String.IsNullOrEmpty(headerValue) && String.Equals(headerValue, "XMLHttpRequest", StringComparison.OrdinalIgnoreCase);
}
private void ValidateRequestHeader(HttpRequestMessage request)
{
var headers = request.Headers;
var cookie = headers
.GetCookies()
.Select(c => c[AntiForgeryConfig.CookieName])
.FirstOrDefault();
IEnumerable<string> xXsrfHeaders;
if (headers.TryGetValues("RequestVerificationToken", out xXsrfHeaders))
{
var rvt = xXsrfHeaders.FirstOrDefault();
if (cookie == null)
{
throw new InvalidOperationException($"Missing {AntiForgeryConfig.CookieName} cookie");
}
AntiForgery.Validate(cookie.Value, rvt);
}
else
{
var headerBuilder = new StringBuilder();
headerBuilder.AppendLine("Missing X-XSRF-Token HTTP header:");
foreach (var header in headers)
{
headerBuilder.AppendFormat("- [{0}] = {1}", header.Key, header.Value);
headerBuilder.AppendLine();
}
throw new InvalidOperationException(headerBuilder.ToString());
}
}
}
值控制器:
public class ValuesController : ApiController
{
// GET: api/Values
[ValidateHttpAntiForgeryToken]
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
// GET: api/Values/5
public string Get(int id)
{
return "value";
}
// POST: api/Values
public void Post([FromBody]string value)
{
}
// PUT: api/Values/5
public void Put(int id, [FromBody]string value)
{
}
// DELETE: api/Values/5
public void Delete(int id)
{
}
}
这不是限制其他服务访问的方式。 ForgeryToken 有助于防止 CSRF 攻击,ASP.NET MVC 使用防伪令牌,也称为请求验证令牌。客户端请求包含表单的 HTML 页面。服务器在响应中包含两个令牌。一个令牌作为 cookie 发送。当您提交表单时,它们将在同一服务器上匹配。
我相信,你需要的是从example1.com
到api.example2.com
的信任。 An example would be stackauth which is a domain for centralized services across the entire Stack Exchange network。然后你可以在你的项目中实现你需要的授权。
- 我想在
www.example1.com
上安装 MVC 项目
api.example2.com
上的 WebApi 项目
我想限制对 WebApi 的访问。 我已尝试实施防伪令牌:
当我使用防伪令牌创建对 WebApi 的 GET 请求时,出现异常,因为该请求不包含此令牌。
在调用的方法中 ValidateRequestHeader
是变量 cookie = null
。
如何修复以下代码?这是正确的解决方案吗?
MVC 项目(前端)- 开发是 localhost:33635
:
Index.cshtml
<div class="container">
<div class="row">
<div class="col-md-12">
<input id="get-request-button" type="button" class="btn btn-info" value="Create request to API Server" />
<br />
<div id="result"></div>
</div>
</div>
</div>
@section scripts
{
<script type="text/javascript">
@functions{
public string TokenHeaderValue()
{
string cookieToken, formToken;
AntiForgery.GetTokens(null, out cookieToken, out formToken);
return cookieToken + ":" + formToken;
}
}
$(function () {
$("#get-request-button").click(function () {
$.ajax("http://localhost:33887/api/values", {
type: "GET",
contentType: "application/json",
data: {},
dataType: "json",
headers: {
'RequestVerificationToken': '@TokenHeaderValue()'
}
}).done(function (data) {
$("#result").html(data);
});
return false;
});
});
</script>
}
WebApi 项目 - 用于开发的是 localhost:33887
:
WebApiConfig.cs
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
config.EnableCors(new EnableCorsAttribute("http://localhost:33635", "*", "*"));
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
ValidateHttpAntiForgeryTokenAttribute.cs:
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class)]
public sealed class ValidateHttpAntiForgeryTokenAttribute : FilterAttribute, IAuthorizationFilter
{
public Task<HttpResponseMessage> ExecuteAuthorizationFilterAsync(HttpActionContext actionContext, CancellationToken cancellationToken, Func<Task<HttpResponseMessage>> continuation)
{
var request = actionContext.Request;
try
{
if (IsAjaxRequest(request))
{
ValidateRequestHeader(request);
}
else
{
AntiForgery.Validate();
}
}
catch (Exception)
{
actionContext.Response = new HttpResponseMessage
{
StatusCode = HttpStatusCode.Forbidden,
RequestMessage = actionContext.ControllerContext.Request
};
return FromResult(actionContext.Response);
}
return continuation();
}
private Task<HttpResponseMessage> FromResult(HttpResponseMessage result)
{
var source = new TaskCompletionSource<HttpResponseMessage>();
source.SetResult(result);
return source.Task;
}
private bool IsAjaxRequest(HttpRequestMessage request)
{
IEnumerable<string> xRequestedWithHeaders;
if (!request.Headers.TryGetValues("X-Requested-With", out xRequestedWithHeaders)) return false;
var headerValue = xRequestedWithHeaders.FirstOrDefault();
return !String.IsNullOrEmpty(headerValue) && String.Equals(headerValue, "XMLHttpRequest", StringComparison.OrdinalIgnoreCase);
}
private void ValidateRequestHeader(HttpRequestMessage request)
{
var headers = request.Headers;
var cookie = headers
.GetCookies()
.Select(c => c[AntiForgeryConfig.CookieName])
.FirstOrDefault();
IEnumerable<string> xXsrfHeaders;
if (headers.TryGetValues("RequestVerificationToken", out xXsrfHeaders))
{
var rvt = xXsrfHeaders.FirstOrDefault();
if (cookie == null)
{
throw new InvalidOperationException($"Missing {AntiForgeryConfig.CookieName} cookie");
}
AntiForgery.Validate(cookie.Value, rvt);
}
else
{
var headerBuilder = new StringBuilder();
headerBuilder.AppendLine("Missing X-XSRF-Token HTTP header:");
foreach (var header in headers)
{
headerBuilder.AppendFormat("- [{0}] = {1}", header.Key, header.Value);
headerBuilder.AppendLine();
}
throw new InvalidOperationException(headerBuilder.ToString());
}
}
}
值控制器:
public class ValuesController : ApiController
{
// GET: api/Values
[ValidateHttpAntiForgeryToken]
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
// GET: api/Values/5
public string Get(int id)
{
return "value";
}
// POST: api/Values
public void Post([FromBody]string value)
{
}
// PUT: api/Values/5
public void Put(int id, [FromBody]string value)
{
}
// DELETE: api/Values/5
public void Delete(int id)
{
}
}
这不是限制其他服务访问的方式。 ForgeryToken 有助于防止 CSRF 攻击,ASP.NET MVC 使用防伪令牌,也称为请求验证令牌。客户端请求包含表单的 HTML 页面。服务器在响应中包含两个令牌。一个令牌作为 cookie 发送。当您提交表单时,它们将在同一服务器上匹配。
我相信,你需要的是从example1.com
到api.example2.com
的信任。 An example would be stackauth which is a domain for centralized services across the entire Stack Exchange network。然后你可以在你的项目中实现你需要的授权。