【发布时间】:2023-03-15 08:04:02
【问题描述】:
只是想知道是否有任何示例展示了在使用 angular2 构建富客户端时如何使用防伪令牌,该客户端使用一组基于 .NET 4.5 构建的 Web api2 服务中的数据。 Web api 服务不是用 asp.net 核心构建的,也不会在接下来的几个月内更新。
对于这种情况,推荐的方法是什么?
谢谢,
路易斯
【问题讨论】:
标签: angular asp.net-web-api antiforgerytoken
只是想知道是否有任何示例展示了在使用 angular2 构建富客户端时如何使用防伪令牌,该客户端使用一组基于 .NET 4.5 构建的 Web api2 服务中的数据。 Web api 服务不是用 asp.net 核心构建的,也不会在接下来的几个月内更新。
对于这种情况,推荐的方法是什么?
谢谢,
路易斯
【问题讨论】:
标签: angular asp.net-web-api antiforgerytoken
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web;
using System.Web.Helpers;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;
using System.Web.Mvc;
using ActionFilterAttribute = System.Web.Http.Filters.ActionFilterAttribute;
namespace NgxAntiforgeryWebApi.Providers
{
public class XsrfCookieGeneratorAttribute : ActionFilterAttribute
{
public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
{
var xsrfTokenCookie = new HttpCookie("XSRF-TOKEN")
{
Value = ComputeXsrfTokenValue(),
HttpOnly = false // Now JavaScript is able to read the cookie
};
HttpContext.Current.Response.AppendCookie(xsrfTokenCookie);
}
private string ComputeXsrfTokenValue()
{
string cookieToken, formToken;
AntiForgery.GetTokens(null, out cookieToken, out formToken);
return $"{cookieToken}:{formToken}";
}
}
public class XsrfTokensValidationAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext actionContext)
{
IEnumerable<string> headerValues;
if (!actionContext.Request.Headers.TryGetValues("X-XSRF-TOKEN", out headerValues))
{
actionContext.Response = new HttpResponseMessage(HttpStatusCode.BadRequest) { ReasonPhrase = "X-XSRF-TOKEN header is missing." };
return;
}
if (headerValues == null)
{
actionContext.Response = new HttpResponseMessage(HttpStatusCode.BadRequest) { ReasonPhrase = "X-XSRF-TOKEN header value is empty." };
return;
}
var xsrfTokensValue = headerValues.FirstOrDefault();
if (string.IsNullOrEmpty(xsrfTokensValue) || !xsrfTokensValue.Contains(":"))
{
actionContext.Response = new HttpResponseMessage(HttpStatusCode.BadRequest) { ReasonPhrase = "X-XSRF-TOKEN header value is null." };
return;
}
var values = xsrfTokensValue.Split(':');
if (values.Length != 2)
{
actionContext.Response = new HttpResponseMessage(HttpStatusCode.BadRequest) { ReasonPhrase = "X-XSRF-TOKEN header value is malformed." };
return;
}
var cookieToken = values[0];
var formToken = values[1];
try
{
AntiForgery.Validate(cookieToken, formToken);
}
catch (HttpAntiForgeryException ex)
{
actionContext.Response = new HttpResponseMessage(HttpStatusCode.BadRequest) { ReasonPhrase = ex.Message };
}
}
}
}
XsrfCookieGeneratorAttribute 创建可由 JavaScript 代码(Angular 代码)读取的 xsrf cookie,XsrfTokensValidationAttribute 进行服务器端验证。
【讨论】: