對於ASP.NET Core應用程序,除了提供認證和受權機制來保證服務的安全性,還須要考慮下面的一些安全因素:javascript
ASP.NET Core經過AntiForgeryToken來阻止CSRF攻擊,通常來講,當用戶作表單提交的時候,表單中隱藏的token也會被提交到服務端,與此同時cookie中包含的另外一半token也被提交到服務端,服務端經過合併兩份token來驗證客戶端的數據是否有效。
例如在ASP.NET Core中經過下面的方式渲染表單:css
<form asp-controller="Manage" asp-action="ChangePassword" method="post"> <!-- Form details --> </form>
這樣會生成下面的html,表單會包含一個隱藏的tokenhtml
<form method="post" action="/Manage/ChangePassword"> <!-- Form details --> <input name="__RequestVerificationToken" type="hidden" value="CfDJ8NrAkSldwD9CpLR...LongValueHere!" /> </form>
服務端的代碼經過在對應的action上標記ValidateAntiForgeryToken
來驗證客戶端的請求java
public class ManageController { [HttpPost] [ValidateAntiForgeryToken] public IActionResult ChangePassword() { // ... return View(); } }
是否是每一個POST請求都須要添加這樣的attribute呢?
ASP.NET Core中有Filter的概念,經過添加全局Filter就能幫咱們達到這樣的目的:jquery
public class Startup { public void ConfigureServices(IServiceCollection services) { services.AddMvc(options => { options.Filters.Add(new AutoValidateAntiforgeryTokenAttribute()); }); } }
AutoValidateAntiforgeryTokenAttribute
會自動忽略不須要作CSRF驗證的請求類型,例如HttpGet請求。git
爲了讓服務更加安全,你還能夠強制用戶使用https,你能夠經過配置API網關的方式達到這個目的,也可使用ASP.NET Core自帶的特性。github
使用了RequireHttpsAttribute
以後,http請求將會報錯。web
services.Configure<MvcOptions>(options => { options.Filters.Add(new RequireHttpsAttribute()); });
經過下面的方式強行跳轉到https。瀏覽器
public void Configure(IApplicationBuilder app, IHostingEnvironment env) { app.UseHttpsRedirection(); }
經過https://securityheaders.com/來檢查HTTP Header是否是安全,例以下面的掃描結果:
NWebsec是一個用來作安全相關的ASP.NET Core類庫,針對ASP.NET Core中HTTP Header相關的修復,能夠添加下面的Nuget包:安全
NWebsec.AspNetCore.Middleware
Strict-Transport-Security
:爲了告訴瀏覽器全部的資源都必須使用https,你須要添加這個header:app.UseHsts(hsts => hsts.MaxAge(365));
Redirect validation
: 一旦啓用了這個中間件,只能被Redirect到容許的站點, 不然會觸發RedirectValidationException
app.UseRedirectValidation(opts => { opts.AllowSameHostRedirectsToHttps(); opts.AllowedDestinations("https://www.google.com/accounts/"); });
Referrer-Policy
: 當用戶點擊了瀏覽器上的鏈接,請求報頭中Referrer用來表示鏈接的來源,這個特性也能夠用來作一些數據分析,經過Referrer-Policy能夠控制是否顯示Referrer:app.UseReferrerPolicy(opts => opts.NoReferrer());
Content-Security-Policy
:內容安全策略,這個http header可讓瀏覽器自動禁止外部注入惡意腳本,例以下面的策略將限制全部的腳本只能從同域加載:'Content-Security-Policy': 'script-src \'self\''
下面的腳本引用將會引發瀏覽器報錯:
<script type="text/javascript" src="https://cdn.bootcss.com/jquery/3.3.1/jquery.js"></script>
使用NWebsec配置Content-Security-Policy
:
app.UseCsp(options => options .DefaultSources(s => s.Self()) .ScriptSources(s => s.Self().CustomSources("scripts.nwebsec.com")) .ReportUris(r => r.Uris("/report")));
X-XSS-Protection
: 防XSS攻擊設置app.UseXXssProtection(options => options.EnabledWithBlockMode());
X-Content-Type-Options
: 若是服務器發送響應頭 X-Content-Type-Options: nosniff
,則 script 和 styleSheet 元素會拒絕包含錯誤的 MIME 類型的響應。這是一種安全功能,有助於防止基於 MIME 類型混淆的攻擊。app.UseXContentTypeOptions();
其餘的安全設置參考NWebsec文檔。