2016-08-05 81 views
4

我安裝Microsoft.AspNetCore.Antiforgery我的asp.net核心.NET Framework應用程序,添加到配置服務使用防僞使用Ajax或AngularJs

public void ConfigureServices(IServiceCollection services) 
{ 
    // Add framework services. 
    services.AddApplicationInsightsTelemetry(Configuration); 
    services.AddTransient<ISession, JwtSession>(s => JwtSession.Factory()); 
    //services.AddCors(); 
    services.AddAntiforgery(options => options.HeaderName = "X-XSRF-TOKEN"); 
    services.AddMvc(); 
} 

我想在一個控制器來使用它,並做了如下:

[Route("[action]"), Route("")] 
    [HttpGet] 
    public IActionResult Index() 
    { 
     var f = _antiforgery.GetAndStoreTokens(HttpContext); 
     return View(); 
    } 

但不知道如何把鑰匙放到視圖中。

回答

4

我想你想Antiforgery與Ajax場景一起工作。以下是一個例子:

在Startup.cs:

// Angular's default header name for sending the XSRF token. 
services.AddAntiforgery(options => options.HeaderName = "X-XSRF-TOKEN"); 

的過濾器,以生成防僞標記餅乾:

[HttpGet] 
    [GenerateAntiforgeryTokenCookieForAjax] 
    public IActionResult Create() 
    { 
     return View(); 
    } 

    [HttpPost] 
    [ValidateAntiForgeryToken] 
    public async Task<IActionResult> Create(Product product) 
    { 
+0

和Don」:

public class GenerateAntiforgeryTokenCookieForAjaxAttribute : ActionFilterAttribute { public override void OnActionExecuted(ActionExecutedContext context) { var antiforgery = context.HttpContext.RequestServices.GetService<IAntiforgery>(); // We can send the request token as a JavaScript-readable cookie, and Angular will use it by default. var tokens = antiforgery.GetAndStoreTokens(context.HttpContext); context.HttpContext.Response.Cookies.Append( "XSRF-TOKEN", tokens.RequestToken, new CookieOptions() { HttpOnly = false }); } } 

過濾器的使用情況t忘記添加「使用Microsoft.Extensions.DependencyInjection」,否則通用的GetService擴展將不可用。 – Zygimantas