From 3177d319f3dfa1c861ad437eba1038c74554d6f5 Mon Sep 17 00:00:00 2001 From: Ryan Nowak Date: Sun, 7 Jun 2015 16:34:01 -0700 Subject: [PATCH 001/296] Add build-template, license, and readme --- .gitattributes | 50 ++++++++++++++++++++++++++++++++++++++++++++++++++ .gitignore | 27 +++++++++++++++++++++++++++ LICENSE.txt | 12 ++++++++++++ NuGet.Config | 7 +++++++ README.md | 6 ++++++ build.cmd | 36 ++++++++++++++++++++++++++++++++++++ build.sh | 38 ++++++++++++++++++++++++++++++++++++++ makefile.shade | 7 +++++++ 8 files changed, 183 insertions(+) create mode 100644 .gitattributes create mode 100644 .gitignore create mode 100644 LICENSE.txt create mode 100644 NuGet.Config create mode 100644 README.md create mode 100644 build.cmd create mode 100644 build.sh create mode 100644 makefile.shade diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000000..bdaa5ba982 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,50 @@ +*.doc diff=astextplain +*.DOC diff=astextplain +*.docx diff=astextplain +*.DOCX diff=astextplain +*.dot diff=astextplain +*.DOT diff=astextplain +*.pdf diff=astextplain +*.PDF diff=astextplain +*.rtf diff=astextplain +*.RTF diff=astextplain + +*.jpg binary +*.png binary +*.gif binary + +*.cs text=auto diff=csharp +*.vb text=auto +*.resx text=auto +*.c text=auto +*.cpp text=auto +*.cxx text=auto +*.h text=auto +*.hxx text=auto +*.py text=auto +*.rb text=auto +*.java text=auto +*.html text=auto +*.htm text=auto +*.css text=auto +*.scss text=auto +*.sass text=auto +*.less text=auto +*.js text=auto +*.lisp text=auto +*.clj text=auto +*.sql text=auto +*.php text=auto +*.lua text=auto +*.m text=auto +*.asm text=auto +*.erl text=auto +*.fs text=auto +*.fsx text=auto +*.hs text=auto + +*.csproj text=auto +*.vbproj text=auto +*.fsproj text=auto +*.dbproj text=auto +*.sln text=auto eol=crlf diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000000..c2e1708217 --- /dev/null +++ b/.gitignore @@ -0,0 +1,27 @@ +[Oo]bj/ +[Bb]in/ +TestResults/ +.nuget/ +*.sln.ide/ +_ReSharper.*/ +packages/ +artifacts/ +PublishProfiles/ +*.user +*.suo +*.cache +*.docstates +_ReSharper.* +nuget.exe +project.lock.json +*net45.csproj +*net451.csproj +*k10.csproj +*.psess +*.vsp +*.pidb +*.userprefs +*DS_Store +*.ncrunchsolution +*.*sdf +*.ipch \ No newline at end of file diff --git a/LICENSE.txt b/LICENSE.txt new file mode 100644 index 0000000000..0bdc1962b6 --- /dev/null +++ b/LICENSE.txt @@ -0,0 +1,12 @@ +Copyright (c) .NET Foundation. All rights reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +these files except in compliance with the License. You may obtain a copy of the +License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software distributed +under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR +CONDITIONS OF ANY KIND, either express or implied. See the License for the +specific language governing permissions and limitations under the License. diff --git a/NuGet.Config b/NuGet.Config new file mode 100644 index 0000000000..46c3b3e36c --- /dev/null +++ b/NuGet.Config @@ -0,0 +1,7 @@ + + + + + + + diff --git a/README.md b/README.md new file mode 100644 index 0000000000..2b53179d2d --- /dev/null +++ b/README.md @@ -0,0 +1,6 @@ +Antiforgery +=== + +Antiforgery system for generating secure tokens to prevent Cross-Site Request Forgery attacks. + +This project is part of ASP.NET 5. You can find samples, documentation and getting started instructions for ASP.NET 5 at the [Home](https://github.com/aspnet/home) repo. diff --git a/build.cmd b/build.cmd new file mode 100644 index 0000000000..5a69c96e86 --- /dev/null +++ b/build.cmd @@ -0,0 +1,36 @@ +@echo off +cd %~dp0 + +SETLOCAL +SET CACHED_NUGET=%LocalAppData%\NuGet\NuGet.exe + +IF EXIST %CACHED_NUGET% goto copynuget +echo Downloading latest version of NuGet.exe... +IF NOT EXIST %LocalAppData%\NuGet md %LocalAppData%\NuGet +@powershell -NoProfile -ExecutionPolicy unrestricted -Command "$ProgressPreference = 'SilentlyContinue'; Invoke-WebRequest 'https://www.nuget.org/nuget.exe' -OutFile '%CACHED_NUGET%'" + +:copynuget +IF EXIST .nuget\nuget.exe goto restore +md .nuget +copy %CACHED_NUGET% .nuget\nuget.exe > nul + +:restore +IF EXIST packages\KoreBuild goto run +IF DEFINED BUILDCMD_RELEASE ( + .nuget\NuGet.exe install KoreBuild -version 0.2.1-%BUILDCMD_RELEASE% -ExcludeVersion -o packages -nocache -pre +) ELSE ( + .nuget\NuGet.exe install KoreBuild -ExcludeVersion -o packages -nocache -pre +) +.nuget\NuGet.exe install Sake -version 0.2 -o packages -ExcludeVersion + +IF "%SKIP_DNX_INSTALL%"=="1" goto run +IF DEFINED BUILDCMD_RELEASE ( + CALL packages\KoreBuild\build\dnvm install 1.0.0-%BUILDCMD_RELEASE% -runtime CLR -arch x86 -a default +) ELSE ( + CALL packages\KoreBuild\build\dnvm upgrade -runtime CLR -arch x86 +) +CALL packages\KoreBuild\build\dnvm install default -runtime CoreCLR -arch x86 + +:run +CALL packages\KoreBuild\build\dnvm use default -runtime CLR -arch x86 +packages\Sake\tools\Sake.exe -I packages\KoreBuild\build -f makefile.shade %* diff --git a/build.sh b/build.sh new file mode 100644 index 0000000000..c8cc2a72e1 --- /dev/null +++ b/build.sh @@ -0,0 +1,38 @@ +#!/bin/bash + +if test `uname` = Darwin; then + cachedir=~/Library/Caches/KBuild +else + if [ -z $XDG_DATA_HOME ]; then + cachedir=$HOME/.local/share + else + cachedir=$XDG_DATA_HOME; + fi +fi +mkdir -p $cachedir + +url=https://www.nuget.org/nuget.exe + +if test ! -f $cachedir/nuget.exe; then + wget -O $cachedir/nuget.exe $url 2>/dev/null || curl -o $cachedir/nuget.exe --location $url /dev/null +fi + +if test ! -e .nuget; then + mkdir .nuget + cp $cachedir/nuget.exe .nuget/nuget.exe +fi + +if test ! -d packages/KoreBuild; then + mono .nuget/nuget.exe install KoreBuild -ExcludeVersion -o packages -nocache -pre + mono .nuget/nuget.exe install Sake -version 0.2 -o packages -ExcludeVersion +fi + +if ! type dnvm > /dev/null 2>&1; then + source packages/KoreBuild/build/dnvm.sh +fi + +if ! type dnx > /dev/null 2>&1; then + dnvm upgrade +fi + +mono packages/Sake/tools/Sake.exe -I packages/KoreBuild/build -f makefile.shade "$@" diff --git a/makefile.shade b/makefile.shade new file mode 100644 index 0000000000..562494d144 --- /dev/null +++ b/makefile.shade @@ -0,0 +1,7 @@ + +var VERSION='0.1' +var FULL_VERSION='0.1' +var AUTHORS='Microsoft Open Technologies, Inc.' + +use-standard-lifecycle +k-standard-goals From 2c3544c348606fa756b1b8382b6f16d7f5f68b7d Mon Sep 17 00:00:00 2001 From: Ryan Nowak Date: Sun, 7 Jun 2015 16:57:21 -0700 Subject: [PATCH 002/296] Add project structure --- Antiforgery.sln | 36 +++++++++++++++++++ global.json | 3 ++ .../Microsoft.AspNet.Antiforgery.xproj | 20 +++++++++++ src/Microsoft.AspNet.Antiforgery/project.json | 23 ++++++++++++ .../Microsoft.AspNet.Antiforgery.Test.xproj | 20 +++++++++++ .../project.json | 14 ++++++++ 6 files changed, 116 insertions(+) create mode 100644 Antiforgery.sln create mode 100644 global.json create mode 100644 src/Microsoft.AspNet.Antiforgery/Microsoft.AspNet.Antiforgery.xproj create mode 100644 src/Microsoft.AspNet.Antiforgery/project.json create mode 100644 test/Microsoft.AspNet.Antiforgery.Test/Microsoft.AspNet.Antiforgery.Test.xproj create mode 100644 test/Microsoft.AspNet.Antiforgery.Test/project.json diff --git a/Antiforgery.sln b/Antiforgery.sln new file mode 100644 index 0000000000..b6b0239866 --- /dev/null +++ b/Antiforgery.sln @@ -0,0 +1,36 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 14 +VisualStudioVersion = 14.0.22808.1 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{71D070C4-B325-48F7-9F25-DD4E91C2BBCA}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "test", "test", "{6EDD8B57-4DE8-4246-A6A3-47ECD92740B4}" +EndProject +Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "Microsoft.AspNet.Antiforgery", "src\Microsoft.AspNet.Antiforgery\Microsoft.AspNet.Antiforgery.xproj", "{46FB03FB-7A44-4106-BDDE-D6F5417544AB}" +EndProject +Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "Microsoft.AspNet.Antiforgery.Test", "test\Microsoft.AspNet.Antiforgery.Test\Microsoft.AspNet.Antiforgery.Test.xproj", "{415E83F8-6002-47E4-AA8E-CD5169C06F28}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {46FB03FB-7A44-4106-BDDE-D6F5417544AB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {46FB03FB-7A44-4106-BDDE-D6F5417544AB}.Debug|Any CPU.Build.0 = Debug|Any CPU + {46FB03FB-7A44-4106-BDDE-D6F5417544AB}.Release|Any CPU.ActiveCfg = Release|Any CPU + {46FB03FB-7A44-4106-BDDE-D6F5417544AB}.Release|Any CPU.Build.0 = Release|Any CPU + {415E83F8-6002-47E4-AA8E-CD5169C06F28}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {415E83F8-6002-47E4-AA8E-CD5169C06F28}.Debug|Any CPU.Build.0 = Debug|Any CPU + {415E83F8-6002-47E4-AA8E-CD5169C06F28}.Release|Any CPU.ActiveCfg = Release|Any CPU + {415E83F8-6002-47E4-AA8E-CD5169C06F28}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(NestedProjects) = preSolution + {46FB03FB-7A44-4106-BDDE-D6F5417544AB} = {71D070C4-B325-48F7-9F25-DD4E91C2BBCA} + {415E83F8-6002-47E4-AA8E-CD5169C06F28} = {6EDD8B57-4DE8-4246-A6A3-47ECD92740B4} + EndGlobalSection +EndGlobal diff --git a/global.json b/global.json new file mode 100644 index 0000000000..983ba0401e --- /dev/null +++ b/global.json @@ -0,0 +1,3 @@ +{ + "projects": ["src"] +} diff --git a/src/Microsoft.AspNet.Antiforgery/Microsoft.AspNet.Antiforgery.xproj b/src/Microsoft.AspNet.Antiforgery/Microsoft.AspNet.Antiforgery.xproj new file mode 100644 index 0000000000..b920ab0e7b --- /dev/null +++ b/src/Microsoft.AspNet.Antiforgery/Microsoft.AspNet.Antiforgery.xproj @@ -0,0 +1,20 @@ + + + + 14.0 + $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion) + + + + + 46fb03fb-7a44-4106-bdde-d6f5417544ab + Microsoft.AspNet.Antiforgery + ..\..\artifacts\obj\$(MSBuildProjectName) + ..\..\artifacts\bin\$(MSBuildProjectName)\ + + + + 2.0 + + + diff --git a/src/Microsoft.AspNet.Antiforgery/project.json b/src/Microsoft.AspNet.Antiforgery/project.json new file mode 100644 index 0000000000..9840dfddec --- /dev/null +++ b/src/Microsoft.AspNet.Antiforgery/project.json @@ -0,0 +1,23 @@ +{ + "version": "1.0.0-*", + "description": "", + "authors": [ "" ], + "tags": [ "" ], + "projectUrl": "", + "licenseUrl": "", + + "dependencies": { + }, + + "frameworks" : { + "dnx451": { }, + "dnxcore50" : { + "dependencies": { + "System.Collections": "4.0.10-beta-22807", + "System.Linq": "4.0.0-beta-22807", + "System.Threading": "4.0.10-beta-22807", + "Microsoft.CSharp": "4.0.0-beta-22807" + } + } + } +} diff --git a/test/Microsoft.AspNet.Antiforgery.Test/Microsoft.AspNet.Antiforgery.Test.xproj b/test/Microsoft.AspNet.Antiforgery.Test/Microsoft.AspNet.Antiforgery.Test.xproj new file mode 100644 index 0000000000..fa6e61dfa1 --- /dev/null +++ b/test/Microsoft.AspNet.Antiforgery.Test/Microsoft.AspNet.Antiforgery.Test.xproj @@ -0,0 +1,20 @@ + + + + 14.0 + $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion) + + + + + 415e83f8-6002-47e4-aa8e-cd5169c06f28 + Microsoft.AspNet.Antiforgery.Test + ..\..\artifacts\obj\$(MSBuildProjectName) + ..\..\artifacts\bin\$(MSBuildProjectName)\ + + + + 2.0 + + + diff --git a/test/Microsoft.AspNet.Antiforgery.Test/project.json b/test/Microsoft.AspNet.Antiforgery.Test/project.json new file mode 100644 index 0000000000..8307de87d5 --- /dev/null +++ b/test/Microsoft.AspNet.Antiforgery.Test/project.json @@ -0,0 +1,14 @@ +{ + "dependencies": { + "Microsoft.AspNet.Antiforgery": "1.0.0-*", + "xunit.runner.aspnet": "2.0.0-aspnet-*" + }, + "commands": { + "run": "xunit.runner.aspnet", + "test": "xunit.runner.aspnet" + }, + "frameworks": { + "dnx451": { }, + "dnxcore50": { } + } +} From 68ee820b5d5916d349b846f58a5301023b24dd99 Mon Sep 17 00:00:00 2001 From: Eilon Lipton Date: Wed, 10 Jun 2015 10:01:46 -0700 Subject: [PATCH 003/296] Create CONTRIBUTING.md --- CONTRIBUTING.md | 4 ++++ 1 file changed, 4 insertions(+) create mode 100644 CONTRIBUTING.md diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000000..64ff041d5c --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,4 @@ +Contributing +====== + +Information on contributing to this repo is in the [Contributing Guide](https://github.com/aspnet/Home/blob/dev/CONTRIBUTING.md) in the Home repo. From 3dc2663c3509a5c3c249e383763c5492338528f9 Mon Sep 17 00:00:00 2001 From: Ryan Nowak Date: Mon, 8 Jun 2015 14:28:39 -0700 Subject: [PATCH 004/296] Code dump of Antiforgery code --- .../Antiforgery.cs | 139 +++++ .../AntiforgeryContext.cs | 13 + .../AntiforgeryContextAccessor.cs | 10 + .../AntiforgeryOptions.cs | 81 +++ .../AntiforgeryToken.cs | 53 ++ .../AntiforgeryTokenProvider.cs | 168 +++++ .../AntiforgeryTokenSerializer.cs | 135 ++++ .../AntiforgeryTokenSet.cs | 42 ++ .../AntiforgeryTokenStore.cs | 79 +++ .../BinaryBlob.cs | 117 ++++ ...efaultAntiforgeryAdditionalDataProvider.cs | 26 + .../DefaultClaimUidExtractor.cs | 82 +++ .../IAntiforgeryAdditionalDataProvider.cs | 39 ++ .../IAntiforgeryContextAccessor.cs | 10 + .../IAntiforgeryTokenGenerator.cs | 22 + .../IAntiforgeryTokenSerializer.cs | 12 + .../IAntiforgeryTokenStore.cs | 16 + .../IAntiforgeryTokenValidator.cs | 23 + .../IClaimUidExtractor.cs | 20 + .../Internal/AntiforgeryWorker.cs | 251 ++++++++ .../Properties/AssemblyInfo.cs | 9 + .../Properties/Resources.Designer.cs | 206 ++++++ .../Resources.resx | 153 +++++ src/Microsoft.AspNet.Antiforgery/project.json | 32 +- .../AntiforgeryTokenSerializerTest.cs | 184 ++++++ .../AntiforgeryTokenStoreTest.cs | 428 +++++++++++++ .../AntiforgeryTokenTest.cs | 132 ++++ .../AntiforgeryWorkerTest.cs | 583 +++++++++++++++++ .../BinaryBlobTest.cs | 129 ++++ .../ClaimUidExtractorTest.cs | 115 ++++ .../Microsoft.AspNet.Antiforgery.Test.xproj | 7 +- .../TokenProviderTest.cs | 588 ++++++++++++++++++ .../project.json | 9 +- 33 files changed, 3897 insertions(+), 16 deletions(-) create mode 100644 src/Microsoft.AspNet.Antiforgery/Antiforgery.cs create mode 100644 src/Microsoft.AspNet.Antiforgery/AntiforgeryContext.cs create mode 100644 src/Microsoft.AspNet.Antiforgery/AntiforgeryContextAccessor.cs create mode 100644 src/Microsoft.AspNet.Antiforgery/AntiforgeryOptions.cs create mode 100644 src/Microsoft.AspNet.Antiforgery/AntiforgeryToken.cs create mode 100644 src/Microsoft.AspNet.Antiforgery/AntiforgeryTokenProvider.cs create mode 100644 src/Microsoft.AspNet.Antiforgery/AntiforgeryTokenSerializer.cs create mode 100644 src/Microsoft.AspNet.Antiforgery/AntiforgeryTokenSet.cs create mode 100644 src/Microsoft.AspNet.Antiforgery/AntiforgeryTokenStore.cs create mode 100644 src/Microsoft.AspNet.Antiforgery/BinaryBlob.cs create mode 100644 src/Microsoft.AspNet.Antiforgery/DefaultAntiforgeryAdditionalDataProvider.cs create mode 100644 src/Microsoft.AspNet.Antiforgery/DefaultClaimUidExtractor.cs create mode 100644 src/Microsoft.AspNet.Antiforgery/IAntiforgeryAdditionalDataProvider.cs create mode 100644 src/Microsoft.AspNet.Antiforgery/IAntiforgeryContextAccessor.cs create mode 100644 src/Microsoft.AspNet.Antiforgery/IAntiforgeryTokenGenerator.cs create mode 100644 src/Microsoft.AspNet.Antiforgery/IAntiforgeryTokenSerializer.cs create mode 100644 src/Microsoft.AspNet.Antiforgery/IAntiforgeryTokenStore.cs create mode 100644 src/Microsoft.AspNet.Antiforgery/IAntiforgeryTokenValidator.cs create mode 100644 src/Microsoft.AspNet.Antiforgery/IClaimUidExtractor.cs create mode 100644 src/Microsoft.AspNet.Antiforgery/Internal/AntiforgeryWorker.cs create mode 100644 src/Microsoft.AspNet.Antiforgery/Properties/AssemblyInfo.cs create mode 100644 src/Microsoft.AspNet.Antiforgery/Properties/Resources.Designer.cs create mode 100644 src/Microsoft.AspNet.Antiforgery/Resources.resx create mode 100644 test/Microsoft.AspNet.Antiforgery.Test/AntiforgeryTokenSerializerTest.cs create mode 100644 test/Microsoft.AspNet.Antiforgery.Test/AntiforgeryTokenStoreTest.cs create mode 100644 test/Microsoft.AspNet.Antiforgery.Test/AntiforgeryTokenTest.cs create mode 100644 test/Microsoft.AspNet.Antiforgery.Test/AntiforgeryWorkerTest.cs create mode 100644 test/Microsoft.AspNet.Antiforgery.Test/BinaryBlobTest.cs create mode 100644 test/Microsoft.AspNet.Antiforgery.Test/ClaimUidExtractorTest.cs create mode 100644 test/Microsoft.AspNet.Antiforgery.Test/TokenProviderTest.cs diff --git a/src/Microsoft.AspNet.Antiforgery/Antiforgery.cs b/src/Microsoft.AspNet.Antiforgery/Antiforgery.cs new file mode 100644 index 0000000000..ab2d2b7c31 --- /dev/null +++ b/src/Microsoft.AspNet.Antiforgery/Antiforgery.cs @@ -0,0 +1,139 @@ +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System; +using System.Linq; +using System.Security.Cryptography; +using System.Text; +using System.Threading.Tasks; +using Microsoft.AspNet.Antiforgery.Internal; +using Microsoft.AspNet.DataProtection; +using Microsoft.AspNet.Http; +using Microsoft.AspNet.WebUtilities; +using Microsoft.Framework.Internal; +using Microsoft.Framework.OptionsModel; +using Microsoft.Framework.WebEncoders; + +namespace Microsoft.AspNet.Antiforgery +{ + /// + /// Provides access to the anti-forgery system, which provides protection against + /// Cross-site Request Forgery (XSRF, also called CSRF) attacks. + /// + public sealed class Antiforgery + { + private static readonly string _purpose = "Microsoft.AspNet.Antiforgery.AntiforgeryToken.v1"; + private readonly AntiforgeryWorker _worker; + + public Antiforgery( + [NotNull] IClaimUidExtractor claimUidExtractor, + [NotNull] IDataProtectionProvider dataProtectionProvider, + [NotNull] IAntiforgeryAdditionalDataProvider additionalDataProvider, + [NotNull] IOptions AntiforgeryOptionsAccessor, + [NotNull] IHtmlEncoder htmlEncoder, + [NotNull] IOptions dataProtectionOptions) + { + var AntiforgeryOptions = AntiforgeryOptionsAccessor.Options; + var applicationId = dataProtectionOptions.Options.ApplicationDiscriminator ?? string.Empty; + AntiforgeryOptions.CookieName = AntiforgeryOptions.CookieName ?? ComputeCookieName(applicationId); + + var serializer = new AntiforgeryTokenSerializer(dataProtectionProvider.CreateProtector(_purpose)); + var tokenStore = new AntiforgeryTokenStore(AntiforgeryOptions, serializer); + var tokenProvider = new AntiforgeryTokenProvider(AntiforgeryOptions, claimUidExtractor, additionalDataProvider); + _worker = new AntiforgeryWorker(serializer, AntiforgeryOptions, tokenStore, tokenProvider, tokenProvider, htmlEncoder); + } + + /// + /// Generates an anti-forgery token for this request. This token can + /// be validated by calling the Validate() method. + /// + /// The HTTP context associated with the current call. + /// An HTML string corresponding to an <input type="hidden"> + /// element. This element should be put inside a <form>. + /// + /// This method has a side effect: + /// A response cookie is set if there is no valid cookie associated with the request. + /// + public string GetHtml([NotNull] HttpContext context) + { + var html = _worker.GetFormInputElement(context); + return html; + } + + /// + /// Generates an anti-forgery token pair (cookie and form token) for this request. + /// This method is similar to GetHtml(HttpContext context), but this method gives the caller control + /// over how to persist the returned values. To validate these tokens, call the + /// appropriate overload of Validate. + /// + /// The HTTP context associated with the current call. + /// The anti-forgery token - if any - that already existed + /// for this request. May be null. The anti-forgery system will try to reuse this cookie + /// value when generating a matching form token. + /// + /// Unlike the GetHtml(HttpContext context) method, this method has no side effect. The caller + /// is responsible for setting the response cookie and injecting the returned + /// form token as appropriate. + /// + public AntiforgeryTokenSet GetTokens([NotNull] HttpContext context, string oldCookieToken) + { + // Will contain a new cookie value if the old cookie token + // was null or invalid. If this value is non-null when the method completes, the caller + // must persist this value in the form of a response cookie, and the existing cookie value + // should be discarded. If this value is null when the method completes, the existing + // cookie value was valid and needn't be modified. + return _worker.GetTokens(context, oldCookieToken); + } + + /// + /// Validates an anti-forgery token that was supplied for this request. + /// The anti-forgery token may be generated by calling GetHtml(HttpContext context). + /// + /// The HTTP context associated with the current call. + public async Task ValidateAsync([NotNull] HttpContext context) + { + await _worker.ValidateAsync(context); + } + + /// + /// Validates an anti-forgery token pair that was generated by the GetTokens method. + /// + /// The HTTP context associated with the current call. + /// The token that was supplied in the request cookie. + /// The token that was supplied in the request form body. + public void Validate([NotNull] HttpContext context, string cookieToken, string formToken) + { + _worker.Validate(context, cookieToken, formToken); + } + + /// + /// Validates an anti-forgery token pair that was generated by the GetTokens method. + /// + /// The HTTP context associated with the current call. + /// The anti-forgery token pair (cookie and form token) for this request. + /// + public void Validate([NotNull] HttpContext context, AntiforgeryTokenSet AntiforgeryTokenSet) + { + Validate(context, AntiforgeryTokenSet.CookieToken, AntiforgeryTokenSet.FormToken); + } + + /// + /// Generates and sets an anti-forgery cookie if one is not available or not valid. Also sets response headers. + /// + /// The HTTP context associated with the current call. + public void SetCookieTokenAndHeader([NotNull] HttpContext context) + { + _worker.SetCookieTokenAndHeader(context); + } + + private string ComputeCookieName(string applicationId) + { + using (var sha256 = SHA256.Create()) + { + var hash = sha256.ComputeHash(Encoding.UTF8.GetBytes(applicationId)); + var subHash = hash.Take(8).ToArray(); + return WebEncoders.Base64UrlEncode(subHash); + } + } + } +} \ No newline at end of file diff --git a/src/Microsoft.AspNet.Antiforgery/AntiforgeryContext.cs b/src/Microsoft.AspNet.Antiforgery/AntiforgeryContext.cs new file mode 100644 index 0000000000..ded759255c --- /dev/null +++ b/src/Microsoft.AspNet.Antiforgery/AntiforgeryContext.cs @@ -0,0 +1,13 @@ +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +namespace Microsoft.AspNet.Antiforgery +{ + /// + /// Used as a per request state. + /// + public class AntiforgeryContext + { + public AntiforgeryToken CookieToken { get; set; } + } +} \ No newline at end of file diff --git a/src/Microsoft.AspNet.Antiforgery/AntiforgeryContextAccessor.cs b/src/Microsoft.AspNet.Antiforgery/AntiforgeryContextAccessor.cs new file mode 100644 index 0000000000..3a2806a10f --- /dev/null +++ b/src/Microsoft.AspNet.Antiforgery/AntiforgeryContextAccessor.cs @@ -0,0 +1,10 @@ +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +namespace Microsoft.AspNet.Antiforgery +{ + public class AntiforgeryContextAccessor : IAntiforgeryContextAccessor + { + public AntiforgeryContext Value { get; set; } + } +} diff --git a/src/Microsoft.AspNet.Antiforgery/AntiforgeryOptions.cs b/src/Microsoft.AspNet.Antiforgery/AntiforgeryOptions.cs new file mode 100644 index 0000000000..50f8f42b51 --- /dev/null +++ b/src/Microsoft.AspNet.Antiforgery/AntiforgeryOptions.cs @@ -0,0 +1,81 @@ +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System; +using Microsoft.Framework.Internal; + +namespace Microsoft.AspNet.Antiforgery +{ + /// + /// Provides programmatic configuration for the anti-forgery token system. + /// + public class AntiforgeryOptions + { + private const string AntiforgeryTokenFieldName = "__RequestVerificationToken"; + + private string _cookieName; + private string _formFieldName = AntiforgeryTokenFieldName; + + /// + /// Specifies the name of the cookie that is used by the anti-forgery + /// system. + /// + /// + /// If an explicit name is not provided, the system will automatically + /// generate a name. + /// + public string CookieName + { + get + { + return _cookieName; + } + + [param: NotNull] + set + { + _cookieName = value; + } + } + + /// + /// Specifies the name of the anti-forgery token field that is used by the anti-forgery system. + /// + public string FormFieldName + { + get + { + return _formFieldName; + } + + [param: NotNull] + set + { + _formFieldName = value; + } + } + + /// + /// Specifies whether SSL is required for the anti-forgery system + /// to operate. If this setting is 'true' and a non-SSL request + /// comes into the system, all anti-forgery APIs will fail. + /// + public bool RequireSSL + { + get; + set; + } + + /// + /// Specifies whether to suppress the generation of X-Frame-Options header + /// which is used to prevent ClickJacking. By default, the X-Frame-Options + /// header is generated with the value SAMEORIGIN. If this setting is 'true', + /// the X-Frame-Options header will not be generated for the response. + /// + public bool SuppressXFrameOptionsHeader + { + get; + set; + } + } +} \ No newline at end of file diff --git a/src/Microsoft.AspNet.Antiforgery/AntiforgeryToken.cs b/src/Microsoft.AspNet.Antiforgery/AntiforgeryToken.cs new file mode 100644 index 0000000000..61f9665c26 --- /dev/null +++ b/src/Microsoft.AspNet.Antiforgery/AntiforgeryToken.cs @@ -0,0 +1,53 @@ +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +namespace Microsoft.AspNet.Antiforgery +{ + public sealed class AntiforgeryToken + { + internal const int SecurityTokenBitLength = 128; + internal const int ClaimUidBitLength = 256; + + private string _additionalData = string.Empty; + private string _username = string.Empty; + private BinaryBlob _securityToken; + + public string AdditionalData + { + get { return _additionalData; } + set + { + _additionalData = value ?? string.Empty; + } + } + + public BinaryBlob ClaimUid { get; set; } + + public bool IsSessionToken { get; set; } + + public BinaryBlob SecurityToken + { + get + { + if (_securityToken == null) + { + _securityToken = new BinaryBlob(SecurityTokenBitLength); + } + return _securityToken; + } + set + { + _securityToken = value; + } + } + + public string Username + { + get { return _username; } + set + { + _username = value ?? string.Empty; + } + } + } +} \ No newline at end of file diff --git a/src/Microsoft.AspNet.Antiforgery/AntiforgeryTokenProvider.cs b/src/Microsoft.AspNet.Antiforgery/AntiforgeryTokenProvider.cs new file mode 100644 index 0000000000..cdb02b986f --- /dev/null +++ b/src/Microsoft.AspNet.Antiforgery/AntiforgeryTokenProvider.cs @@ -0,0 +1,168 @@ +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System; +using System.Diagnostics; +using System.Security.Claims; +using Microsoft.AspNet.Http; + +namespace Microsoft.AspNet.Antiforgery +{ + public sealed class AntiforgeryTokenProvider : IAntiforgeryTokenValidator, IAntiforgeryTokenGenerator + { + private readonly IClaimUidExtractor _claimUidExtractor; + private readonly AntiforgeryOptions _config; + private readonly IAntiforgeryAdditionalDataProvider _additionalDataProvider; + + internal AntiforgeryTokenProvider( + AntiforgeryOptions config, + IClaimUidExtractor claimUidExtractor, + IAntiforgeryAdditionalDataProvider additionalDataProvider) + { + _config = config; + _claimUidExtractor = claimUidExtractor; + _additionalDataProvider = additionalDataProvider; + } + + public AntiforgeryToken GenerateCookieToken() + { + return new AntiforgeryToken() + { + // SecurityToken will be populated automatically. + IsSessionToken = true + }; + } + + public AntiforgeryToken GenerateFormToken(HttpContext httpContext, + ClaimsIdentity identity, + AntiforgeryToken cookieToken) + { + Debug.Assert(IsCookieTokenValid(cookieToken)); + + var formToken = new AntiforgeryToken() + { + SecurityToken = cookieToken.SecurityToken, + IsSessionToken = false + }; + + var isIdentityAuthenticated = false; + + // populate Username and ClaimUid + if (identity != null && identity.IsAuthenticated) + { + isIdentityAuthenticated = true; + formToken.ClaimUid = GetClaimUidBlob(_claimUidExtractor.ExtractClaimUid(identity)); + if (formToken.ClaimUid == null) + { + formToken.Username = identity.Name; + } + } + + // populate AdditionalData + if (_additionalDataProvider != null) + { + formToken.AdditionalData = _additionalDataProvider.GetAdditionalData(httpContext); + } + + if (isIdentityAuthenticated + && string.IsNullOrEmpty(formToken.Username) + && formToken.ClaimUid == null + && string.IsNullOrEmpty(formToken.AdditionalData)) + { + // Application says user is authenticated, but we have no identifier for the user. + throw new InvalidOperationException( + Resources.FormatAntiforgeryTokenValidator_AuthenticatedUserWithoutUsername(identity.GetType())); + } + + return formToken; + } + + public bool IsCookieTokenValid(AntiforgeryToken cookieToken) + { + return (cookieToken != null && cookieToken.IsSessionToken); + } + + public void ValidateTokens( + HttpContext httpContext, + ClaimsIdentity identity, + AntiforgeryToken sessionToken, + AntiforgeryToken fieldToken) + { + // Were the tokens even present at all? + if (sessionToken == null) + { + throw new InvalidOperationException( + Resources.FormatAntiforgeryToken_CookieMissing(_config.CookieName)); + } + if (fieldToken == null) + { + throw new InvalidOperationException( + Resources.FormatAntiforgeryToken_FormFieldMissing(_config.FormFieldName)); + } + + // Do the tokens have the correct format? + if (!sessionToken.IsSessionToken || fieldToken.IsSessionToken) + { + throw new InvalidOperationException( + Resources.FormatAntiforgeryToken_TokensSwapped(_config.CookieName, _config.FormFieldName)); + } + + // Are the security tokens embedded in each incoming token identical? + if (!Equals(sessionToken.SecurityToken, fieldToken.SecurityToken)) + { + throw new InvalidOperationException(Resources.AntiforgeryToken_SecurityTokenMismatch); + } + + // Is the incoming token meant for the current user? + var currentUsername = string.Empty; + BinaryBlob currentClaimUid = null; + + if (identity != null && identity.IsAuthenticated) + { + currentClaimUid = GetClaimUidBlob(_claimUidExtractor.ExtractClaimUid(identity)); + if (currentClaimUid == null) + { + currentUsername = identity.Name ?? string.Empty; + } + } + + // OpenID and other similar authentication schemes use URIs for the username. + // These should be treated as case-sensitive. + var useCaseSensitiveUsernameComparison = + currentUsername.StartsWith("http://", StringComparison.OrdinalIgnoreCase) || + currentUsername.StartsWith("https://", StringComparison.OrdinalIgnoreCase); + + if (!string.Equals(fieldToken.Username, + currentUsername, + (useCaseSensitiveUsernameComparison) ? + StringComparison.Ordinal : + StringComparison.OrdinalIgnoreCase)) + { + throw new InvalidOperationException( + Resources.FormatAntiforgeryToken_UsernameMismatch(fieldToken.Username, currentUsername)); + } + + if (!Equals(fieldToken.ClaimUid, currentClaimUid)) + { + throw new InvalidOperationException(Resources.AntiforgeryToken_ClaimUidMismatch); + } + + // Is the AdditionalData valid? + if (_additionalDataProvider != null && + !_additionalDataProvider.ValidateAdditionalData(httpContext, fieldToken.AdditionalData)) + { + throw new InvalidOperationException(Resources.AntiforgeryToken_AdditionalDataCheckFailed); + } + } + + private static BinaryBlob GetClaimUidBlob(string base64ClaimUid) + { + if (base64ClaimUid == null) + { + return null; + } + + return new BinaryBlob(256, Convert.FromBase64String(base64ClaimUid)); + } + } +} \ No newline at end of file diff --git a/src/Microsoft.AspNet.Antiforgery/AntiforgeryTokenSerializer.cs b/src/Microsoft.AspNet.Antiforgery/AntiforgeryTokenSerializer.cs new file mode 100644 index 0000000000..9022f77b13 --- /dev/null +++ b/src/Microsoft.AspNet.Antiforgery/AntiforgeryTokenSerializer.cs @@ -0,0 +1,135 @@ +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System; +using System.IO; +using Microsoft.AspNet.DataProtection; +using Microsoft.AspNet.WebUtilities; +using Microsoft.Framework.Internal; + +namespace Microsoft.AspNet.Antiforgery +{ + public sealed class AntiforgeryTokenSerializer : IAntiforgeryTokenSerializer + { + private readonly IDataProtector _cryptoSystem; + private const byte TokenVersion = 0x01; + + public AntiforgeryTokenSerializer([NotNull] IDataProtector cryptoSystem) + { + _cryptoSystem = cryptoSystem; + } + + public AntiforgeryToken Deserialize(string serializedToken) + { + Exception innerException = null; + try + { + var tokenBytes = WebEncoders.Base64UrlDecode(serializedToken); + using (var stream = new MemoryStream(_cryptoSystem.Unprotect(tokenBytes))) + { + using (var reader = new BinaryReader(stream)) + { + var token = DeserializeImpl(reader); + if (token != null) + { + return token; + } + } + } + } + catch (Exception ex) + { + // swallow all exceptions - homogenize error if something went wrong + innerException = ex; + } + + // if we reached this point, something went wrong deserializing + throw new InvalidOperationException(Resources.AntiforgeryToken_DeserializationFailed, innerException); + } + + /* The serialized format of the anti-XSRF token is as follows: + * Version: 1 byte integer + * SecurityToken: 16 byte binary blob + * IsSessionToken: 1 byte Boolean + * [if IsSessionToken != true] + * +- IsClaimsBased: 1 byte Boolean + * | [if IsClaimsBased = true] + * | `- ClaimUid: 32 byte binary blob + * | [if IsClaimsBased = false] + * | `- Username: UTF-8 string with 7-bit integer length prefix + * `- AdditionalData: UTF-8 string with 7-bit integer length prefix + */ + private static AntiforgeryToken DeserializeImpl(BinaryReader reader) + { + // we can only consume tokens of the same serialized version that we generate + var embeddedVersion = reader.ReadByte(); + if (embeddedVersion != TokenVersion) + { + return null; + } + + var deserializedToken = new AntiforgeryToken(); + var securityTokenBytes = reader.ReadBytes(AntiforgeryToken.SecurityTokenBitLength / 8); + deserializedToken.SecurityToken = + new BinaryBlob(AntiforgeryToken.SecurityTokenBitLength, securityTokenBytes); + deserializedToken.IsSessionToken = reader.ReadBoolean(); + + if (!deserializedToken.IsSessionToken) + { + var isClaimsBased = reader.ReadBoolean(); + if (isClaimsBased) + { + var claimUidBytes = reader.ReadBytes(AntiforgeryToken.ClaimUidBitLength / 8); + deserializedToken.ClaimUid = new BinaryBlob(AntiforgeryToken.ClaimUidBitLength, claimUidBytes); + } + else + { + deserializedToken.Username = reader.ReadString(); + } + + deserializedToken.AdditionalData = reader.ReadString(); + } + + // if there's still unconsumed data in the stream, fail + if (reader.BaseStream.ReadByte() != -1) + { + return null; + } + + // success + return deserializedToken; + } + + public string Serialize([NotNull] AntiforgeryToken token) + { + using (var stream = new MemoryStream()) + { + using (var writer = new BinaryWriter(stream)) + { + writer.Write(TokenVersion); + writer.Write(token.SecurityToken.GetData()); + writer.Write(token.IsSessionToken); + + if (!token.IsSessionToken) + { + if (token.ClaimUid != null) + { + writer.Write(true /* isClaimsBased */); + writer.Write(token.ClaimUid.GetData()); + } + else + { + writer.Write(false /* isClaimsBased */); + writer.Write(token.Username); + } + + writer.Write(token.AdditionalData); + } + + writer.Flush(); + return WebEncoders.Base64UrlEncode(_cryptoSystem.Protect(stream.ToArray())); + } + } + } + } +} \ No newline at end of file diff --git a/src/Microsoft.AspNet.Antiforgery/AntiforgeryTokenSet.cs b/src/Microsoft.AspNet.Antiforgery/AntiforgeryTokenSet.cs new file mode 100644 index 0000000000..c18e15dd4f --- /dev/null +++ b/src/Microsoft.AspNet.Antiforgery/AntiforgeryTokenSet.cs @@ -0,0 +1,42 @@ +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System; + +namespace Microsoft.AspNet.Antiforgery +{ + /// + /// The anti-forgery token pair (cookie and form token) for a request. + /// + public class AntiforgeryTokenSet + { + /// + /// Creates the anti-forgery token pair (cookie and form token) for a request. + /// + /// The token that is supplied in the request form body. + /// The token that is supplied in the request cookie. + public AntiforgeryTokenSet(string formToken, string cookieToken) + { + if (string.IsNullOrEmpty(formToken)) + { + throw new ArgumentException(Resources.ArgumentCannotBeNullOrEmpty, nameof(formToken)); + } + + FormToken = formToken; + + // Cookie Token is allowed to be null in the case when the old cookie is valid + // and there is no new cookieToken generated. + CookieToken = cookieToken; + } + + /// + /// The token that is supplied in the request form body. + /// + public string FormToken { get; private set; } + + /// The cookie token is allowed to be null. + /// This would be the case when the old cookie token is still valid. + /// In such cases a call to GetTokens would return a token set with null cookie token. + public string CookieToken { get; private set; } + } +} \ No newline at end of file diff --git a/src/Microsoft.AspNet.Antiforgery/AntiforgeryTokenStore.cs b/src/Microsoft.AspNet.Antiforgery/AntiforgeryTokenStore.cs new file mode 100644 index 0000000000..e288c1c786 --- /dev/null +++ b/src/Microsoft.AspNet.Antiforgery/AntiforgeryTokenStore.cs @@ -0,0 +1,79 @@ +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System.Diagnostics; +using System.Threading.Tasks; +using Microsoft.AspNet.Http; +using Microsoft.Framework.DependencyInjection; +using Microsoft.Framework.Internal; + +namespace Microsoft.AspNet.Antiforgery +{ + // Saves anti-XSRF tokens split between HttpRequest.Cookies and HttpRequest.Form + public sealed class AntiforgeryTokenStore : IAntiforgeryTokenStore + { + private readonly AntiforgeryOptions _config; + private readonly IAntiforgeryTokenSerializer _serializer; + + public AntiforgeryTokenStore([NotNull] AntiforgeryOptions config, + [NotNull] IAntiforgeryTokenSerializer serializer) + { + _config = config; + _serializer = serializer; + } + + public AntiforgeryToken GetCookieToken(HttpContext httpContext) + { + var contextAccessor = + httpContext.RequestServices.GetRequiredService(); + if (contextAccessor.Value != null) + { + return contextAccessor.Value.CookieToken; + } + + var requestCookie = httpContext.Request.Cookies[_config.CookieName]; + if (string.IsNullOrEmpty(requestCookie)) + { + // unable to find the cookie. + return null; + } + + return _serializer.Deserialize(requestCookie); + } + + public async Task GetFormTokenAsync(HttpContext httpContext) + { + var form = await httpContext.Request.ReadFormAsync(); + var value = form[_config.FormFieldName]; + if (string.IsNullOrEmpty(value)) + { + // did not exist + return null; + } + + return _serializer.Deserialize(value); + } + + public void SaveCookieToken(HttpContext httpContext, AntiforgeryToken token) + { + // Add the cookie to the request based context. + // This is useful if the cookie needs to be reloaded in the context of the same request. + var contextAccessor = + httpContext.RequestServices.GetRequiredService(); + Debug.Assert(contextAccessor.Value == null, "AntiforgeryContext should be set only once per request."); + contextAccessor.Value = new AntiforgeryContext() { CookieToken = token }; + + var serializedToken = _serializer.Serialize(token); + var options = new CookieOptions() { HttpOnly = true }; + + // Note: don't use "newCookie.Secure = _config.RequireSSL;" since the default + // value of newCookie.Secure is poulated out of band. + if (_config.RequireSSL) + { + options.Secure = true; + } + + httpContext.Response.Cookies.Append(_config.CookieName, serializedToken, options); + } + } +} \ No newline at end of file diff --git a/src/Microsoft.AspNet.Antiforgery/BinaryBlob.cs b/src/Microsoft.AspNet.Antiforgery/BinaryBlob.cs new file mode 100644 index 0000000000..e0faebed0a --- /dev/null +++ b/src/Microsoft.AspNet.Antiforgery/BinaryBlob.cs @@ -0,0 +1,117 @@ +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System; +using System.Diagnostics; +using System.Globalization; +using System.Runtime.CompilerServices; +using System.Security.Cryptography; +using System.Text; + +namespace Microsoft.AspNet.Antiforgery +{ + // Represents a binary blob (token) that contains random data. + // Useful for binary data inside a serialized stream. + [DebuggerDisplay("{DebuggerString}")] + public sealed class BinaryBlob : IEquatable + { + private static readonly RandomNumberGenerator _randomNumberGenerator = RandomNumberGenerator.Create(); + private readonly byte[] _data; + + // Generates a new token using a specified bit length. + public BinaryBlob(int bitLength) + : this(bitLength, GenerateNewToken(bitLength)) + { + } + + // Generates a token using an existing binary value. + public BinaryBlob(int bitLength, byte[] data) + { + if (bitLength < 32 || bitLength % 8 != 0) + { + throw new ArgumentOutOfRangeException("bitLength"); + } + if (data == null || data.Length != bitLength / 8) + { + throw new ArgumentOutOfRangeException("data"); + } + + _data = data; + } + + public int BitLength + { + get + { + return checked(_data.Length * 8); + } + } + + private string DebuggerString + { + get + { + var sb = new StringBuilder("0x", 2 + (_data.Length * 2)); + for (var i = 0; i < _data.Length; i++) + { + sb.AppendFormat(CultureInfo.InvariantCulture, "{0:x2}", _data[i]); + } + return sb.ToString(); + } + } + + public override bool Equals(object obj) + { + return Equals(obj as BinaryBlob); + } + + public bool Equals(BinaryBlob other) + { + if (other == null) + { + return false; + } + + Debug.Assert(this._data.Length == other._data.Length); + return AreByteArraysEqual(this._data, other._data); + } + + public byte[] GetData() + { + return _data; + } + + public override int GetHashCode() + { + // Since data should contain uniformly-distributed entropy, the + // first 32 bits can serve as the hash code. + Debug.Assert(_data != null && _data.Length >= (32 / 8)); + return BitConverter.ToInt32(_data, 0); + } + + private static byte[] GenerateNewToken(int bitLength) + { + var data = new byte[bitLength / 8]; + _randomNumberGenerator.GetBytes(data); + return data; + } + + // Need to mark it with NoInlining and NoOptimization attributes to ensure that the + // operation runs in constant time. + [MethodImplAttribute(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)] + private static bool AreByteArraysEqual(byte[] a, byte[] b) + { + if (a == null || b == null || a.Length != b.Length) + { + return false; + } + + var areEqual = true; + for (var i = 0; i < a.Length; i++) + { + areEqual &= (a[i] == b[i]); + } + return areEqual; + } + } +} \ No newline at end of file diff --git a/src/Microsoft.AspNet.Antiforgery/DefaultAntiforgeryAdditionalDataProvider.cs b/src/Microsoft.AspNet.Antiforgery/DefaultAntiforgeryAdditionalDataProvider.cs new file mode 100644 index 0000000000..2d5967f368 --- /dev/null +++ b/src/Microsoft.AspNet.Antiforgery/DefaultAntiforgeryAdditionalDataProvider.cs @@ -0,0 +1,26 @@ +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using Microsoft.AspNet.Http; + +namespace Microsoft.AspNet.Antiforgery +{ + /// + /// A default implementation. + /// + public class DefaultAntiforgeryAdditionalDataProvider : IAntiforgeryAdditionalDataProvider + { + /// + public virtual string GetAdditionalData(HttpContext context) + { + return string.Empty; + } + + /// + public virtual bool ValidateAdditionalData(HttpContext context, string additionalData) + { + // Default implementation does not understand anything but empty data. + return string.IsNullOrEmpty(additionalData); + } + } +} \ No newline at end of file diff --git a/src/Microsoft.AspNet.Antiforgery/DefaultClaimUidExtractor.cs b/src/Microsoft.AspNet.Antiforgery/DefaultClaimUidExtractor.cs new file mode 100644 index 0000000000..7c033547cc --- /dev/null +++ b/src/Microsoft.AspNet.Antiforgery/DefaultClaimUidExtractor.cs @@ -0,0 +1,82 @@ +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Security.Claims; +using System.Security.Cryptography; + +namespace Microsoft.AspNet.Antiforgery +{ + /// + /// Default implementation of . + /// + public class DefaultClaimUidExtractor : IClaimUidExtractor + { + /// + public string ExtractClaimUid(ClaimsIdentity claimsIdentity) + { + if (claimsIdentity == null || !claimsIdentity.IsAuthenticated) + { + // Skip anonymous users + return null; + } + + var uniqueIdentifierParameters = GetUniqueIdentifierParameters(claimsIdentity); + var claimUidBytes = ComputeSHA256(uniqueIdentifierParameters); + return Convert.ToBase64String(claimUidBytes); + } + + // Internal for testing + internal static IEnumerable GetUniqueIdentifierParameters(ClaimsIdentity claimsIdentity) + { + var nameIdentifierClaim = claimsIdentity.FindFirst(claim => + String.Equals(ClaimTypes.NameIdentifier, + claim.Type, StringComparison.Ordinal)); + if (nameIdentifierClaim != null && !string.IsNullOrEmpty(nameIdentifierClaim.Value)) + { + return new string[] + { + ClaimTypes.NameIdentifier, + nameIdentifierClaim.Value + }; + } + + // We do not understand this ClaimsIdentity, fallback on serializing the entire claims Identity. + var claims = claimsIdentity.Claims.ToList(); + claims.Sort((a, b) => string.Compare(a.Type, b.Type, StringComparison.Ordinal)); + var identifierParameters = new List(); + foreach (var claim in claims) + { + identifierParameters.Add(claim.Type); + identifierParameters.Add(claim.Value); + } + + return identifierParameters; + } + + private static byte[] ComputeSHA256(IEnumerable parameters) + { + using (var stream = new MemoryStream()) + { + using (var writer = new BinaryWriter(stream)) + { + foreach (string parameter in parameters) + { + writer.Write(parameter); // also writes the length as a prefix; unambiguous + } + + writer.Flush(); + + using (var sha256 = SHA256.Create()) + { + var bytes = sha256.ComputeHash(stream.ToArray(), 0, checked((int)stream.Length)); + return bytes; + } + } + } + } + } +} \ No newline at end of file diff --git a/src/Microsoft.AspNet.Antiforgery/IAntiforgeryAdditionalDataProvider.cs b/src/Microsoft.AspNet.Antiforgery/IAntiforgeryAdditionalDataProvider.cs new file mode 100644 index 0000000000..fb609768bc --- /dev/null +++ b/src/Microsoft.AspNet.Antiforgery/IAntiforgeryAdditionalDataProvider.cs @@ -0,0 +1,39 @@ +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using Microsoft.AspNet.Http; + +namespace Microsoft.AspNet.Antiforgery +{ + /// + /// Allows providing or validating additional custom data for anti-forgery tokens. + /// For example, the developer could use this to supply a nonce when the token is + /// generated, then he could validate the nonce when the token is validated. + /// + /// + /// The anti-forgery system already embeds the client's username within the + /// generated tokens. This interface provides and consumes supplemental + /// data. If an incoming anti-forgery token contains supplemental data but no + /// additional data provider is configured, the supplemental data will not be + /// validated. + /// + public interface IAntiforgeryAdditionalDataProvider + { + /// + /// Provides additional data to be stored for the anti-forgery tokens generated + /// during this request. + /// + /// Information about the current request. + /// Supplemental data to embed within the anti-forgery token. + string GetAdditionalData(HttpContext context); + + /// + /// Validates additional data that was embedded inside an incoming anti-forgery + /// token. + /// + /// Information about the current request. + /// Supplemental data that was embedded within the token. + /// True if the data is valid; false if the data is invalid. + bool ValidateAdditionalData(HttpContext context, string additionalData); + } +} \ No newline at end of file diff --git a/src/Microsoft.AspNet.Antiforgery/IAntiforgeryContextAccessor.cs b/src/Microsoft.AspNet.Antiforgery/IAntiforgeryContextAccessor.cs new file mode 100644 index 0000000000..ac2c5e023f --- /dev/null +++ b/src/Microsoft.AspNet.Antiforgery/IAntiforgeryContextAccessor.cs @@ -0,0 +1,10 @@ +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +namespace Microsoft.AspNet.Antiforgery +{ + public interface IAntiforgeryContextAccessor + { + AntiforgeryContext Value { get; set; } + } +} diff --git a/src/Microsoft.AspNet.Antiforgery/IAntiforgeryTokenGenerator.cs b/src/Microsoft.AspNet.Antiforgery/IAntiforgeryTokenGenerator.cs new file mode 100644 index 0000000000..87d936dec3 --- /dev/null +++ b/src/Microsoft.AspNet.Antiforgery/IAntiforgeryTokenGenerator.cs @@ -0,0 +1,22 @@ +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System.Security.Claims; +using Microsoft.AspNet.Http; + +namespace Microsoft.AspNet.Antiforgery +{ + // Provides configuration information about the anti-forgery system. + public interface IAntiforgeryTokenGenerator + { + // Generates a new random cookie token. + AntiforgeryToken GenerateCookieToken(); + + // Given a cookie token, generates a corresponding form token. + // The incoming cookie token must be valid. + AntiforgeryToken GenerateFormToken( + HttpContext httpContext, + ClaimsIdentity identity, + AntiforgeryToken cookieToken); + } +} \ No newline at end of file diff --git a/src/Microsoft.AspNet.Antiforgery/IAntiforgeryTokenSerializer.cs b/src/Microsoft.AspNet.Antiforgery/IAntiforgeryTokenSerializer.cs new file mode 100644 index 0000000000..4ba30c5591 --- /dev/null +++ b/src/Microsoft.AspNet.Antiforgery/IAntiforgeryTokenSerializer.cs @@ -0,0 +1,12 @@ +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +namespace Microsoft.AspNet.Antiforgery +{ + // Abstracts out the serialization process for an anti-forgery token + public interface IAntiforgeryTokenSerializer + { + AntiforgeryToken Deserialize(string serializedToken); + string Serialize(AntiforgeryToken token); + } +} \ No newline at end of file diff --git a/src/Microsoft.AspNet.Antiforgery/IAntiforgeryTokenStore.cs b/src/Microsoft.AspNet.Antiforgery/IAntiforgeryTokenStore.cs new file mode 100644 index 0000000000..0f2ab27024 --- /dev/null +++ b/src/Microsoft.AspNet.Antiforgery/IAntiforgeryTokenStore.cs @@ -0,0 +1,16 @@ +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System.Threading.Tasks; +using Microsoft.AspNet.Http; + +namespace Microsoft.AspNet.Antiforgery +{ + // Provides an abstraction around how tokens are persisted and retrieved for a request + public interface IAntiforgeryTokenStore + { + AntiforgeryToken GetCookieToken(HttpContext httpContext); + Task GetFormTokenAsync(HttpContext httpContext); + void SaveCookieToken(HttpContext httpContext, AntiforgeryToken token); + } +} \ No newline at end of file diff --git a/src/Microsoft.AspNet.Antiforgery/IAntiforgeryTokenValidator.cs b/src/Microsoft.AspNet.Antiforgery/IAntiforgeryTokenValidator.cs new file mode 100644 index 0000000000..ed75a9de45 --- /dev/null +++ b/src/Microsoft.AspNet.Antiforgery/IAntiforgeryTokenValidator.cs @@ -0,0 +1,23 @@ +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System.Security.Claims; +using Microsoft.AspNet.Http; + +namespace Microsoft.AspNet.Antiforgery +{ + // Provides an abstraction around something that can validate anti-XSRF tokens + public interface IAntiforgeryTokenValidator + { + // Determines whether an existing cookie token is valid (well-formed). + // If it is not, the caller must call GenerateCookieToken() before calling GenerateFormToken(). + bool IsCookieTokenValid(AntiforgeryToken cookieToken); + + // Validates a (cookie, form) token pair. + void ValidateTokens( + HttpContext httpContext, + ClaimsIdentity identity, + AntiforgeryToken cookieToken, + AntiforgeryToken formToken); + } +} \ No newline at end of file diff --git a/src/Microsoft.AspNet.Antiforgery/IClaimUidExtractor.cs b/src/Microsoft.AspNet.Antiforgery/IClaimUidExtractor.cs new file mode 100644 index 0000000000..c7b0af04c9 --- /dev/null +++ b/src/Microsoft.AspNet.Antiforgery/IClaimUidExtractor.cs @@ -0,0 +1,20 @@ +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System.Security.Claims; + +namespace Microsoft.AspNet.Antiforgery +{ + /// + /// This interface can extract unique identifers for a claims-based identity. + /// + public interface IClaimUidExtractor + { + /// + /// Extracts claims identifier. + /// + /// The . + /// The claims identifier. + string ExtractClaimUid(ClaimsIdentity identity); + } +} \ No newline at end of file diff --git a/src/Microsoft.AspNet.Antiforgery/Internal/AntiforgeryWorker.cs b/src/Microsoft.AspNet.Antiforgery/Internal/AntiforgeryWorker.cs new file mode 100644 index 0000000000..ac4dd9e0b8 --- /dev/null +++ b/src/Microsoft.AspNet.Antiforgery/Internal/AntiforgeryWorker.cs @@ -0,0 +1,251 @@ +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System; +using System.Diagnostics; +using System.Security.Claims; +using System.Threading.Tasks; +using Microsoft.AspNet.Http; +using Microsoft.Framework.Internal; +using Microsoft.Framework.WebEncoders; + +namespace Microsoft.AspNet.Antiforgery.Internal +{ + public sealed class AntiforgeryWorker + { + private readonly AntiforgeryOptions _config; + private readonly IAntiforgeryTokenSerializer _serializer; + private readonly IAntiforgeryTokenStore _tokenStore; + private readonly IAntiforgeryTokenValidator _validator; + private readonly IAntiforgeryTokenGenerator _generator; + private readonly IHtmlEncoder _htmlEncoder; + + public AntiforgeryWorker( + [NotNull] IAntiforgeryTokenSerializer serializer, + [NotNull] AntiforgeryOptions config, + [NotNull] IAntiforgeryTokenStore tokenStore, + [NotNull] IAntiforgeryTokenGenerator generator, + [NotNull] IAntiforgeryTokenValidator validator, + [NotNull] IHtmlEncoder htmlEncoder) + { + _serializer = serializer; + _config = config; + _tokenStore = tokenStore; + _generator = generator; + _validator = validator; + _htmlEncoder = htmlEncoder; + } + + private void CheckSSLConfig(HttpContext httpContext) + { + if (_config.RequireSSL && !httpContext.Request.IsHttps) + { + throw new InvalidOperationException(Resources.AntiforgeryWorker_RequireSSL); + } + } + + private AntiforgeryToken DeserializeToken(string serializedToken) + { + return (!string.IsNullOrEmpty(serializedToken)) + ? _serializer.Deserialize(serializedToken) + : null; + } + + private AntiforgeryToken DeserializeTokenDoesNotThrow(string serializedToken) + { + try + { + return DeserializeToken(serializedToken); + } + catch + { + // ignore failures since we'll just generate a new token + return null; + } + } + + private static ClaimsIdentity ExtractIdentity(HttpContext httpContext) + { + if (httpContext != null) + { + var user = httpContext.User; + + if (user != null) + { + // We only support ClaimsIdentity. + return user.Identity as ClaimsIdentity; + } + } + + return null; + } + + private AntiforgeryToken GetCookieTokenDoesNotThrow(HttpContext httpContext) + { + try + { + return _tokenStore.GetCookieToken(httpContext); + } + catch + { + // ignore failures since we'll just generate a new token + return null; + } + } + + // [ ENTRY POINT ] + // Generates an anti-XSRF token pair for the current user. The return + // value is the hidden input form element that should be rendered in + // the
. This method has a side effect: it may set a response + // cookie. + public string GetFormInputElement([NotNull] HttpContext httpContext) + { + CheckSSLConfig(httpContext); + + var cookieToken = GetCookieTokenDoesNotThrow(httpContext); + var tokenSet = GetTokens(httpContext, cookieToken); + cookieToken = tokenSet.CookieToken; + var formToken = tokenSet.FormToken; + + SaveCookieTokenAndHeader(httpContext, cookieToken); + + var inputTag = string.Format( + "", + _htmlEncoder.HtmlEncode(_config.FormFieldName), + _htmlEncoder.HtmlEncode("hidden"), + _htmlEncoder.HtmlEncode(_serializer.Serialize(formToken))); + return inputTag; + } + + // [ ENTRY POINT ] + // Generates a (cookie, form) serialized token pair for the current user. + // The caller may specify an existing cookie value if one exists. If the + // 'new cookie value' out param is non-null, the caller *must* persist + // the new value to cookie storage since the original value was null or + // invalid. This method is side-effect free. + public AntiforgeryTokenSet GetTokens([NotNull] HttpContext httpContext, string cookieToken) + { + CheckSSLConfig(httpContext); + var deSerializedcookieToken = DeserializeTokenDoesNotThrow(cookieToken); + var tokenSet = GetTokens(httpContext, deSerializedcookieToken); + + var serializedCookieToken = Serialize(tokenSet.CookieToken); + var serializedFormToken = Serialize(tokenSet.FormToken); + return new AntiforgeryTokenSet(serializedFormToken, serializedCookieToken); + } + + private AntiforgeryTokenSetInternal GetTokens(HttpContext httpContext, AntiforgeryToken cookieToken) + { + var newCookieToken = ValidateAndGenerateNewCookieToken(cookieToken); + if (newCookieToken != null) + { + cookieToken = newCookieToken; + } + var formToken = _generator.GenerateFormToken( + httpContext, + ExtractIdentity(httpContext), + cookieToken); + + return new AntiforgeryTokenSetInternal() + { + // Note : The new cookie would be null if the old cookie is valid. + CookieToken = newCookieToken, + FormToken = formToken + }; + } + + private string Serialize(AntiforgeryToken token) + { + return (token != null) ? _serializer.Serialize(token) : null; + } + + // [ ENTRY POINT ] + // Given an HttpContext, validates that the anti-XSRF tokens contained + // in the cookies & form are OK for this request. + public async Task ValidateAsync([NotNull] HttpContext httpContext) + { + CheckSSLConfig(httpContext); + + // Extract cookie & form tokens + var cookieToken = _tokenStore.GetCookieToken(httpContext); + var formToken = await _tokenStore.GetFormTokenAsync(httpContext); + + // Validate + _validator.ValidateTokens(httpContext, ExtractIdentity(httpContext), cookieToken, formToken); + } + + // [ ENTRY POINT ] + // Given the serialized string representations of a cookie & form token, + // validates that the pair is OK for this request. + public void Validate([NotNull] HttpContext httpContext, string cookieToken, string formToken) + { + CheckSSLConfig(httpContext); + + // Extract cookie & form tokens + var deserializedCookieToken = DeserializeToken(cookieToken); + var deserializedFormToken = DeserializeToken(formToken); + + // Validate + _validator.ValidateTokens( + httpContext, + ExtractIdentity(httpContext), + deserializedCookieToken, + deserializedFormToken); + } + + + /// + /// Generates and sets an anti-forgery cookie if one is not available or not valid. Also sets response headers. + /// + /// The HTTP context associated with the current call. + public void SetCookieTokenAndHeader([NotNull] HttpContext httpContext) + { + CheckSSLConfig(httpContext); + + var cookieToken = GetCookieTokenDoesNotThrow(httpContext); + cookieToken = ValidateAndGenerateNewCookieToken(cookieToken); + + SaveCookieTokenAndHeader(httpContext, cookieToken); + } + + // This method returns null if oldCookieToken is valid. + private AntiforgeryToken ValidateAndGenerateNewCookieToken(AntiforgeryToken cookieToken) + { + if (!_validator.IsCookieTokenValid(cookieToken)) + { + // Need to make sure we're always operating with a good cookie token. + var newCookieToken = _generator.GenerateCookieToken(); + Debug.Assert(_validator.IsCookieTokenValid(newCookieToken)); + return newCookieToken; + } + + return null; + } + + private void SaveCookieTokenAndHeader( + [NotNull] HttpContext httpContext, + AntiforgeryToken cookieToken) + { + if (cookieToken != null) + { + // Persist the new cookie if it is not null. + _tokenStore.SaveCookieToken(httpContext, cookieToken); + } + + if (!_config.SuppressXFrameOptionsHeader) + { + // Adding X-Frame-Options header to prevent ClickJacking. See + // http://tools.ietf.org/html/draft-ietf-websec-x-frame-options-10 + // for more information. + httpContext.Response.Headers.Set("X-Frame-Options", "SAMEORIGIN"); + } + } + + private class AntiforgeryTokenSetInternal + { + public AntiforgeryToken FormToken { get; set; } + + public AntiforgeryToken CookieToken { get; set; } + } + } +} \ No newline at end of file diff --git a/src/Microsoft.AspNet.Antiforgery/Properties/AssemblyInfo.cs b/src/Microsoft.AspNet.Antiforgery/Properties/AssemblyInfo.cs new file mode 100644 index 0000000000..a91599ff84 --- /dev/null +++ b/src/Microsoft.AspNet.Antiforgery/Properties/AssemblyInfo.cs @@ -0,0 +1,9 @@ +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System.Reflection; +using System.Runtime.CompilerServices; + +[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")] +[assembly: InternalsVisibleTo("Microsoft.AspNet.Antiforgery.Test")] +[assembly: AssemblyMetadata("Serviceable", "True")] diff --git a/src/Microsoft.AspNet.Antiforgery/Properties/Resources.Designer.cs b/src/Microsoft.AspNet.Antiforgery/Properties/Resources.Designer.cs new file mode 100644 index 0000000000..af584b07c3 --- /dev/null +++ b/src/Microsoft.AspNet.Antiforgery/Properties/Resources.Designer.cs @@ -0,0 +1,206 @@ +// +namespace Microsoft.AspNet.Antiforgery +{ + using System.Globalization; + using System.Reflection; + using System.Resources; + + internal static class Resources + { + private static readonly ResourceManager _resourceManager + = new ResourceManager("Microsoft.AspNet.Antiforgery.Resources", typeof(Resources).GetTypeInfo().Assembly); + + /// + /// The provided identity of type '{0}' is marked IsAuthenticated = true but does not have a value for Name. By default, the anti-forgery system requires that all authenticated identities have a unique Name. If it is not possible to provide a unique Name for this identity, consider extending IAdditionalDataProvider by overriding the DefaultAdditionalDataProvider or a custom type that can provide some form of unique identifier for the current user. + /// + internal static string AntiforgeryTokenValidator_AuthenticatedUserWithoutUsername + { + get { return GetString("AntiforgeryTokenValidator_AuthenticatedUserWithoutUsername"); } + } + + /// + /// The provided identity of type '{0}' is marked IsAuthenticated = true but does not have a value for Name. By default, the anti-forgery system requires that all authenticated identities have a unique Name. If it is not possible to provide a unique Name for this identity, consider extending IAdditionalDataProvider by overriding the DefaultAdditionalDataProvider or a custom type that can provide some form of unique identifier for the current user. + /// + internal static string FormatAntiforgeryTokenValidator_AuthenticatedUserWithoutUsername(object p0) + { + return string.Format(CultureInfo.CurrentCulture, GetString("AntiforgeryTokenValidator_AuthenticatedUserWithoutUsername"), p0); + } + + /// + /// The provided anti-forgery token failed a custom data check. + /// + internal static string AntiforgeryToken_AdditionalDataCheckFailed + { + get { return GetString("AntiforgeryToken_AdditionalDataCheckFailed"); } + } + + /// + /// The provided anti-forgery token failed a custom data check. + /// + internal static string FormatAntiforgeryToken_AdditionalDataCheckFailed() + { + return GetString("AntiforgeryToken_AdditionalDataCheckFailed"); + } + + /// + /// The provided anti-forgery token was meant for a different claims-based user than the current user. + /// + internal static string AntiforgeryToken_ClaimUidMismatch + { + get { return GetString("AntiforgeryToken_ClaimUidMismatch"); } + } + + /// + /// The provided anti-forgery token was meant for a different claims-based user than the current user. + /// + internal static string FormatAntiforgeryToken_ClaimUidMismatch() + { + return GetString("AntiforgeryToken_ClaimUidMismatch"); + } + + /// + /// The required anti-forgery cookie "{0}" is not present. + /// + internal static string AntiforgeryToken_CookieMissing + { + get { return GetString("AntiforgeryToken_CookieMissing"); } + } + + /// + /// The required anti-forgery cookie "{0}" is not present. + /// + internal static string FormatAntiforgeryToken_CookieMissing(object p0) + { + return string.Format(CultureInfo.CurrentCulture, GetString("AntiforgeryToken_CookieMissing"), p0); + } + + /// + /// The anti-forgery token could not be decrypted. + /// + internal static string AntiforgeryToken_DeserializationFailed + { + get { return GetString("AntiforgeryToken_DeserializationFailed"); } + } + + /// + /// The anti-forgery token could not be decrypted. + /// + internal static string FormatAntiforgeryToken_DeserializationFailed() + { + return GetString("AntiforgeryToken_DeserializationFailed"); + } + + /// + /// The required anti-forgery form field "{0}" is not present. + /// + internal static string AntiforgeryToken_FormFieldMissing + { + get { return GetString("AntiforgeryToken_FormFieldMissing"); } + } + + /// + /// The required anti-forgery form field "{0}" is not present. + /// + internal static string FormatAntiforgeryToken_FormFieldMissing(object p0) + { + return string.Format(CultureInfo.CurrentCulture, GetString("AntiforgeryToken_FormFieldMissing"), p0); + } + + /// + /// The anti-forgery cookie token and form field token do not match. + /// + internal static string AntiforgeryToken_SecurityTokenMismatch + { + get { return GetString("AntiforgeryToken_SecurityTokenMismatch"); } + } + + /// + /// The anti-forgery cookie token and form field token do not match. + /// + internal static string FormatAntiforgeryToken_SecurityTokenMismatch() + { + return GetString("AntiforgeryToken_SecurityTokenMismatch"); + } + + /// + /// Validation of the provided anti-forgery token failed. The cookie "{0}" and the form field "{1}" were swapped. + /// + internal static string AntiforgeryToken_TokensSwapped + { + get { return GetString("AntiforgeryToken_TokensSwapped"); } + } + + /// + /// Validation of the provided anti-forgery token failed. The cookie "{0}" and the form field "{1}" were swapped. + /// + internal static string FormatAntiforgeryToken_TokensSwapped(object p0, object p1) + { + return string.Format(CultureInfo.CurrentCulture, GetString("AntiforgeryToken_TokensSwapped"), p0, p1); + } + + /// + /// The provided anti-forgery token was meant for user "{0}", but the current user is "{1}". + /// + internal static string AntiforgeryToken_UsernameMismatch + { + get { return GetString("AntiforgeryToken_UsernameMismatch"); } + } + + /// + /// The provided anti-forgery token was meant for user "{0}", but the current user is "{1}". + /// + internal static string FormatAntiforgeryToken_UsernameMismatch(object p0, object p1) + { + return string.Format(CultureInfo.CurrentCulture, GetString("AntiforgeryToken_UsernameMismatch"), p0, p1); + } + + /// + /// The anti-forgery system has the configuration value AntiforgeryOptions.RequireSsl = true, but the current request is not an SSL request. + /// + internal static string AntiforgeryWorker_RequireSSL + { + get { return GetString("AntiforgeryWorker_RequireSSL"); } + } + + /// + /// The anti-forgery system has the configuration value AntiforgeryOptions.RequireSsl = true, but the current request is not an SSL request. + /// + internal static string FormatAntiforgeryWorker_RequireSSL() + { + return GetString("AntiforgeryWorker_RequireSSL"); + } + + /// + /// Value cannot be null or empty. + /// + internal static string ArgumentCannotBeNullOrEmpty + { + get { return GetString("ArgumentCannotBeNullOrEmpty"); } + } + + /// + /// Value cannot be null or empty. + /// + internal static string FormatArgumentCannotBeNullOrEmpty() + { + return GetString("ArgumentCannotBeNullOrEmpty"); + } + + private static string GetString(string name, params string[] formatterNames) + { + var value = _resourceManager.GetString(name); + + System.Diagnostics.Debug.Assert(value != null); + + if (formatterNames != null) + { + for (var i = 0; i < formatterNames.Length; i++) + { + value = value.Replace("{" + formatterNames[i] + "}", "{" + i + "}"); + } + } + + return value; + } + } +} diff --git a/src/Microsoft.AspNet.Antiforgery/Resources.resx b/src/Microsoft.AspNet.Antiforgery/Resources.resx new file mode 100644 index 0000000000..e666385354 --- /dev/null +++ b/src/Microsoft.AspNet.Antiforgery/Resources.resx @@ -0,0 +1,153 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + The provided identity of type '{0}' is marked IsAuthenticated = true but does not have a value for Name. By default, the anti-forgery system requires that all authenticated identities have a unique Name. If it is not possible to provide a unique Name for this identity, consider extending IAdditionalDataProvider by overriding the DefaultAdditionalDataProvider or a custom type that can provide some form of unique identifier for the current user. + + + The provided anti-forgery token failed a custom data check. + + + The provided anti-forgery token was meant for a different claims-based user than the current user. + + + The required anti-forgery cookie "{0}" is not present. + + + The anti-forgery token could not be decrypted. + + + The required anti-forgery form field "{0}" is not present. + + + The anti-forgery cookie token and form field token do not match. + + + Validation of the provided anti-forgery token failed. The cookie "{0}" and the form field "{1}" were swapped. + + + The provided anti-forgery token was meant for user "{0}", but the current user is "{1}". + + + The anti-forgery system has the configuration value AntiforgeryOptions.RequireSsl = true, but the current request is not an SSL request. + + + Value cannot be null or empty. + + \ No newline at end of file diff --git a/src/Microsoft.AspNet.Antiforgery/project.json b/src/Microsoft.AspNet.Antiforgery/project.json index 9840dfddec..10cb97d9a1 100644 --- a/src/Microsoft.AspNet.Antiforgery/project.json +++ b/src/Microsoft.AspNet.Antiforgery/project.json @@ -1,22 +1,30 @@ { - "version": "1.0.0-*", - "description": "", - "authors": [ "" ], - "tags": [ "" ], - "projectUrl": "", - "licenseUrl": "", + "version": "1.0.0-*", + "description": "", + "authors": [ "" ], + "tags": [ "" ], + "projectUrl": "", + "licenseUrl": "", - "dependencies": { - }, + "dependencies": { + "Microsoft.AspNet.DataProtection": "1.0.0-*", + "Microsoft.AspNet.Http.Abstractions": "1.0.0-*", + "Microsoft.AspNet.WebUtilities": "1.0.0-*", + "Microsoft.Framework.DependencyInjection.Abstractions": "1.0.0-*", + "Microsoft.Framework.NotNullAttribute.Sources": { "type": "build", "version": "1.0.0-*" }, + "Microsoft.Framework.OptionsModel": "1.0.0-*" + }, "frameworks" : { "dnx451": { }, "dnxcore50" : { "dependencies": { - "System.Collections": "4.0.10-beta-22807", - "System.Linq": "4.0.0-beta-22807", - "System.Threading": "4.0.10-beta-22807", - "Microsoft.CSharp": "4.0.0-beta-22807" + "System.Collections": "4.0.10-beta-*", + "System.Linq": "4.0.0-beta-*", + "System.Security.Cryptography.RandomNumberGenerator": "4.0.0-beta-*", + "System.Security.Cryptography.Hashing.Algorithms": "4.0.0-beta-*", + "System.Threading": "4.0.10-beta-*", + "Microsoft.CSharp": "4.0.0-beta-*" } } } diff --git a/test/Microsoft.AspNet.Antiforgery.Test/AntiforgeryTokenSerializerTest.cs b/test/Microsoft.AspNet.Antiforgery.Test/AntiforgeryTokenSerializerTest.cs new file mode 100644 index 0000000000..dae7de6a17 --- /dev/null +++ b/test/Microsoft.AspNet.Antiforgery.Test/AntiforgeryTokenSerializerTest.cs @@ -0,0 +1,184 @@ +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +#if DNX451 +using System; +using System.Collections.Generic; +using System.Linq; +using Microsoft.AspNet.DataProtection; +using Moq; +using Xunit; + +namespace Microsoft.AspNet.Antiforgery +{ + public class AntiforgeryTokenSerializerTest + { + private static readonly Mock _dataProtector = GetDataProtector(); + private static readonly BinaryBlob _claimUid = new BinaryBlob(256, new byte[] { 0x6F, 0x16, 0x48, 0xE9, 0x72, 0x49, 0xAA, 0x58, 0x75, 0x40, 0x36, 0xA6, 0x7E, 0x24, 0x8C, 0xF0, 0x44, 0xF0, 0x7E, 0xCF, 0xB0, 0xED, 0x38, 0x75, 0x56, 0xCE, 0x02, 0x9A, 0x4F, 0x9A, 0x40, 0xE0 }); + private static readonly BinaryBlob _securityToken = new BinaryBlob(128, new byte[] { 0x70, 0x5E, 0xED, 0xCC, 0x7D, 0x42, 0xF1, 0xD6, 0xB3, 0xB9, 0x8A, 0x59, 0x36, 0x25, 0xBB, 0x4C }); + private const byte _salt = 0x05; + + [Theory] + [InlineData( + "01" // Version + + "705EEDCC7D42F1D6B3B9" // SecurityToken + // (WRONG!) Stream ends too early + )] + [InlineData( + "01" // Version + + "705EEDCC7D42F1D6B3B98A593625BB4C" // SecurityToken + + "01" // IsSessionToken + + "00" // (WRONG!) Too much data in stream + )] + [InlineData( + "02" // (WRONG! - must be 0x01) Version + + "705EEDCC7D42F1D6B3B98A593625BB4C" // SecurityToken + + "01" // IsSessionToken + )] + [InlineData( + "01" // Version + + "705EEDCC7D42F1D6B3B98A593625BB4C" // SecurityToken + + "00" // IsSessionToken + + "00" // IsClaimsBased + + "05" // Username length header + + "0000" // (WRONG!) Too little data in stream + )] + public void Deserialize_BadToken_Throws(string serializedToken) + { + // Arrange + var testSerializer = new AntiforgeryTokenSerializer(_dataProtector.Object); + + // Act & assert + var ex = Assert.Throws(() => testSerializer.Deserialize(serializedToken)); + Assert.Equal(@"The anti-forgery token could not be decrypted.", ex.Message); + } + + [Fact] + public void Serialize_FieldToken_WithClaimUid_TokenRoundTripSuccessful() + { + // Arrange + var testSerializer = new AntiforgeryTokenSerializer(_dataProtector.Object); + + //"01" // Version + //+ "705EEDCC7D42F1D6B3B98A593625BB4C" // SecurityToken + //+ "00" // IsSessionToken + //+ "01" // IsClaimsBased + //+ "6F1648E97249AA58754036A67E248CF044F07ECFB0ED387556CE029A4F9A40E0" // ClaimUid + //+ "05" // AdditionalData length header + //+ "E282AC3437"; // AdditionalData ("€47") as UTF8 + var token = new AntiforgeryToken() + { + SecurityToken = _securityToken, + IsSessionToken = false, + ClaimUid = _claimUid, + AdditionalData = "€47" + }; + + // Act + var actualSerializedData = testSerializer.Serialize(token); + var deserializedToken = testSerializer.Deserialize(actualSerializedData); + + // Assert + AssertTokensEqual(token, deserializedToken); + _dataProtector.Verify(); + } + + [Fact] + public void Serialize_FieldToken_WithUsername_TokenRoundTripSuccessful() + { + // Arrange + var testSerializer = new AntiforgeryTokenSerializer(_dataProtector.Object); + + //"01" // Version + //+ "705EEDCC7D42F1D6B3B98A593625BB4C" // SecurityToken + //+ "00" // IsSessionToken + //+ "00" // IsClaimsBased + //+ "08" // Username length header + //+ "4AC3A972C3B46D65" // Username ("Jérôme") as UTF8 + //+ "05" // AdditionalData length header + //+ "E282AC3437"; // AdditionalData ("€47") as UTF8 + var token = new AntiforgeryToken() + { + SecurityToken = _securityToken, + IsSessionToken = false, + Username = "Jérôme", + AdditionalData = "€47" + }; + + // Act + var actualSerializedData = testSerializer.Serialize(token); + var deserializedToken = testSerializer.Deserialize(actualSerializedData); + + // Assert + AssertTokensEqual(token, deserializedToken); + _dataProtector.Verify(); + } + + [Fact] + public void Serialize_SessionToken_TokenRoundTripSuccessful() + { + // Arrange + var testSerializer = new AntiforgeryTokenSerializer(_dataProtector.Object); + + //"01" // Version + //+ "705EEDCC7D42F1D6B3B98A593625BB4C" // SecurityToken + //+ "01"; // IsSessionToken + var token = new AntiforgeryToken() + { + SecurityToken = _securityToken, + IsSessionToken = true + }; + + // Act + string actualSerializedData = testSerializer.Serialize(token); + var deserializedToken = testSerializer.Deserialize(actualSerializedData); + + // Assert + AssertTokensEqual(token, deserializedToken); + _dataProtector.Verify(); + } + + private static Mock GetDataProtector() + { + var mockCryptoSystem = new Mock(); + mockCryptoSystem.Setup(o => o.Protect(It.IsAny())) + .Returns(Protect) + .Verifiable(); + mockCryptoSystem.Setup(o => o.Unprotect(It.IsAny())) + .Returns(UnProtect) + .Verifiable(); + return mockCryptoSystem; + } + + private static byte[] Protect(byte[] data) + { + var input = new List(data); + input.Add(_salt); + return input.ToArray(); + } + + private static byte[] UnProtect(byte[] data) + { + var salt = data[data.Length - 1]; + if (salt != _salt) + { + throw new ArgumentException("Invalid salt value in data"); + } + + return data.Take(data.Length - 1).ToArray(); + } + + private static void AssertTokensEqual(AntiforgeryToken expected, AntiforgeryToken actual) + { + Assert.NotNull(expected); + Assert.NotNull(actual); + Assert.Equal(expected.AdditionalData, actual.AdditionalData); + Assert.Equal(expected.ClaimUid, actual.ClaimUid); + Assert.Equal(expected.IsSessionToken, actual.IsSessionToken); + Assert.Equal(expected.SecurityToken, actual.SecurityToken); + Assert.Equal(expected.Username, actual.Username); + } + } +} + +#endif \ No newline at end of file diff --git a/test/Microsoft.AspNet.Antiforgery.Test/AntiforgeryTokenStoreTest.cs b/test/Microsoft.AspNet.Antiforgery.Test/AntiforgeryTokenStoreTest.cs new file mode 100644 index 0000000000..b8e45bc0e1 --- /dev/null +++ b/test/Microsoft.AspNet.Antiforgery.Test/AntiforgeryTokenStoreTest.cs @@ -0,0 +1,428 @@ +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +#if DNX451 +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.AspNet.Http; +using Microsoft.Framework.DependencyInjection; +using Moq; +using Xunit; + +namespace Microsoft.AspNet.Antiforgery +{ + public class AntiforgeryTokenStoreTest + { + private readonly string _cookieName = "cookie-name"; + + [Fact] + public void GetCookieToken_CookieDoesNotExist_ReturnsNull() + { + // Arrange + var requestCookies = new Mock(); + requestCookies + .Setup(o => o.Get(It.IsAny())) + .Returns(string.Empty); + var mockHttpContext = new Mock(); + mockHttpContext + .Setup(o => o.Request.Cookies) + .Returns(requestCookies.Object); + var contextAccessor = new AntiforgeryContextAccessor(); + mockHttpContext.SetupGet(o => o.RequestServices) + .Returns(GetServiceProvider(contextAccessor)); + var config = new AntiforgeryOptions() + { + CookieName = _cookieName + }; + + var tokenStore = new AntiforgeryTokenStore( + config: config, + serializer: null); + + // Act + var token = tokenStore.GetCookieToken(mockHttpContext.Object); + + // Assert + Assert.Null(token); + } + + [Fact] + public void GetCookieToken_CookieIsMissingInRequest_LooksUpCookieInAntiforgeryContext() + { + // Arrange + var requestCookies = new Mock(); + requestCookies + .Setup(o => o.Get(It.IsAny())) + .Returns(string.Empty); + var mockHttpContext = new Mock(); + mockHttpContext + .Setup(o => o.Request.Cookies) + .Returns(requestCookies.Object); + var contextAccessor = new AntiforgeryContextAccessor(); + mockHttpContext.SetupGet(o => o.RequestServices) + .Returns(GetServiceProvider(contextAccessor)); + + // add a cookie explicitly. + var cookie = new AntiforgeryToken(); + contextAccessor.Value = new AntiforgeryContext() { CookieToken = cookie }; + var config = new AntiforgeryOptions() + { + CookieName = _cookieName + }; + + var tokenStore = new AntiforgeryTokenStore( + config: config, + serializer: null); + + // Act + var token = tokenStore.GetCookieToken(mockHttpContext.Object); + + // Assert + Assert.Equal(cookie, token); + } + + [Fact] + public void GetCookieToken_CookieIsEmpty_ReturnsNull() + { + // Arrange + var mockHttpContext = GetMockHttpContext(_cookieName, string.Empty); + + var config = new AntiforgeryOptions() + { + CookieName = _cookieName + }; + + var tokenStore = new AntiforgeryTokenStore( + config: config, + serializer: null); + + // Act + var token = tokenStore.GetCookieToken(mockHttpContext); + + // Assert + Assert.Null(token); + } + + [Fact] + public void GetCookieToken_CookieIsInvalid_PropagatesException() + { + // Arrange + var mockHttpContext = GetMockHttpContext(_cookieName, "invalid-value"); + var config = new AntiforgeryOptions() + { + CookieName = _cookieName + }; + + var expectedException = new InvalidOperationException("some exception"); + var mockSerializer = new Mock(); + mockSerializer + .Setup(o => o.Deserialize("invalid-value")) + .Throws(expectedException); + + var tokenStore = new AntiforgeryTokenStore( + config: config, + serializer: mockSerializer.Object); + + // Act & assert + var ex = Assert.Throws(() => tokenStore.GetCookieToken(mockHttpContext)); + Assert.Same(expectedException, ex); + } + + [Fact] + public void GetCookieToken_CookieIsValid_ReturnsToken() + { + // Arrange + var expectedToken = new AntiforgeryToken(); + var mockHttpContext = GetMockHttpContext(_cookieName, "valid-value"); + + var config = new AntiforgeryOptions() + { + CookieName = _cookieName + }; + + var mockSerializer = new Mock(); + mockSerializer + .Setup(o => o.Deserialize("valid-value")) + .Returns(expectedToken); + + var tokenStore = new AntiforgeryTokenStore( + config: config, + serializer: mockSerializer.Object); + + // Act + AntiforgeryToken retVal = tokenStore.GetCookieToken(mockHttpContext); + + // Assert + Assert.Same(expectedToken, retVal); + } + + [Fact] + public async Task GetFormToken_FormFieldIsEmpty_ReturnsNull() + { + // Arrange + var mockHttpContext = new Mock(); + var requestContext = new Mock(); + var formCollection = new Mock(); + formCollection.Setup(f => f["form-field-name"]).Returns(string.Empty); + requestContext.Setup(o => o.ReadFormAsync(CancellationToken.None)) + .Returns(Task.FromResult(formCollection.Object)); + mockHttpContext.Setup(o => o.Request) + .Returns(requestContext.Object); + var config = new AntiforgeryOptions() + { + FormFieldName = "form-field-name" + }; + + var tokenStore = new AntiforgeryTokenStore( + config: config, + serializer: null); + + // Act + var token = await tokenStore.GetFormTokenAsync(mockHttpContext.Object); + + // Assert + Assert.Null(token); + } + + [Fact] + public async Task GetFormToken_FormFieldIsInvalid_PropagatesException() + { + // Arrange + var formCollection = new Mock(); + formCollection.Setup(f => f["form-field-name"]).Returns("invalid-value"); + + var requestContext = new Mock(); + requestContext.Setup(o => o.ReadFormAsync(CancellationToken.None)) + .Returns(Task.FromResult(formCollection.Object)); + + var mockHttpContext = new Mock(); + mockHttpContext.Setup(o => o.Request) + .Returns(requestContext.Object); + + var config = new AntiforgeryOptions() + { + FormFieldName = "form-field-name" + }; + + var expectedException = new InvalidOperationException("some exception"); + var mockSerializer = new Mock(); + mockSerializer.Setup(o => o.Deserialize("invalid-value")) + .Throws(expectedException); + + var tokenStore = new AntiforgeryTokenStore( + config: config, + serializer: mockSerializer.Object); + + // Act & assert + var ex = + await + Assert.ThrowsAsync( + async () => await tokenStore.GetFormTokenAsync(mockHttpContext.Object)); + Assert.Same(expectedException, ex); + } + + [Fact] + public async Task GetFormToken_FormFieldIsValid_ReturnsToken() + { + // Arrange + var expectedToken = new AntiforgeryToken(); + + // Arrange + var mockHttpContext = new Mock(); + var requestContext = new Mock(); + var formCollection = new Mock(); + formCollection.Setup(f => f["form-field-name"]).Returns("valid-value"); + requestContext.Setup(o => o.ReadFormAsync(CancellationToken.None)) + .Returns(Task.FromResult(formCollection.Object)); + mockHttpContext.Setup(o => o.Request) + .Returns(requestContext.Object); + + var config = new AntiforgeryOptions() + { + FormFieldName = "form-field-name" + }; + + var mockSerializer = new Mock(); + mockSerializer.Setup(o => o.Deserialize("valid-value")) + .Returns(expectedToken); + + var tokenStore = new AntiforgeryTokenStore( + config: config, + serializer: mockSerializer.Object); + + // Act + var retVal = await tokenStore.GetFormTokenAsync(mockHttpContext.Object); + + // Assert + Assert.Same(expectedToken, retVal); + } + + [Theory] + [InlineData(true, true)] + [InlineData(false, null)] + public void SaveCookieToken(bool requireSsl, bool? expectedCookieSecureFlag) + { + // Arrange + var token = new AntiforgeryToken(); + var mockCookies = new Mock(); + + bool defaultCookieSecureValue = expectedCookieSecureFlag ?? false; // pulled from config; set by ctor + var cookies = new MockResponseCookieCollection(); + + cookies.Count = 0; + var mockHttpContext = new Mock(); + mockHttpContext.Setup(o => o.Response.Cookies) + .Returns(cookies); + var contextAccessor = new AntiforgeryContextAccessor(); + mockHttpContext.SetupGet(o => o.RequestServices) + .Returns(GetServiceProvider(contextAccessor)); + + var mockSerializer = new Mock(); + mockSerializer.Setup(o => o.Serialize(token)) + .Returns("serialized-value"); + + var config = new AntiforgeryOptions() + { + CookieName = _cookieName, + RequireSSL = requireSsl + }; + + var tokenStore = new AntiforgeryTokenStore( + config: config, + serializer: mockSerializer.Object); + + // Act + tokenStore.SaveCookieToken(mockHttpContext.Object, token); + + // Assert + Assert.Equal(1, cookies.Count); + Assert.NotNull(contextAccessor.Value.CookieToken); + Assert.NotNull(cookies); + Assert.Equal(_cookieName, cookies.Key); + Assert.Equal("serialized-value", cookies.Value); + Assert.True(cookies.Options.HttpOnly); + Assert.Equal(defaultCookieSecureValue, cookies.Options.Secure); + } + + private HttpContext GetMockHttpContext(string cookieName, string cookieValue) + { + var requestCookies = new MockCookieCollection(new Dictionary() { { cookieName, cookieValue } }); + + var request = new Mock(); + request.Setup(o => o.Cookies) + .Returns(requestCookies); + var mockHttpContext = new Mock(); + mockHttpContext.Setup(o => o.Request) + .Returns(request.Object); + + var contextAccessor = new AntiforgeryContextAccessor(); + mockHttpContext.SetupGet(o => o.RequestServices) + .Returns(GetServiceProvider(contextAccessor)); + + return mockHttpContext.Object; + } + + private static IServiceProvider GetServiceProvider(IAntiforgeryContextAccessor contextAccessor) + { + var serviceCollection = new ServiceCollection(); + serviceCollection.AddInstance(contextAccessor); + return serviceCollection.BuildServiceProvider(); + } + + private class MockResponseCookieCollection : IResponseCookies + { + public string Key { get; set; } + public string Value { get; set; } + public CookieOptions Options { get; set; } + public int Count { get; set; } + + public void Append(string key, string value, CookieOptions options) + { + this.Key = key; + this.Value = value; + this.Options = options; + this.Count++; + } + + public void Append(string key, string value) + { + throw new NotImplementedException(); + } + + public void Delete(string key, CookieOptions options) + { + throw new NotImplementedException(); + } + + public void Delete(string key) + { + throw new NotImplementedException(); + } + } + + private class MockCookieCollection : IReadableStringCollection + { + private Dictionary _dictionary; + + public int Count + { + get + { + return _dictionary.Count; + } + } + + public ICollection Keys + { + get + { + return _dictionary.Keys; + } + } + + public MockCookieCollection(Dictionary dictionary) + { + _dictionary = dictionary; + } + + public static MockCookieCollection GetDummyInstance(string key, string value) + { + return new MockCookieCollection(new Dictionary() { { key, value } }); + } + + public string Get(string key) + { + return this[key]; + } + + public IList GetValues(string key) + { + throw new NotImplementedException(); + } + + public bool ContainsKey(string key) + { + return _dictionary.ContainsKey(key); + } + + public string this[string key] + { + get { return _dictionary[key]; } + } + + public IEnumerator> GetEnumerator() + { + throw new NotImplementedException(); + } + + System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() + { + throw new NotImplementedException(); + } + } + } +} + +#endif \ No newline at end of file diff --git a/test/Microsoft.AspNet.Antiforgery.Test/AntiforgeryTokenTest.cs b/test/Microsoft.AspNet.Antiforgery.Test/AntiforgeryTokenTest.cs new file mode 100644 index 0000000000..cddd47e43f --- /dev/null +++ b/test/Microsoft.AspNet.Antiforgery.Test/AntiforgeryTokenTest.cs @@ -0,0 +1,132 @@ +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using Xunit; + +namespace Microsoft.AspNet.Antiforgery +{ + public class AntiforgeryTokenTest + { + [Fact] + public void AdditionalDataProperty() + { + // Arrange + var token = new AntiforgeryToken(); + + // Act & assert - 1 + Assert.Equal("", token.AdditionalData); + + // Act & assert - 2 + token.AdditionalData = "additional data"; + Assert.Equal("additional data", token.AdditionalData); + + // Act & assert - 3 + token.AdditionalData = null; + Assert.Equal("", token.AdditionalData); + } + + [Fact] + public void ClaimUidProperty() + { + // Arrange + var token = new AntiforgeryToken(); + + // Act & assert - 1 + Assert.Null(token.ClaimUid); + + // Act & assert - 2 + BinaryBlob blob = new BinaryBlob(32); + token.ClaimUid = blob; + Assert.Equal(blob, token.ClaimUid); + + // Act & assert - 3 + token.ClaimUid = null; + Assert.Null(token.ClaimUid); + } + + [Fact] + public void IsSessionTokenProperty() + { + // Arrange + var token = new AntiforgeryToken(); + + // Act & assert - 1 + Assert.False(token.IsSessionToken); + + // Act & assert - 2 + token.IsSessionToken = true; + Assert.True(token.IsSessionToken); + + // Act & assert - 3 + token.IsSessionToken = false; + Assert.False(token.IsSessionToken); + } + + [Fact] + public void UsernameProperty() + { + // Arrange + var token = new AntiforgeryToken(); + + // Act & assert - 1 + Assert.Equal("", token.Username); + + // Act & assert - 2 + token.Username = "my username"; + Assert.Equal("my username", token.Username); + + // Act & assert - 3 + token.Username = null; + Assert.Equal("", token.Username); + } + + [Fact] + public void SecurityTokenProperty_GetsAutopopulated() + { + // Arrange + var token = new AntiforgeryToken(); + + // Act + var securityToken = token.SecurityToken; + + // Assert + Assert.NotNull(securityToken); + Assert.Equal(AntiforgeryToken.SecurityTokenBitLength, securityToken.BitLength); + + // check that we're not making a new one each property call + Assert.Equal(securityToken, token.SecurityToken); + } + + [Fact] + public void SecurityTokenProperty_PropertySetter_DoesNotUseDefaults() + { + // Arrange + var token = new AntiforgeryToken(); + + // Act + var securityToken = new BinaryBlob(64); + token.SecurityToken = securityToken; + + // Assert + Assert.Equal(securityToken, token.SecurityToken); + } + + [Fact] + public void SecurityTokenProperty_PropertySetter_DoesNotAllowNulls() + { + // Arrange + var token = new AntiforgeryToken(); + + // Act + token.SecurityToken = null; + var securityToken = token.SecurityToken; + + // Assert + Assert.NotNull(securityToken); + Assert.Equal(AntiforgeryToken.SecurityTokenBitLength, securityToken.BitLength); + + // check that we're not making a new one each property call + Assert.Equal(securityToken, token.SecurityToken); + } + } +} \ No newline at end of file diff --git a/test/Microsoft.AspNet.Antiforgery.Test/AntiforgeryWorkerTest.cs b/test/Microsoft.AspNet.Antiforgery.Test/AntiforgeryWorkerTest.cs new file mode 100644 index 0000000000..899a1f0225 --- /dev/null +++ b/test/Microsoft.AspNet.Antiforgery.Test/AntiforgeryWorkerTest.cs @@ -0,0 +1,583 @@ +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +#if DNX451 + +using System; +using System.Collections.Generic; +using System.Security.Claims; +using System.Threading.Tasks; +using Microsoft.AspNet.Antiforgery.Internal; +using Microsoft.AspNet.Http; +using Microsoft.AspNet.Http.Internal; +using Microsoft.Framework.WebEncoders.Testing; +using Moq; +using Xunit; + +namespace Microsoft.AspNet.Antiforgery +{ + public class AntiforgeryWorkerTest + { + + [Fact] + public async Task ChecksSSL_ValidateAsync_Throws() + { + // Arrange + var mockHttpContext = new Mock(); + mockHttpContext.Setup(o => o.Request.IsHttps) + .Returns(false); + + var config = new AntiforgeryOptions() + { + RequireSSL = true + }; + + var worker = new AntiforgeryWorker( + config: config, + serializer: null, + tokenStore: null, + generator: null, + validator: null, + htmlEncoder: new CommonTestEncoder()); + + // Act & assert + var ex = + await + Assert.ThrowsAsync( + async () => await worker.ValidateAsync(mockHttpContext.Object)); + Assert.Equal( + @"The anti-forgery system has the configuration value AntiforgeryOptions.RequireSsl = true, " + + "but the current request is not an SSL request.", + ex.Message); + } + + [Fact] + public void ChecksSSL_Validate_Throws() + { + // Arrange + var mockHttpContext = new Mock(); + mockHttpContext.Setup(o => o.Request.IsHttps) + .Returns(false); + + var config = new AntiforgeryOptions() + { + RequireSSL = true + }; + + var worker = new AntiforgeryWorker( + config: config, + serializer: null, + tokenStore: null, + generator: null, + validator: null, + htmlEncoder: new CommonTestEncoder()); + + // Act & assert + var ex = Assert.Throws( + () => worker.Validate(mockHttpContext.Object, cookieToken: null, formToken: null)); + Assert.Equal( + @"The anti-forgery system has the configuration value AntiforgeryOptions.RequireSsl = true, " + + "but the current request is not an SSL request.", + ex.Message); + } + + [Fact] + public void ChecksSSL_GetFormInputElement_Throws() + { + // Arrange + var mockHttpContext = new Mock(); + mockHttpContext.Setup(o => o.Request.IsHttps) + .Returns(false); + + var config = new AntiforgeryOptions() + { + RequireSSL = true + }; + + var worker = new AntiforgeryWorker( + config: config, + serializer: null, + tokenStore: null, + generator: null, + validator: null, + htmlEncoder: new CommonTestEncoder()); + + // Act & assert + var ex = Assert.Throws(() => worker.GetFormInputElement(mockHttpContext.Object)); + Assert.Equal( + @"The anti-forgery system has the configuration value AntiforgeryOptions.RequireSsl = true, " + + "but the current request is not an SSL request.", + ex.Message); + } + + [Fact] + public void ChecksSSL_GetTokens_Throws() + { + // Arrange + var mockHttpContext = new Mock(); + mockHttpContext.Setup(o => o.Request.IsHttps) + .Returns(false); + + var config = new AntiforgeryOptions() + { + RequireSSL = true + }; + + var worker = new AntiforgeryWorker( + config: config, + serializer: null, + tokenStore: null, + generator: null, + validator: null, + htmlEncoder: new CommonTestEncoder()); + + // Act & assert + var ex = Assert.Throws(() => + worker.GetTokens(mockHttpContext.Object, "cookie-token")); + Assert.Equal( + @"The anti-forgery system has the configuration value AntiforgeryOptions.RequireSsl = true, " + + "but the current request is not an SSL request.", + ex.Message); + } + + [Fact] + public void GetFormInputElement_ExistingInvalidCookieToken_GeneratesANewCookieAndAnAntiforgeryToken() + { + // Arrange + var config = new AntiforgeryOptions() + { + FormFieldName = "form-field-name" + }; + + // Make sure the existing cookie is invalid. + var context = GetAntiforgeryWorkerContext(config, isOldCookieValid: false); + var worker = GetAntiforgeryWorker(context); + + // Act + var inputElement = worker.GetFormInputElement(context.HttpContext.Object); + + // Assert + Assert.Equal( + @"", + inputElement); + context.TokenStore.Verify(); + } + + [Fact] + public void GetFormInputElement_ExistingInvalidCookieToken_SwallowsExceptions() + { + // Arrange + var config = new AntiforgeryOptions() + { + FormFieldName = "form-field-name" + }; + + // Make sure the existing cookie is invalid. + var context = GetAntiforgeryWorkerContext(config, isOldCookieValid: false); + var worker = GetAntiforgeryWorker(context); + + // This will cause the cookieToken to be null. + context.TokenStore.Setup(o => o.GetCookieToken(context.HttpContext.Object)) + .Throws(new Exception("should be swallowed")); + + // Setup so that the null cookie token returned is treated as invalid. + context.TokenValidator.Setup(o => o.IsCookieTokenValid(null)) + .Returns(false); + + // Act + var inputElement = worker.GetFormInputElement(context.HttpContext.Object); + + // Assert + Assert.Equal( + @"", + inputElement); + context.TokenStore.Verify(); + } + + [Fact] + public void GetFormInputElement_ExistingValidCookieToken_GeneratesAnAntiforgeryToken() + { + // Arrange + var options = new AntiforgeryOptions() + { + FormFieldName = "form-field-name" + }; + + // Make sure the existing cookie is valid and use the same cookie for the mock Token Provider. + var context = GetAntiforgeryWorkerContext(options, useOldCookie: true, isOldCookieValid: true); + var worker = GetAntiforgeryWorker(context); + + // Act + var inputElement = worker.GetFormInputElement(context.HttpContext.Object); + + // Assert + Assert.Equal( + @"", + inputElement); + } + + [Theory] + [InlineData(false, "SAMEORIGIN")] + [InlineData(true, null)] + public void GetFormInputElement_AddsXFrameOptionsHeader(bool suppressXFrameOptions, string expectedHeaderValue) + { + // Arrange + var options = new AntiforgeryOptions() + { + SuppressXFrameOptionsHeader = suppressXFrameOptions + }; + + // Genreate a new cookie. + var context = GetAntiforgeryWorkerContext(options, useOldCookie: false, isOldCookieValid: false); + var worker = GetAntiforgeryWorker(context); + + // Act + var inputElement = worker.GetFormInputElement(context.HttpContext.Object); + + // Assert + string xFrameOptions = context.HttpContext.Object.Response.Headers["X-Frame-Options"]; + Assert.Equal(expectedHeaderValue, xFrameOptions); + } + + [Fact] + public void GetTokens_ExistingInvalidCookieToken_GeneratesANewCookieTokenAndANewFormToken() + { + // Arrange + // Genreate a new cookie. + var context = GetAntiforgeryWorkerContext( + new AntiforgeryOptions(), + useOldCookie: false, + isOldCookieValid: false); + var worker = GetAntiforgeryWorker(context); + + // Act + var tokenset = worker.GetTokens(context.HttpContext.Object, "serialized-old-cookie-token"); + + // Assert + Assert.Equal("serialized-new-cookie-token", tokenset.CookieToken); + Assert.Equal("serialized-form-token", tokenset.FormToken); + } + + [Fact] + public void GetTokens_ExistingInvalidCookieToken_SwallowsExceptions() + { + // Arrange + // Make sure the existing cookie is invalid. + var context = GetAntiforgeryWorkerContext( + new AntiforgeryOptions(), + useOldCookie: false, + isOldCookieValid: false); + + // This will cause the cookieToken to be null. + context.TokenSerializer.Setup(o => o.Deserialize("serialized-old-cookie-token")) + .Throws(new Exception("should be swallowed")); + + // Setup so that the null cookie token returned is treated as invalid. + context.TokenValidator.Setup(o => o.IsCookieTokenValid(null)) + .Returns(false); + var worker = GetAntiforgeryWorker(context); + + // Act + var tokenset = worker.GetTokens(context.HttpContext.Object, "serialized-old-cookie-token"); + + // Assert + Assert.Equal("serialized-new-cookie-token", tokenset.CookieToken); + Assert.Equal("serialized-form-token", tokenset.FormToken); + } + + [Fact] + public void GetTokens_ExistingValidCookieToken_GeneratesANewFormToken() + { + // Arrange + var context = GetAntiforgeryWorkerContext( + new AntiforgeryOptions(), + useOldCookie: true, + isOldCookieValid: true); + context.TokenStore = null; + var worker = GetAntiforgeryWorker(context); + + // Act + var tokenset = worker.GetTokens(context.HttpContext.Object, "serialized-old-cookie-token"); + + // Assert + Assert.Null(tokenset.CookieToken); + Assert.Equal("serialized-form-token", tokenset.FormToken); + } + + [Fact] + public void Validate_FromInvalidStrings_Throws() + { + // Arrange + var context = GetAntiforgeryWorkerContext(new AntiforgeryOptions()); + + context.TokenSerializer.Setup(o => o.Deserialize("cookie-token")) + .Returns(context.TestTokenSet.OldCookieToken); + context.TokenSerializer.Setup(o => o.Deserialize("form-token")) + .Returns(context.TestTokenSet.FormToken); + + context.TokenValidator.Setup(o => o.ValidateTokens( + context.HttpContext.Object, + context.HttpContext.Object.User.Identity as ClaimsIdentity, + context.TestTokenSet.OldCookieToken, context.TestTokenSet.FormToken)) + .Throws(new InvalidOperationException("my-message")); + context.TokenStore = null; + var worker = GetAntiforgeryWorker(context); + + // Act & assert + var ex = + Assert.Throws( + () => worker.Validate(context.HttpContext.Object, "cookie-token", "form-token")); + Assert.Equal("my-message", ex.Message); + } + + [Fact] + public void Validate_FromValidStrings_TokensValidatedSuccessfully() + { + // Arrange + var context = GetAntiforgeryWorkerContext(new AntiforgeryOptions()); + + context.TokenSerializer.Setup(o => o.Deserialize("cookie-token")) + .Returns(context.TestTokenSet.OldCookieToken); + context.TokenSerializer.Setup(o => o.Deserialize("form-token")) + .Returns(context.TestTokenSet.FormToken); + + context.TokenValidator.Setup(o => o.ValidateTokens( + context.HttpContext.Object, + context.HttpContext.Object.User.Identity as ClaimsIdentity, + context.TestTokenSet.OldCookieToken, context.TestTokenSet.FormToken)) + .Verifiable(); + context.TokenStore = null; + var worker = GetAntiforgeryWorker(context); + + // Act + worker.Validate(context.HttpContext.Object, "cookie-token", "form-token"); + + // Assert + context.TokenValidator.Verify(); + } + + [Fact] + public async Task Validate_FromStore_Failure() + { + // Arrange + var context = GetAntiforgeryWorkerContext(new AntiforgeryOptions()); + + context.TokenValidator.Setup(o => o.ValidateTokens( + context.HttpContext.Object, + context.HttpContext.Object.User.Identity as ClaimsIdentity, + context.TestTokenSet.OldCookieToken, context.TestTokenSet.FormToken)) + .Throws(new InvalidOperationException("my-message")); + context.TokenSerializer = null; + var worker = GetAntiforgeryWorker(context); + + // Act & assert + var ex = + await + Assert.ThrowsAsync( + async () => await worker.ValidateAsync(context.HttpContext.Object)); + Assert.Equal("my-message", ex.Message); + } + + [Fact] + public async Task Validate_FromStore_Success() + { + // Arrange + var context = GetAntiforgeryWorkerContext(new AntiforgeryOptions()); + + context.TokenValidator.Setup(o => o.ValidateTokens( + context.HttpContext.Object, + context.HttpContext.Object.User.Identity as ClaimsIdentity, + context.TestTokenSet.OldCookieToken, context.TestTokenSet.FormToken)) + .Verifiable(); + context.TokenSerializer = null; + var worker = GetAntiforgeryWorker(context); + + // Act + await worker.ValidateAsync(context.HttpContext.Object); + + // Assert + context.TokenValidator.Verify(); + } + + [Theory] + [InlineData(false, "SAMEORIGIN")] + [InlineData(true, null)] + public void SetCookieTokenAndHeader_AddsXFrameOptionsHeader( + bool suppressXFrameOptions, + string expectedHeaderValue) + { + // Arrange + var options = new AntiforgeryOptions() + { + SuppressXFrameOptionsHeader = suppressXFrameOptions + }; + + // Genreate a new cookie. + var context = GetAntiforgeryWorkerContext(options, useOldCookie: false, isOldCookieValid: false); + var worker = GetAntiforgeryWorker(context); + + // Act + worker.SetCookieTokenAndHeader(context.HttpContext.Object); + + // Assert + var xFrameOptions = context.HttpContext.Object.Response.Headers["X-Frame-Options"]; + Assert.Equal(expectedHeaderValue, xFrameOptions); + } + + private AntiforgeryWorker GetAntiforgeryWorker(AntiforgeryWorkerContext context) + { + return new AntiforgeryWorker( + config: context.Options, + serializer: context.TokenSerializer != null ? context.TokenSerializer.Object : null, + tokenStore: context.TokenStore != null ? context.TokenStore.Object : null, + generator: context.TokenGenerator != null ? context.TokenGenerator.Object : null, + validator: context.TokenValidator != null ? context.TokenValidator.Object : null, + htmlEncoder: new CommonTestEncoder()); + } + + private Mock GetHttpContext(bool setupResponse = true) + { + var identity = new ClaimsIdentity("some-auth"); + var mockHttpContext = new Mock(); + mockHttpContext.Setup(o => o.User) + .Returns(new ClaimsPrincipal(identity)); + + if (setupResponse) + { + var mockResponse = new Mock(); + mockResponse.Setup(r => r.Headers) + .Returns(new HeaderDictionary(new Dictionary())); + mockHttpContext.Setup(o => o.Response) + .Returns(mockResponse.Object); + } + + return mockHttpContext; + } + + private Mock GetTokenStore( + HttpContext context, + TestTokenSet testTokenSet, + bool saveNewCookie = true) + { + var oldCookieToken = testTokenSet.OldCookieToken; + var formToken = testTokenSet.FormToken; + var mockTokenStore = new Mock(MockBehavior.Strict); + mockTokenStore.Setup(o => o.GetCookieToken(context)) + .Returns(oldCookieToken); + mockTokenStore.Setup(o => o.GetFormTokenAsync(context)) + .Returns(Task.FromResult(formToken)); + + if (saveNewCookie) + { + var newCookieToken = testTokenSet.NewCookieToken; + mockTokenStore.Setup(o => o.SaveCookieToken(context, newCookieToken)) + .Verifiable(); + } + + return mockTokenStore; + } + + private Mock GetTokenSerializer(TestTokenSet testTokenSet) + { + var oldCookieToken = testTokenSet.OldCookieToken; + var newCookieToken = testTokenSet.NewCookieToken; + var formToken = testTokenSet.FormToken; + var mockSerializer = new Mock(MockBehavior.Strict); + mockSerializer.Setup(o => o.Serialize(formToken)) + .Returns("serialized-form-token"); + mockSerializer.Setup(o => o.Deserialize("serialized-old-cookie-token")) + .Returns(oldCookieToken); + mockSerializer.Setup(o => o.Serialize(newCookieToken)) + .Returns("serialized-new-cookie-token"); + return mockSerializer; + } + + private TestTokenSet GetTokenSet(bool isOldCookieTokenSessionToken = true, bool isNewCookieSessionToken = true) + { + return new TestTokenSet() + { + FormToken = new AntiforgeryToken() { IsSessionToken = false }, + OldCookieToken = new AntiforgeryToken() { IsSessionToken = isOldCookieTokenSessionToken }, + NewCookieToken = new AntiforgeryToken() { IsSessionToken = isNewCookieSessionToken }, + }; + } + + private AntiforgeryWorkerContext GetAntiforgeryWorkerContext( + AntiforgeryOptions config, + bool useOldCookie = false, + bool isOldCookieValid = true) + { + // Arrange + var mockHttpContext = GetHttpContext(); + var testTokenSet = GetTokenSet(isOldCookieTokenSessionToken: true, isNewCookieSessionToken: true); + + var mockSerializer = GetTokenSerializer(testTokenSet); + + var mockTokenStore = GetTokenStore(mockHttpContext.Object, testTokenSet); + + var mockGenerator = new Mock(MockBehavior.Strict); + mockGenerator + .Setup(o => o.GenerateFormToken( + mockHttpContext.Object, + mockHttpContext.Object.User.Identity as ClaimsIdentity, + useOldCookie ? testTokenSet.OldCookieToken : testTokenSet.NewCookieToken)) + .Returns(testTokenSet.FormToken); + + mockGenerator + .Setup(o => o.GenerateCookieToken()) + .Returns(useOldCookie ? testTokenSet.OldCookieToken : testTokenSet.NewCookieToken); + + var mockValidator = new Mock(MockBehavior.Strict); + mockValidator + .Setup(o => o.IsCookieTokenValid(testTokenSet.OldCookieToken)) + .Returns(isOldCookieValid); + + mockValidator + .Setup(o => o.IsCookieTokenValid(testTokenSet.NewCookieToken)) + .Returns(!isOldCookieValid); + + return new AntiforgeryWorkerContext() + { + Options = config, + HttpContext = mockHttpContext, + TokenGenerator = mockGenerator, + TokenValidator = mockValidator, + TokenSerializer = mockSerializer, + TokenStore = mockTokenStore, + TestTokenSet = testTokenSet + }; + } + + private class TestTokenSet + { + public AntiforgeryToken FormToken { get; set; } + public string FormTokenString { get; set; } + public AntiforgeryToken OldCookieToken { get; set; } + public string OldCookieTokenString { get; set; } + public AntiforgeryToken NewCookieToken { get; set; } + public string NewCookieTokenString { get; set; } + } + + private class AntiforgeryWorkerContext + { + public AntiforgeryOptions Options { get; set; } + + public TestTokenSet TestTokenSet { get; set; } + + public Mock HttpContext { get; set; } + + public Mock TokenGenerator { get; set; } + + public Mock TokenValidator { get; set; } + + public Mock TokenStore { get; set; } + + public Mock TokenSerializer { get; set; } + } + } +} + +#endif \ No newline at end of file diff --git a/test/Microsoft.AspNet.Antiforgery.Test/BinaryBlobTest.cs b/test/Microsoft.AspNet.Antiforgery.Test/BinaryBlobTest.cs new file mode 100644 index 0000000000..c27b12986d --- /dev/null +++ b/test/Microsoft.AspNet.Antiforgery.Test/BinaryBlobTest.cs @@ -0,0 +1,129 @@ +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System; +using Xunit; + +namespace Microsoft.AspNet.Antiforgery +{ + public class BinaryBlobTest + { + [Fact] + public void Ctor_BitLength() + { + // Act + var blob = new BinaryBlob(bitLength: 64); + var data = blob.GetData(); + + // Assert + Assert.Equal(64, blob.BitLength); + Assert.Equal(64 / 8, data.Length); + Assert.NotEqual(new byte[64 / 8], data); // should not be a zero-filled array + } + + [Theory] + [InlineData(24)] + [InlineData(33)] + public void Ctor_BitLength_Bad(int bitLength) + { + // Act & assert + var ex = Assert.Throws(() => new BinaryBlob(bitLength)); + Assert.Equal("bitLength", ex.ParamName); + } + + [Fact] + public void Ctor_BitLength_ProducesDifferentValues() + { + // Act + var blobA = new BinaryBlob(bitLength: 64); + var blobB = new BinaryBlob(bitLength: 64); + + // Assert + Assert.NotEqual(blobA.GetData(), blobB.GetData()); + } + + [Fact] + public void Ctor_Data() + { + // Arrange + var expectedData = new byte[] { 0x01, 0x02, 0x03, 0x04 }; + + // Act + var blob = new BinaryBlob(32, expectedData); + + // Assert + Assert.Equal(32, blob.BitLength); + Assert.Equal(expectedData, blob.GetData()); + } + + [Theory] + [InlineData((object[])null)] + [InlineData(new byte[] { 0x01, 0x02, 0x03 })] + public void Ctor_Data_Bad(byte[] data) + { + // Act & assert + var ex = Assert.Throws(() => new BinaryBlob(32, data)); + Assert.Equal("data", ex.ParamName); + } + + [Fact] + public void Equals_DifferentData_ReturnsFalse() + { + // Arrange + object blobA = new BinaryBlob(32, new byte[] { 0x01, 0x02, 0x03, 0x04 }); + object blobB = new BinaryBlob(32, new byte[] { 0x04, 0x03, 0x02, 0x01 }); + + // Act & assert + Assert.NotEqual(blobA, blobB); + } + + [Fact] + public void Equals_NotABlob_ReturnsFalse() + { + // Arrange + object blobA = new BinaryBlob(32); + object blobB = "hello"; + + // Act & assert + Assert.NotEqual(blobA, blobB); + } + + [Fact] + public void Equals_Null_ReturnsFalse() + { + // Arrange + object blobA = new BinaryBlob(32); + object blobB = null; + + // Act & assert + Assert.NotEqual(blobA, blobB); + } + + [Fact] + public void Equals_SameData_ReturnsTrue() + { + // Arrange + object blobA = new BinaryBlob(32, new byte[] { 0x01, 0x02, 0x03, 0x04 }); + object blobB = new BinaryBlob(32, new byte[] { 0x01, 0x02, 0x03, 0x04 }); + + // Act & assert + Assert.Equal(blobA, blobB); + } + + [Fact] + public void GetHashCodeTest() + { + // Arrange + var blobData = new byte[] { 0x01, 0x02, 0x03, 0x04 }; + var expectedHashCode = BitConverter.ToInt32(blobData, 0); + + var blob = new BinaryBlob(32, blobData); + + // Act + var actualHashCode = blob.GetHashCode(); + + // Assert + Assert.Equal(expectedHashCode, actualHashCode); + } + } +} \ No newline at end of file diff --git a/test/Microsoft.AspNet.Antiforgery.Test/ClaimUidExtractorTest.cs b/test/Microsoft.AspNet.Antiforgery.Test/ClaimUidExtractorTest.cs new file mode 100644 index 0000000000..1a8dd5c8c7 --- /dev/null +++ b/test/Microsoft.AspNet.Antiforgery.Test/ClaimUidExtractorTest.cs @@ -0,0 +1,115 @@ +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System; +using System.Linq; +using System.Security.Claims; +#if DNX451 +using Moq; +#endif +using Xunit; + +namespace Microsoft.AspNet.Antiforgery +{ + public class ClaimUidExtractorTest + { + [Fact] + public void ExtractClaimUid_NullIdentity() + { + // Arrange + IClaimUidExtractor extractor = new DefaultClaimUidExtractor(); + + // Act + var claimUid = extractor.ExtractClaimUid(null); + + // Assert + Assert.Null(claimUid); + } + +#if DNX451 + [Fact] + public void ExtractClaimUid_Unauthenticated() + { + // Arrange + IClaimUidExtractor extractor = new DefaultClaimUidExtractor(); + + var mockIdentity = new Mock(); + mockIdentity.Setup(o => o.IsAuthenticated) + .Returns(false); + + // Act + var claimUid = extractor.ExtractClaimUid(mockIdentity.Object); + + // Assert + Assert.Null(claimUid); + } + + [Fact] + public void ExtractClaimUid_ClaimsIdentity() + { + // Arrange + var mockIdentity = new Mock(); + mockIdentity.Setup(o => o.IsAuthenticated) + .Returns(true); + + IClaimUidExtractor extractor = new DefaultClaimUidExtractor(); + + // Act + var claimUid = extractor.ExtractClaimUid(mockIdentity.Object); + + // Assert + Assert.NotNull(claimUid); + Assert.Equal("47DEQpj8HBSa+/TImW+5JCeuQeRkm5NMpJWZG3hSuFU=", claimUid); + } +#endif + + [Fact] + public void DefaultUniqueClaimTypes_NotPresent_SerializesAllClaimTypes() + { + var identity = new ClaimsIdentity(); + identity.AddClaim(new Claim(ClaimTypes.Email, "someone@antifrogery.com")); + identity.AddClaim(new Claim(ClaimTypes.GivenName, "some")); + identity.AddClaim(new Claim(ClaimTypes.Surname, "one")); +#if DNX451 + // CoreCLR doesn't support an 'empty' name + identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, string.Empty)); +#endif + + // Arrange + var claimsIdentity = (ClaimsIdentity)identity; + + // Act + var identiferParameters = DefaultClaimUidExtractor.GetUniqueIdentifierParameters(claimsIdentity) + .ToArray(); + var claims = claimsIdentity.Claims.ToList(); + claims.Sort((a, b) => string.Compare(a.Type, b.Type, StringComparison.Ordinal)); + + // Assert + int index = 0; + foreach (var claim in claims) + { + Assert.Equal(identiferParameters[index++], claim.Type); + Assert.Equal(identiferParameters[index++], claim.Value); + } + } + + [Fact] + public void DefaultUniqueClaimTypes_Present() + { + // Arrange + var identity = new ClaimsIdentity(); + identity.AddClaim(new Claim("fooClaim", "fooClaimValue")); + identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, "nameIdentifierValue")); + + // Act + var uniqueIdentifierParameters = DefaultClaimUidExtractor.GetUniqueIdentifierParameters(identity); + + // Assert + Assert.Equal(new string[] + { + ClaimTypes.NameIdentifier, + "nameIdentifierValue", + }, uniqueIdentifierParameters); + } + } +} \ No newline at end of file diff --git a/test/Microsoft.AspNet.Antiforgery.Test/Microsoft.AspNet.Antiforgery.Test.xproj b/test/Microsoft.AspNet.Antiforgery.Test/Microsoft.AspNet.Antiforgery.Test.xproj index fa6e61dfa1..efe8ba14f1 100644 --- a/test/Microsoft.AspNet.Antiforgery.Test/Microsoft.AspNet.Antiforgery.Test.xproj +++ b/test/Microsoft.AspNet.Antiforgery.Test/Microsoft.AspNet.Antiforgery.Test.xproj @@ -4,7 +4,6 @@ 14.0 $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion) - 415e83f8-6002-47e4-aa8e-cd5169c06f28 @@ -12,9 +11,11 @@ ..\..\artifacts\obj\$(MSBuildProjectName) ..\..\artifacts\bin\$(MSBuildProjectName)\ - 2.0 + + + - + \ No newline at end of file diff --git a/test/Microsoft.AspNet.Antiforgery.Test/TokenProviderTest.cs b/test/Microsoft.AspNet.Antiforgery.Test/TokenProviderTest.cs new file mode 100644 index 0000000000..ea3955511f --- /dev/null +++ b/test/Microsoft.AspNet.Antiforgery.Test/TokenProviderTest.cs @@ -0,0 +1,588 @@ +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System; +using System.Security.Claims; +using System.Security.Cryptography; +using Microsoft.AspNet.Http; +#if DNX451 +using Moq; +#endif +using Xunit; + +namespace Microsoft.AspNet.Antiforgery +{ + public class TokenProviderTest + { + [Fact] + public void GenerateCookieToken() + { + // Arrange + var tokenProvider = new AntiforgeryTokenProvider( + config: null, + claimUidExtractor: null, + additionalDataProvider: null); + + // Act + var retVal = tokenProvider.GenerateCookieToken(); + + // Assert + Assert.NotNull(retVal); + } + +#if DNX451 + [Fact] + public void GenerateFormToken_AnonymousUser() + { + // Arrange + var cookieToken = new AntiforgeryToken() { IsSessionToken = true }; + var httpContext = new Mock().Object; + var mockIdentity = new Mock(); + mockIdentity.Setup(o => o.IsAuthenticated) + .Returns(false); + + var config = new AntiforgeryOptions(); + + var tokenProvider = new AntiforgeryTokenProvider( + config: config, + claimUidExtractor: null, + additionalDataProvider: null); + + // Act + var fieldToken = tokenProvider.GenerateFormToken(httpContext, mockIdentity.Object, cookieToken); + + // Assert + Assert.NotNull(fieldToken); + Assert.Equal(cookieToken.SecurityToken, fieldToken.SecurityToken); + Assert.False(fieldToken.IsSessionToken); + Assert.Empty(fieldToken.Username); + Assert.Null(fieldToken.ClaimUid); + Assert.Empty(fieldToken.AdditionalData); + } + + [Fact] + public void GenerateFormToken_AuthenticatedWithoutUsernameAndNoAdditionalData_NoAdditionalData() + { + // Arrange + var cookieToken = new AntiforgeryToken() + { + IsSessionToken = true + }; + + var httpContext = new Mock().Object; + ClaimsIdentity identity = new MyAuthenticatedIdentityWithoutUsername(); + var config = new AntiforgeryOptions(); + IClaimUidExtractor claimUidExtractor = new Mock().Object; + + var tokenProvider = new AntiforgeryTokenProvider( + config: config, + claimUidExtractor: claimUidExtractor, + additionalDataProvider: null); + + // Act & assert + var ex = + Assert.Throws( + () => tokenProvider.GenerateFormToken(httpContext, identity, cookieToken)); + Assert.Equal( + "The provided identity of type " + + $"'{typeof(MyAuthenticatedIdentityWithoutUsername).FullName}' " + + "is marked IsAuthenticated = true but does not have a value for Name. " + + "By default, the anti-forgery system requires that all authenticated identities have a unique Name. " + + "If it is not possible to provide a unique Name for this identity, " + + "consider extending IAdditionalDataProvider by overriding the DefaultAdditionalDataProvider " + + "or a custom type that can provide some form of unique identifier for the current user.", + ex.Message); + } + + [Fact] + public void GenerateFormToken_AuthenticatedWithoutUsername_WithAdditionalData() + { + // Arrange + var cookieToken = new AntiforgeryToken() { IsSessionToken = true }; + var httpContext = new Mock().Object; + ClaimsIdentity identity = new MyAuthenticatedIdentityWithoutUsername(); + + var mockAdditionalDataProvider = new Mock(); + mockAdditionalDataProvider.Setup(o => o.GetAdditionalData(httpContext)) + .Returns("additional-data"); + + var config = new AntiforgeryOptions(); + IClaimUidExtractor claimUidExtractor = new Mock().Object; + + var tokenProvider = new AntiforgeryTokenProvider( + config: config, + claimUidExtractor: claimUidExtractor, + additionalDataProvider: mockAdditionalDataProvider.Object); + + // Act + var fieldToken = tokenProvider.GenerateFormToken(httpContext, identity, cookieToken); + + // Assert + Assert.NotNull(fieldToken); + Assert.Equal(cookieToken.SecurityToken, fieldToken.SecurityToken); + Assert.False(fieldToken.IsSessionToken); + Assert.Empty(fieldToken.Username); + Assert.Null(fieldToken.ClaimUid); + Assert.Equal("additional-data", fieldToken.AdditionalData); + } + + [Fact] + public void GenerateFormToken_ClaimsBasedIdentity() + { + // Arrange + var cookieToken = new AntiforgeryToken() { IsSessionToken = true }; + var httpContext = new Mock().Object; + var identity = GetAuthenticatedIdentity("some-identity"); + + var config = new AntiforgeryOptions(); + + byte[] data = new byte[256 / 8]; + using (var rng = RandomNumberGenerator.Create()) + { + rng.GetBytes(data); + } + var base64ClaimUId = Convert.ToBase64String(data); + var expectedClaimUid = new BinaryBlob(256, data); + + var mockClaimUidExtractor = new Mock(); + mockClaimUidExtractor.Setup(o => o.ExtractClaimUid(identity)) + .Returns(base64ClaimUId); + + var tokenProvider = new AntiforgeryTokenProvider( + config: config, + claimUidExtractor: mockClaimUidExtractor.Object, + additionalDataProvider: null); + + // Act + var fieldToken = tokenProvider.GenerateFormToken(httpContext, identity, cookieToken); + + // Assert + Assert.NotNull(fieldToken); + Assert.Equal(cookieToken.SecurityToken, fieldToken.SecurityToken); + Assert.False(fieldToken.IsSessionToken); + Assert.Equal("", fieldToken.Username); + Assert.Equal(expectedClaimUid, fieldToken.ClaimUid); + Assert.Equal("", fieldToken.AdditionalData); + } + + [Fact] + public void GenerateFormToken_RegularUserWithUsername() + { + // Arrange + var cookieToken = new AntiforgeryToken() { IsSessionToken = true }; + + var httpContext = new Mock().Object; + var mockIdentity = new Mock(); + mockIdentity.Setup(o => o.IsAuthenticated) + .Returns(true); + mockIdentity.Setup(o => o.Name) + .Returns("my-username"); + + var config = new AntiforgeryOptions(); + IClaimUidExtractor claimUidExtractor = new Mock().Object; + + var tokenProvider = new AntiforgeryTokenProvider( + config: config, + claimUidExtractor: claimUidExtractor, + additionalDataProvider: null); + + // Act + var fieldToken = tokenProvider.GenerateFormToken(httpContext, mockIdentity.Object, cookieToken); + + // Assert + Assert.NotNull(fieldToken); + Assert.Equal(cookieToken.SecurityToken, fieldToken.SecurityToken); + Assert.False(fieldToken.IsSessionToken); + Assert.Equal("my-username", fieldToken.Username); + Assert.Null(fieldToken.ClaimUid); + Assert.Empty(fieldToken.AdditionalData); + } +#endif + + [Fact] + public void IsCookieTokenValid_FieldToken_ReturnsFalse() + { + // Arrange + var cookieToken = new AntiforgeryToken() + { + IsSessionToken = false + }; + + var tokenProvider = new AntiforgeryTokenProvider( + config: null, + claimUidExtractor: null, + additionalDataProvider: null); + + // Act + bool retVal = tokenProvider.IsCookieTokenValid(cookieToken); + + // Assert + Assert.False(retVal); + } + + [Fact] + public void IsCookieTokenValid_NullToken_ReturnsFalse() + { + // Arrange + AntiforgeryToken cookieToken = null; + var tokenProvider = new AntiforgeryTokenProvider( + config: null, + claimUidExtractor: null, + additionalDataProvider: null); + + // Act + bool retVal = tokenProvider.IsCookieTokenValid(cookieToken); + + // Assert + Assert.False(retVal); + } + + [Fact] + public void IsCookieTokenValid_ValidToken_ReturnsTrue() + { + // Arrange + var cookieToken = new AntiforgeryToken() + { + IsSessionToken = true + }; + + var tokenProvider = new AntiforgeryTokenProvider( + config: null, + claimUidExtractor: null, + additionalDataProvider: null); + + // Act + bool retVal = tokenProvider.IsCookieTokenValid(cookieToken); + + // Assert + Assert.True(retVal); + } + +#if DNX451 + [Fact] + public void ValidateTokens_SessionTokenMissing() + { + // Arrange + var httpContext = new Mock().Object; + ClaimsIdentity identity = new Mock().Object; + AntiforgeryToken sessionToken = null; + var fieldtoken = new AntiforgeryToken() { IsSessionToken = false }; + + var config = new AntiforgeryOptions() + { + CookieName = "my-cookie-name" + }; + var tokenProvider = new AntiforgeryTokenProvider( + config: config, + claimUidExtractor: null, + additionalDataProvider: null); + + // Act & assert + var ex = + Assert.Throws( + () => tokenProvider.ValidateTokens(httpContext, identity, sessionToken, fieldtoken)); + Assert.Equal(@"The required anti-forgery cookie ""my-cookie-name"" is not present.", ex.Message); + } + + [Fact] + public void ValidateTokens_FieldTokenMissing() + { + // Arrange + var httpContext = new Mock().Object; + ClaimsIdentity identity = new Mock().Object; + var sessionToken = new AntiforgeryToken() { IsSessionToken = true }; + AntiforgeryToken fieldtoken = null; + + var config = new AntiforgeryOptions() + { + FormFieldName = "my-form-field-name" + }; + + var tokenProvider = new AntiforgeryTokenProvider( + config: config, + claimUidExtractor: null, + additionalDataProvider: null); + + // Act & assert + var ex = + Assert.Throws( + () => tokenProvider.ValidateTokens(httpContext, identity, sessionToken, fieldtoken)); + Assert.Equal(@"The required anti-forgery form field ""my-form-field-name"" is not present.", ex.Message); + } + + [Fact] + public void ValidateTokens_FieldAndSessionTokensSwapped() + { + // Arrange + var httpContext = new Mock().Object; + ClaimsIdentity identity = new Mock().Object; + var sessionToken = new AntiforgeryToken() { IsSessionToken = true }; + var fieldtoken = new AntiforgeryToken() { IsSessionToken = false }; + + var config = new AntiforgeryOptions() + { + CookieName = "my-cookie-name", + FormFieldName = "my-form-field-name" + }; + + var tokenProvider = new AntiforgeryTokenProvider( + config: config, + claimUidExtractor: null, + additionalDataProvider: null); + + // Act & assert + var ex1 = + Assert.Throws( + () => tokenProvider.ValidateTokens(httpContext, identity, fieldtoken, fieldtoken)); + Assert.Equal( + "Validation of the provided anti-forgery token failed. " + + @"The cookie ""my-cookie-name"" and the form field ""my-form-field-name"" were swapped.", + ex1.Message); + + var ex2 = + Assert.Throws( + () => tokenProvider.ValidateTokens(httpContext, identity, sessionToken, sessionToken)); + Assert.Equal( + "Validation of the provided anti-forgery token failed. " + + @"The cookie ""my-cookie-name"" and the form field ""my-form-field-name"" were swapped.", + ex2.Message); + } + + [Fact] + public void ValidateTokens_FieldAndSessionTokensHaveDifferentSecurityKeys() + { + // Arrange + var httpContext = new Mock().Object; + ClaimsIdentity identity = new Mock().Object; + var sessionToken = new AntiforgeryToken() { IsSessionToken = true }; + var fieldtoken = new AntiforgeryToken() { IsSessionToken = false }; + + var tokenProvider = new AntiforgeryTokenProvider( + config: null, + claimUidExtractor: null, + additionalDataProvider: null); + + // Act & assert + var ex = + Assert.Throws( + () => tokenProvider.ValidateTokens(httpContext, identity, sessionToken, fieldtoken)); + Assert.Equal(@"The anti-forgery cookie token and form field token do not match.", ex.Message); + } + + [Theory] + [InlineData("the-user", "the-other-user")] + [InlineData("http://example.com/uri-casing", "http://example.com/URI-casing")] + [InlineData("https://example.com/secure-uri-casing", "https://example.com/secure-URI-casing")] + public void ValidateTokens_UsernameMismatch(string identityUsername, string embeddedUsername) + { + // Arrange + var httpContext = new Mock().Object; + var identity = GetAuthenticatedIdentity(identityUsername); + var sessionToken = new AntiforgeryToken() { IsSessionToken = true }; + var fieldtoken = new AntiforgeryToken() + { + SecurityToken = sessionToken.SecurityToken, + Username = embeddedUsername, + IsSessionToken = false + }; + + var mockClaimUidExtractor = new Mock(); + mockClaimUidExtractor.Setup(o => o.ExtractClaimUid(identity)) + .Returns((string)null); + + var tokenProvider = new AntiforgeryTokenProvider( + config: null, + claimUidExtractor: mockClaimUidExtractor.Object, + additionalDataProvider: null); + + // Act & assert + var ex = + Assert.Throws( + () => tokenProvider.ValidateTokens(httpContext, identity, sessionToken, fieldtoken)); + Assert.Equal( + @"The provided anti-forgery token was meant for user """ + embeddedUsername + + @""", but the current user is """ + identityUsername + @""".", ex.Message); + } + + [Fact] + public void ValidateTokens_ClaimUidMismatch() + { + // Arrange + var httpContext = new Mock().Object; + var identity = GetAuthenticatedIdentity("the-user"); + var sessionToken = new AntiforgeryToken() { IsSessionToken = true }; + var fieldtoken = new AntiforgeryToken() + { + SecurityToken = sessionToken.SecurityToken, + IsSessionToken = false, + ClaimUid = new BinaryBlob(256) + }; + + var differentToken = new BinaryBlob(256); + var mockClaimUidExtractor = new Mock(); + mockClaimUidExtractor.Setup(o => o.ExtractClaimUid(identity)) + .Returns(Convert.ToBase64String(differentToken.GetData())); + + var tokenProvider = new AntiforgeryTokenProvider( + config: null, + claimUidExtractor: mockClaimUidExtractor.Object, + additionalDataProvider: null); + + // Act & assert + var ex = + Assert.Throws( + () => tokenProvider.ValidateTokens(httpContext, identity, sessionToken, fieldtoken)); + Assert.Equal( + @"The provided anti-forgery token was meant for a different claims-based user than the current user.", + ex.Message); + } + + [Fact] + public void ValidateTokens_AdditionalDataRejected() + { + // Arrange + var httpContext = new Mock().Object; + var identity = new ClaimsIdentity(); + var sessionToken = new AntiforgeryToken() { IsSessionToken = true }; + var fieldtoken = new AntiforgeryToken() + { + SecurityToken = sessionToken.SecurityToken, + Username = String.Empty, + IsSessionToken = false, + AdditionalData = "some-additional-data" + }; + + var mockAdditionalDataProvider = new Mock(); + mockAdditionalDataProvider.Setup(o => o.ValidateAdditionalData(httpContext, "some-additional-data")) + .Returns(false); + + var config = new AntiforgeryOptions(); + var tokenProvider = new AntiforgeryTokenProvider( + config: config, + claimUidExtractor: null, + additionalDataProvider: mockAdditionalDataProvider.Object); + + // Act & assert + var ex = + Assert.Throws( + () => tokenProvider.ValidateTokens(httpContext, identity, sessionToken, fieldtoken)); + Assert.Equal(@"The provided anti-forgery token failed a custom data check.", ex.Message); + } + + [Fact] + public void ValidateTokens_Success_AnonymousUser() + { + // Arrange + var httpContext = new Mock().Object; + var identity = new ClaimsIdentity(); + var sessionToken = new AntiforgeryToken() { IsSessionToken = true }; + var fieldtoken = new AntiforgeryToken() + { + SecurityToken = sessionToken.SecurityToken, + Username = String.Empty, + IsSessionToken = false, + AdditionalData = "some-additional-data" + }; + + var mockAdditionalDataProvider = new Mock(); + mockAdditionalDataProvider.Setup(o => o.ValidateAdditionalData(httpContext, "some-additional-data")) + .Returns(true); + + var config = new AntiforgeryOptions(); + var tokenProvider = new AntiforgeryTokenProvider( + config: config, + claimUidExtractor: null, + additionalDataProvider: mockAdditionalDataProvider.Object); + + // Act + tokenProvider.ValidateTokens(httpContext, identity, sessionToken, fieldtoken); + + // Assert + // Nothing to assert - if we got this far, success! + } + + [Fact] + public void ValidateTokens_Success_AuthenticatedUserWithUsername() + { + // Arrange + var httpContext = new Mock().Object; + var identity = GetAuthenticatedIdentity("the-user"); + var sessionToken = new AntiforgeryToken() { IsSessionToken = true }; + var fieldtoken = new AntiforgeryToken() + { + SecurityToken = sessionToken.SecurityToken, + Username = "THE-USER", + IsSessionToken = false, + AdditionalData = "some-additional-data" + }; + + var mockAdditionalDataProvider = new Mock(); + mockAdditionalDataProvider.Setup(o => o.ValidateAdditionalData(httpContext, "some-additional-data")) + .Returns(true); + + var config = new AntiforgeryOptions(); + var tokenProvider = new AntiforgeryTokenProvider( + config: config, + claimUidExtractor: new Mock().Object, + additionalDataProvider: mockAdditionalDataProvider.Object); + + // Act + tokenProvider.ValidateTokens(httpContext, identity, sessionToken, fieldtoken); + + // Assert + // Nothing to assert - if we got this far, success! + } + + [Fact] + public void ValidateTokens_Success_ClaimsBasedUser() + { + // Arrange + var httpContext = new Mock().Object; + var identity = GetAuthenticatedIdentity("the-user"); + var sessionToken = new AntiforgeryToken() { IsSessionToken = true }; + var fieldtoken = new AntiforgeryToken() + { + SecurityToken = sessionToken.SecurityToken, + IsSessionToken = false, + ClaimUid = new BinaryBlob(256) + }; + + var mockClaimUidExtractor = new Mock(); + mockClaimUidExtractor.Setup(o => o.ExtractClaimUid(identity)) + .Returns(Convert.ToBase64String(fieldtoken.ClaimUid.GetData())); + + var config = new AntiforgeryOptions(); + + var tokenProvider = new AntiforgeryTokenProvider( + config: config, + claimUidExtractor: mockClaimUidExtractor.Object, + additionalDataProvider: null); + + // Act + tokenProvider.ValidateTokens(httpContext, identity, sessionToken, fieldtoken); + + // Assert + // Nothing to assert - if we got this far, success! + } +#endif + + private static ClaimsIdentity GetAuthenticatedIdentity(string identityUsername) + { + var claim = new Claim(ClaimsIdentity.DefaultNameClaimType, identityUsername); + return new ClaimsIdentity(new[] { claim }, "Some-Authentication"); + } + + private sealed class MyAuthenticatedIdentityWithoutUsername : ClaimsIdentity + { + public override bool IsAuthenticated + { + get { return true; } + } + + public override string Name + { + get { return String.Empty; } + } + } + } +} \ No newline at end of file diff --git a/test/Microsoft.AspNet.Antiforgery.Test/project.json b/test/Microsoft.AspNet.Antiforgery.Test/project.json index 8307de87d5..ce82ef7f25 100644 --- a/test/Microsoft.AspNet.Antiforgery.Test/project.json +++ b/test/Microsoft.AspNet.Antiforgery.Test/project.json @@ -1,6 +1,9 @@ { "dependencies": { "Microsoft.AspNet.Antiforgery": "1.0.0-*", + "Microsoft.AspNet.Http": "1.0.0-*", + "Microsoft.Framework.DependencyInjection": "1.0.0-*", + "Microsoft.Framework.WebEncoders.Testing": "1.0.0-*", "xunit.runner.aspnet": "2.0.0-aspnet-*" }, "commands": { @@ -8,7 +11,11 @@ "test": "xunit.runner.aspnet" }, "frameworks": { - "dnx451": { }, + "dnx451": { + "dependencies": { + "Moq": "4.2.1312.1622" + } + }, "dnxcore50": { } } } From e789e82d3da875ce71b1fc85e035e8f9dc7f9468 Mon Sep 17 00:00:00 2001 From: Ryan Nowak Date: Wed, 10 Jun 2015 12:24:22 -0700 Subject: [PATCH 005/296] Add package description --- src/Microsoft.AspNet.Antiforgery/project.json | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) diff --git a/src/Microsoft.AspNet.Antiforgery/project.json b/src/Microsoft.AspNet.Antiforgery/project.json index 10cb97d9a1..565854b5df 100644 --- a/src/Microsoft.AspNet.Antiforgery/project.json +++ b/src/Microsoft.AspNet.Antiforgery/project.json @@ -1,11 +1,6 @@ { + "description": "An antiforgery system for ASP.NET designed to generate and validate tokens to prevent Cross-Site Request Forgery attacks.", "version": "1.0.0-*", - "description": "", - "authors": [ "" ], - "tags": [ "" ], - "projectUrl": "", - "licenseUrl": "", - "dependencies": { "Microsoft.AspNet.DataProtection": "1.0.0-*", "Microsoft.AspNet.Http.Abstractions": "1.0.0-*", From 355a2b0a783f7bd4539340792785ec5d2b3ca837 Mon Sep 17 00:00:00 2001 From: Ryan Nowak Date: Wed, 10 Jun 2015 12:52:20 -0700 Subject: [PATCH 006/296] Add an IServiceCollection extensions --- .../AntiforgeryOptions.cs | 1 - .../ServiceCollectionExtensions.cs | 31 +++++++++++++++++++ 2 files changed, 31 insertions(+), 1 deletion(-) create mode 100644 src/Microsoft.AspNet.Antiforgery/ServiceCollectionExtensions.cs diff --git a/src/Microsoft.AspNet.Antiforgery/AntiforgeryOptions.cs b/src/Microsoft.AspNet.Antiforgery/AntiforgeryOptions.cs index 50f8f42b51..6906c02643 100644 --- a/src/Microsoft.AspNet.Antiforgery/AntiforgeryOptions.cs +++ b/src/Microsoft.AspNet.Antiforgery/AntiforgeryOptions.cs @@ -1,7 +1,6 @@ // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. -using System; using Microsoft.Framework.Internal; namespace Microsoft.AspNet.Antiforgery diff --git a/src/Microsoft.AspNet.Antiforgery/ServiceCollectionExtensions.cs b/src/Microsoft.AspNet.Antiforgery/ServiceCollectionExtensions.cs new file mode 100644 index 0000000000..59c278957b --- /dev/null +++ b/src/Microsoft.AspNet.Antiforgery/ServiceCollectionExtensions.cs @@ -0,0 +1,31 @@ +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System; +using Microsoft.AspNet.Antiforgery; +using Microsoft.Framework.Internal; + +namespace Microsoft.Framework.DependencyInjection +{ + public static class ServiceCollectionExtensions + { + public static IServiceCollection AddAntiforgery([NotNull] this IServiceCollection services) + { + services.AddDataProtection(); + + services.TryAdd(ServiceDescriptor.Singleton()); + services.TryAdd(ServiceDescriptor.Singleton()); + services.TryAdd( + ServiceDescriptor.Singleton()); + return services; + } + + public static IServiceCollection ConfigureAntiforgery( + [NotNull] this IServiceCollection services, + [NotNull] Action setupAction) + { + services.Configure(setupAction); + return services; + } + } +} From b474ef9b232b5c9604754eab104fdbed649ba1ed Mon Sep 17 00:00:00 2001 From: Ryan Nowak Date: Wed, 10 Jun 2015 14:53:44 -0700 Subject: [PATCH 007/296] Add sample of using Antiforgery outside of MVC --- .gitignore | 1 + Antiforgery.sln | 9 +++ global.json | 2 +- .../AntiforgerySample/AntiforgerySample.xproj | 19 ++++++ .../FormPostSampleMiddleware.cs | 67 +++++++++++++++++++ samples/AntiforgerySample/Startup.cs | 22 ++++++ samples/AntiforgerySample/project.json | 36 ++++++++++ samples/AntiforgerySample/wwwroot/Index.html | 10 +++ samples/AntiforgerySample/wwwroot/favicon.ico | 1 + .../ServiceCollectionExtensions.cs | 2 + src/Microsoft.AspNet.Antiforgery/project.json | 3 +- 11 files changed, 170 insertions(+), 2 deletions(-) create mode 100644 samples/AntiforgerySample/AntiforgerySample.xproj create mode 100644 samples/AntiforgerySample/FormPostSampleMiddleware.cs create mode 100644 samples/AntiforgerySample/Startup.cs create mode 100644 samples/AntiforgerySample/project.json create mode 100644 samples/AntiforgerySample/wwwroot/Index.html create mode 100644 samples/AntiforgerySample/wwwroot/favicon.ico diff --git a/.gitignore b/.gitignore index c2e1708217..304382499d 100644 --- a/.gitignore +++ b/.gitignore @@ -7,6 +7,7 @@ _ReSharper.*/ packages/ artifacts/ PublishProfiles/ +.vs/ *.user *.suo *.cache diff --git a/Antiforgery.sln b/Antiforgery.sln index b6b0239866..3074ae4f3d 100644 --- a/Antiforgery.sln +++ b/Antiforgery.sln @@ -11,6 +11,10 @@ Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "Microsoft.AspNet.Antiforger EndProject Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "Microsoft.AspNet.Antiforgery.Test", "test\Microsoft.AspNet.Antiforgery.Test\Microsoft.AspNet.Antiforgery.Test.xproj", "{415E83F8-6002-47E4-AA8E-CD5169C06F28}" EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "samples", "samples", "{D8C46ADF-E40A-4B48-ADE9-E1FA80466FE3}" +EndProject +Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "AntiforgerySample", "samples\AntiforgerySample\AntiforgerySample.xproj", "{AF9E0784-5EDB-494F-B46C-1A8DA785C49C}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -25,6 +29,10 @@ Global {415E83F8-6002-47E4-AA8E-CD5169C06F28}.Debug|Any CPU.Build.0 = Debug|Any CPU {415E83F8-6002-47E4-AA8E-CD5169C06F28}.Release|Any CPU.ActiveCfg = Release|Any CPU {415E83F8-6002-47E4-AA8E-CD5169C06F28}.Release|Any CPU.Build.0 = Release|Any CPU + {AF9E0784-5EDB-494F-B46C-1A8DA785C49C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {AF9E0784-5EDB-494F-B46C-1A8DA785C49C}.Debug|Any CPU.Build.0 = Debug|Any CPU + {AF9E0784-5EDB-494F-B46C-1A8DA785C49C}.Release|Any CPU.ActiveCfg = Release|Any CPU + {AF9E0784-5EDB-494F-B46C-1A8DA785C49C}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -32,5 +40,6 @@ Global GlobalSection(NestedProjects) = preSolution {46FB03FB-7A44-4106-BDDE-D6F5417544AB} = {71D070C4-B325-48F7-9F25-DD4E91C2BBCA} {415E83F8-6002-47E4-AA8E-CD5169C06F28} = {6EDD8B57-4DE8-4246-A6A3-47ECD92740B4} + {AF9E0784-5EDB-494F-B46C-1A8DA785C49C} = {D8C46ADF-E40A-4B48-ADE9-E1FA80466FE3} EndGlobalSection EndGlobal diff --git a/global.json b/global.json index 983ba0401e..feb51cb71d 100644 --- a/global.json +++ b/global.json @@ -1,3 +1,3 @@ { - "projects": ["src"] + "projects": ["src", "samples"] } diff --git a/samples/AntiforgerySample/AntiforgerySample.xproj b/samples/AntiforgerySample/AntiforgerySample.xproj new file mode 100644 index 0000000000..d6dbc6607b --- /dev/null +++ b/samples/AntiforgerySample/AntiforgerySample.xproj @@ -0,0 +1,19 @@ + + + + 14.0 + $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion) + + + + af9e0784-5edb-494f-b46c-1a8da785c49c + AntiforgerySample + ..\..\artifacts\obj\$(MSBuildProjectName) + ..\..\artifacts\bin\$(MSBuildProjectName)\ + + + 2.0 + 48542 + + + \ No newline at end of file diff --git a/samples/AntiforgerySample/FormPostSampleMiddleware.cs b/samples/AntiforgerySample/FormPostSampleMiddleware.cs new file mode 100644 index 0000000000..946513badd --- /dev/null +++ b/samples/AntiforgerySample/FormPostSampleMiddleware.cs @@ -0,0 +1,67 @@ +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System.Threading.Tasks; +using Microsoft.AspNet.Antiforgery; +using Microsoft.AspNet.Builder; +using Microsoft.AspNet.Http; +using Microsoft.Framework.OptionsModel; + +namespace AntiforgerySample +{ + public class FormPostSampleMiddleware + { + private readonly Antiforgery _antiforgery; + private readonly AntiforgeryOptions _options; + private readonly RequestDelegate _next; + + public FormPostSampleMiddleware( + RequestDelegate next, + Antiforgery antiforgery, + IOptions options) + { + _next = next; + _antiforgery = antiforgery; + _options = options.Options; + } + + public async Task Invoke(HttpContext context) + { + if (context.Request.Method == "GET") + { + var page = +@" + + + + + + +"; + + var tokenSet = _antiforgery.GetTokens(context, oldCookieToken: null); + context.Response.Cookies.Delete(_options.CookieName); + context.Response.Cookies.Append(_options.CookieName, tokenSet.CookieToken); + await context.Response.WriteAsync(string.Format(page, _options.FormFieldName, tokenSet.FormToken)); + } + else if (context.Request.Method == "POST") + { + // This will throw if invalid. + await _antiforgery.ValidateAsync(context); + + var page = +@" + +

Everything is fine

+ + +"; + await context.Response.WriteAsync(page); + } + else + { + await _next(context); + } + } + } +} diff --git a/samples/AntiforgerySample/Startup.cs b/samples/AntiforgerySample/Startup.cs new file mode 100644 index 0000000000..dadb75b86f --- /dev/null +++ b/samples/AntiforgerySample/Startup.cs @@ -0,0 +1,22 @@ +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using Microsoft.AspNet.Builder; +using Microsoft.Framework.DependencyInjection; + +namespace AntiforgerySample +{ + public class Startup + { + public void ConfigureServices(IServiceCollection services) + { + services.AddAntiforgery(); + } + + public void Configure(IApplicationBuilder app) + { + app.UseStaticFiles(); + app.UseMiddleware(); + } + } +} diff --git a/samples/AntiforgerySample/project.json b/samples/AntiforgerySample/project.json new file mode 100644 index 0000000000..34f061b15b --- /dev/null +++ b/samples/AntiforgerySample/project.json @@ -0,0 +1,36 @@ +{ + "webroot": "wwwroot", + "version": "1.0.0-*", + + "dependencies": { + "Microsoft.AspNet.Antiforgery": "1.0.0-*", + "Microsoft.AspNet.Http.Extensions": "1.0.0-*", + "Microsoft.AspNet.Server.IIS": "1.0.0-*", + "Microsoft.AspNet.Server.Kestrel": "1.0.0-*", + "Microsoft.AspNet.Server.WebListener": "1.0.0-*", + "Microsoft.AspNet.StaticFiles": "1.0.0-*" + }, + + "commands": { + "kestrel": "Microsoft.AspNet.Hosting --server Microsoft.AspNet.Server.Kestrel --server.urls http://localhost:5000", + "web": "Microsoft.AspNet.Hosting --server Microsoft.AspNet.Server.WebListener --server.urls http://localhost:5000" + }, + + "frameworks": { + "dnx451": { }, + "dnxcore50": { } + }, + + "publishExclude": [ + "node_modules", + "bower_components", + "**.xproj", + "**.user", + "**.vspscc" + ], + "exclude": [ + "wwwroot", + "node_modules", + "bower_components" + ] +} diff --git a/samples/AntiforgerySample/wwwroot/Index.html b/samples/AntiforgerySample/wwwroot/Index.html new file mode 100644 index 0000000000..94edeefc78 --- /dev/null +++ b/samples/AntiforgerySample/wwwroot/Index.html @@ -0,0 +1,10 @@ + + + + + Antiforgery Sample + + +

Hello, World!

+ + \ No newline at end of file diff --git a/samples/AntiforgerySample/wwwroot/favicon.ico b/samples/AntiforgerySample/wwwroot/favicon.ico new file mode 100644 index 0000000000..5f282702bb --- /dev/null +++ b/samples/AntiforgerySample/wwwroot/favicon.ico @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/src/Microsoft.AspNet.Antiforgery/ServiceCollectionExtensions.cs b/src/Microsoft.AspNet.Antiforgery/ServiceCollectionExtensions.cs index 59c278957b..22ad5f2202 100644 --- a/src/Microsoft.AspNet.Antiforgery/ServiceCollectionExtensions.cs +++ b/src/Microsoft.AspNet.Antiforgery/ServiceCollectionExtensions.cs @@ -12,9 +12,11 @@ namespace Microsoft.Framework.DependencyInjection public static IServiceCollection AddAntiforgery([NotNull] this IServiceCollection services) { services.AddDataProtection(); + services.AddWebEncoders(); services.TryAdd(ServiceDescriptor.Singleton()); services.TryAdd(ServiceDescriptor.Singleton()); + services.TryAdd(ServiceDescriptor.Scoped()); services.TryAdd( ServiceDescriptor.Singleton()); return services; diff --git a/src/Microsoft.AspNet.Antiforgery/project.json b/src/Microsoft.AspNet.Antiforgery/project.json index 565854b5df..d46ba0c895 100644 --- a/src/Microsoft.AspNet.Antiforgery/project.json +++ b/src/Microsoft.AspNet.Antiforgery/project.json @@ -7,7 +7,8 @@ "Microsoft.AspNet.WebUtilities": "1.0.0-*", "Microsoft.Framework.DependencyInjection.Abstractions": "1.0.0-*", "Microsoft.Framework.NotNullAttribute.Sources": { "type": "build", "version": "1.0.0-*" }, - "Microsoft.Framework.OptionsModel": "1.0.0-*" + "Microsoft.Framework.OptionsModel": "1.0.0-*", + "Microsoft.Framework.WebEncoders": "1.0.0-*" }, "frameworks" : { From fae6a8cf165e20d8338ac924ff9f4ed5f62d58f3 Mon Sep 17 00:00:00 2001 From: Hisham Abdullah Bin Ateya Date: Sat, 20 Jun 2015 23:34:50 +0300 Subject: [PATCH 008/296] Add AppVeyor, Travis build status --- README.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/README.md b/README.md index 2b53179d2d..8c911eb6f1 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,10 @@ Antiforgery === +AppVeyor: [![AppVeyor](https://ci.appveyor.com/api/projects/status/17l06rulbn328v4k/branch/dev?svg=true)](https://ci.appveyor.com/project/aspnetci/Antiforgery/branch/dev) + +Travis: [![Travis](https://travis-ci.org/aspnet/Antiforgery.svg?branch=dev)](https://travis-ci.org/aspnet/Antiforgery) + Antiforgery system for generating secure tokens to prevent Cross-Site Request Forgery attacks. This project is part of ASP.NET 5. You can find samples, documentation and getting started instructions for ASP.NET 5 at the [Home](https://github.com/aspnet/home) repo. From e8ac98ad5d0ea0b123edbadc259c1c1548c49201 Mon Sep 17 00:00:00 2001 From: Doug Bunting Date: Tue, 23 Jun 2015 10:46:47 -0700 Subject: [PATCH 009/296] Change hardcoded `bash` shebang to `env` - aspnet/Home#695 - support various `bash` installation locations - in particular, enable building on FreeBSD --- build.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/build.sh b/build.sh index c8cc2a72e1..203b034a33 100644 --- a/build.sh +++ b/build.sh @@ -1,4 +1,4 @@ -#!/bin/bash +#!/usr/bin/env bash if test `uname` = Darwin; then cachedir=~/Library/Caches/KBuild From 9eeb1de68f7aa04a9088bd849e21820b00ac4364 Mon Sep 17 00:00:00 2001 From: Ryan Nowak Date: Mon, 22 Jun 2015 16:15:30 -0700 Subject: [PATCH 010/296] Use DI for all Antiforgery services This change makes it possible to replace all of the various IAntiforgery*** extensibility points via DI. changes: - Move functionality out of AntiforgeryWorker into Antiforgery - Move services to DI (instead of constructed by Antiforgery) - Cleanup how application/cookie-name is computed - Merge IAntiforgeryTokenGenerator & IAntiforgeryTokenValidator - Unseal classes - Fix use of options in services - Misc test cleanup --- .../Antiforgery.cs | 199 ++++++-- .../AntiforgeryOptions.cs | 43 +- .../AntiforgeryOptionsSetup.cs | 41 ++ ...ovider.cs => AntiforgeryTokenGenerator.cs} | 26 +- .../AntiforgeryTokenSerializer.cs | 8 +- .../AntiforgeryTokenStore.cs | 41 +- .../IAntiforgeryTokenGenerator.cs | 15 +- .../IAntiforgeryTokenValidator.cs | 23 - .../Internal/AntiforgeryWorker.cs | 251 ---------- .../ServiceCollectionExtensions.cs | 17 +- .../AntiforgeryOptionsSetupTest.cs | 58 +++ ...orgeryWorkerTest.cs => AntiforgeryTest.cs} | 428 +++++++++--------- ...st.cs => AntiforgeryTokenGeneratorTest.cs} | 266 +++++------ .../AntiforgeryTokenSerializerTest.cs | 11 +- .../AntiforgeryTokenStoreTest.cs | 94 ++-- .../TestOptionsManager.cs | 27 ++ 16 files changed, 758 insertions(+), 790 deletions(-) create mode 100644 src/Microsoft.AspNet.Antiforgery/AntiforgeryOptionsSetup.cs rename src/Microsoft.AspNet.Antiforgery/{AntiforgeryTokenProvider.cs => AntiforgeryTokenGenerator.cs} (89%) delete mode 100644 src/Microsoft.AspNet.Antiforgery/IAntiforgeryTokenValidator.cs delete mode 100644 src/Microsoft.AspNet.Antiforgery/Internal/AntiforgeryWorker.cs create mode 100644 test/Microsoft.AspNet.Antiforgery.Test/AntiforgeryOptionsSetupTest.cs rename test/Microsoft.AspNet.Antiforgery.Test/{AntiforgeryWorkerTest.cs => AntiforgeryTest.cs} (58%) rename test/Microsoft.AspNet.Antiforgery.Test/{TokenProviderTest.cs => AntiforgeryTokenGeneratorTest.cs} (72%) create mode 100644 test/Microsoft.AspNet.Antiforgery.Test/TestOptionsManager.cs diff --git a/src/Microsoft.AspNet.Antiforgery/Antiforgery.cs b/src/Microsoft.AspNet.Antiforgery/Antiforgery.cs index ab2d2b7c31..b2c2838643 100644 --- a/src/Microsoft.AspNet.Antiforgery/Antiforgery.cs +++ b/src/Microsoft.AspNet.Antiforgery/Antiforgery.cs @@ -2,14 +2,9 @@ // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; -using System.Linq; -using System.Security.Cryptography; -using System.Text; +using System.Diagnostics; using System.Threading.Tasks; -using Microsoft.AspNet.Antiforgery.Internal; -using Microsoft.AspNet.DataProtection; using Microsoft.AspNet.Http; -using Microsoft.AspNet.WebUtilities; using Microsoft.Framework.Internal; using Microsoft.Framework.OptionsModel; using Microsoft.Framework.WebEncoders; @@ -20,27 +15,26 @@ namespace Microsoft.AspNet.Antiforgery /// Provides access to the anti-forgery system, which provides protection against /// Cross-site Request Forgery (XSRF, also called CSRF) attacks. /// - public sealed class Antiforgery + public class Antiforgery { - private static readonly string _purpose = "Microsoft.AspNet.Antiforgery.AntiforgeryToken.v1"; - private readonly AntiforgeryWorker _worker; + private readonly IHtmlEncoder _htmlEncoder; + private readonly AntiforgeryOptions _options; + private readonly IAntiforgeryTokenGenerator _tokenGenerator; + private readonly IAntiforgeryTokenSerializer _tokenSerializer; + private readonly IAntiforgeryTokenStore _tokenStore; public Antiforgery( - [NotNull] IClaimUidExtractor claimUidExtractor, - [NotNull] IDataProtectionProvider dataProtectionProvider, - [NotNull] IAntiforgeryAdditionalDataProvider additionalDataProvider, - [NotNull] IOptions AntiforgeryOptionsAccessor, - [NotNull] IHtmlEncoder htmlEncoder, - [NotNull] IOptions dataProtectionOptions) + IOptions antiforgeryOptionsAccessor, + IAntiforgeryTokenGenerator tokenGenerator, + IAntiforgeryTokenSerializer tokenSerializer, + IAntiforgeryTokenStore tokenStore, + IHtmlEncoder htmlEncoder) { - var AntiforgeryOptions = AntiforgeryOptionsAccessor.Options; - var applicationId = dataProtectionOptions.Options.ApplicationDiscriminator ?? string.Empty; - AntiforgeryOptions.CookieName = AntiforgeryOptions.CookieName ?? ComputeCookieName(applicationId); - - var serializer = new AntiforgeryTokenSerializer(dataProtectionProvider.CreateProtector(_purpose)); - var tokenStore = new AntiforgeryTokenStore(AntiforgeryOptions, serializer); - var tokenProvider = new AntiforgeryTokenProvider(AntiforgeryOptions, claimUidExtractor, additionalDataProvider); - _worker = new AntiforgeryWorker(serializer, AntiforgeryOptions, tokenStore, tokenProvider, tokenProvider, htmlEncoder); + _options = antiforgeryOptionsAccessor.Options; + _tokenGenerator = tokenGenerator; + _tokenSerializer = tokenSerializer; + _tokenStore = tokenStore; + _htmlEncoder = htmlEncoder; } /// @@ -56,8 +50,21 @@ namespace Microsoft.AspNet.Antiforgery /// public string GetHtml([NotNull] HttpContext context) { - var html = _worker.GetFormInputElement(context); - return html; + CheckSSLConfig(context); + + var cookieToken = GetCookieTokenDoesNotThrow(context); + var tokenSet = GetTokens(context, cookieToken); + cookieToken = tokenSet.CookieToken; + var formToken = tokenSet.FormToken; + + SaveCookieTokenAndHeader(context, cookieToken); + + var inputTag = string.Format( + "", + _htmlEncoder.HtmlEncode(_options.FormFieldName), + _htmlEncoder.HtmlEncode("hidden"), + _htmlEncoder.HtmlEncode(_tokenSerializer.Serialize(formToken))); + return inputTag; } /// @@ -82,7 +89,14 @@ namespace Microsoft.AspNet.Antiforgery // must persist this value in the form of a response cookie, and the existing cookie value // should be discarded. If this value is null when the method completes, the existing // cookie value was valid and needn't be modified. - return _worker.GetTokens(context, oldCookieToken); + CheckSSLConfig(context); + + var deserializedcookieToken = DeserializeTokenDoesNotThrow(oldCookieToken); + var tokenSet = GetTokens(context, deserializedcookieToken); + + var serializedCookieToken = Serialize(tokenSet.CookieToken); + var serializedFormToken = Serialize(tokenSet.FormToken); + return new AntiforgeryTokenSet(serializedFormToken, serializedCookieToken); } /// @@ -92,7 +106,14 @@ namespace Microsoft.AspNet.Antiforgery /// The HTTP context associated with the current call. public async Task ValidateAsync([NotNull] HttpContext context) { - await _worker.ValidateAsync(context); + CheckSSLConfig(context); + + // Extract cookie & form tokens + var cookieToken = _tokenStore.GetCookieToken(context); + var formToken = await _tokenStore.GetFormTokenAsync(context); + + // Validate + _tokenGenerator.ValidateTokens(context, cookieToken, formToken); } /// @@ -103,7 +124,17 @@ namespace Microsoft.AspNet.Antiforgery /// The token that was supplied in the request form body. public void Validate([NotNull] HttpContext context, string cookieToken, string formToken) { - _worker.Validate(context, cookieToken, formToken); + CheckSSLConfig(context); + + // Extract cookie & form tokens + var deserializedCookieToken = DeserializeToken(cookieToken); + var deserializedFormToken = DeserializeToken(formToken); + + // Validate + _tokenGenerator.ValidateTokens( + context, + deserializedCookieToken, + deserializedFormToken); } /// @@ -123,17 +154,117 @@ namespace Microsoft.AspNet.Antiforgery /// The HTTP context associated with the current call. public void SetCookieTokenAndHeader([NotNull] HttpContext context) { - _worker.SetCookieTokenAndHeader(context); + CheckSSLConfig(context); + + var cookieToken = GetCookieTokenDoesNotThrow(context); + cookieToken = ValidateAndGenerateNewCookieToken(cookieToken); + + SaveCookieTokenAndHeader(context, cookieToken); } - private string ComputeCookieName(string applicationId) + // This method returns null if oldCookieToken is valid. + private AntiforgeryToken ValidateAndGenerateNewCookieToken(AntiforgeryToken cookieToken) { - using (var sha256 = SHA256.Create()) + if (!_tokenGenerator.IsCookieTokenValid(cookieToken)) { - var hash = sha256.ComputeHash(Encoding.UTF8.GetBytes(applicationId)); - var subHash = hash.Take(8).ToArray(); - return WebEncoders.Base64UrlEncode(subHash); + // Need to make sure we're always operating with a good cookie token. + var newCookieToken = _tokenGenerator.GenerateCookieToken(); + Debug.Assert(_tokenGenerator.IsCookieTokenValid(newCookieToken)); + return newCookieToken; } + + return null; + } + + private void SaveCookieTokenAndHeader( + [NotNull] HttpContext httpContext, + AntiforgeryToken cookieToken) + { + if (cookieToken != null) + { + // Persist the new cookie if it is not null. + _tokenStore.SaveCookieToken(httpContext, cookieToken); + } + + if (!_options.SuppressXFrameOptionsHeader) + { + // Adding X-Frame-Options header to prevent ClickJacking. See + // http://tools.ietf.org/html/draft-ietf-websec-x-frame-options-10 + // for more information. + httpContext.Response.Headers.Set("X-Frame-Options", "SAMEORIGIN"); + } + } + + private void CheckSSLConfig(HttpContext httpContext) + { + if (_options.RequireSSL && !httpContext.Request.IsHttps) + { + throw new InvalidOperationException(Resources.AntiforgeryWorker_RequireSSL); + } + } + + private AntiforgeryToken DeserializeToken(string serializedToken) + { + return (!string.IsNullOrEmpty(serializedToken)) + ? _tokenSerializer.Deserialize(serializedToken) + : null; + } + + private AntiforgeryToken DeserializeTokenDoesNotThrow(string serializedToken) + { + try + { + return DeserializeToken(serializedToken); + } + catch + { + // ignore failures since we'll just generate a new token + return null; + } + } + + private AntiforgeryToken GetCookieTokenDoesNotThrow(HttpContext httpContext) + { + try + { + return _tokenStore.GetCookieToken(httpContext); + } + catch + { + // ignore failures since we'll just generate a new token + return null; + } + } + + private AntiforgeryTokenSetInternal GetTokens(HttpContext httpContext, AntiforgeryToken cookieToken) + { + var newCookieToken = ValidateAndGenerateNewCookieToken(cookieToken); + if (newCookieToken != null) + { + cookieToken = newCookieToken; + } + var formToken = _tokenGenerator.GenerateFormToken( + httpContext, + cookieToken); + + return new AntiforgeryTokenSetInternal() + { + // Note : The new cookie would be null if the old cookie is valid. + CookieToken = newCookieToken, + FormToken = formToken + }; + } + + private string Serialize(AntiforgeryToken token) + { + return (token != null) ? _tokenSerializer.Serialize(token) : null; + } + + private class AntiforgeryTokenSetInternal + { + public AntiforgeryToken FormToken { get; set; } + + public AntiforgeryToken CookieToken { get; set; } } } } \ No newline at end of file diff --git a/src/Microsoft.AspNet.Antiforgery/AntiforgeryOptions.cs b/src/Microsoft.AspNet.Antiforgery/AntiforgeryOptions.cs index 6906c02643..d8db3df2cb 100644 --- a/src/Microsoft.AspNet.Antiforgery/AntiforgeryOptions.cs +++ b/src/Microsoft.AspNet.Antiforgery/AntiforgeryOptions.cs @@ -12,9 +12,6 @@ namespace Microsoft.AspNet.Antiforgery { private const string AntiforgeryTokenFieldName = "__RequestVerificationToken"; - private string _cookieName; - private string _formFieldName = AntiforgeryTokenFieldName; - /// /// Specifies the name of the cookie that is used by the anti-forgery /// system. @@ -23,47 +20,19 @@ namespace Microsoft.AspNet.Antiforgery /// If an explicit name is not provided, the system will automatically /// generate a name. /// - public string CookieName - { - get - { - return _cookieName; - } - - [param: NotNull] - set - { - _cookieName = value; - } - } + public string CookieName { get; [param: NotNull] set; } /// /// Specifies the name of the anti-forgery token field that is used by the anti-forgery system. /// - public string FormFieldName - { - get - { - return _formFieldName; - } - - [param: NotNull] - set - { - _formFieldName = value; - } - } + public string FormFieldName { get; [param: NotNull] set; } = AntiforgeryTokenFieldName; /// /// Specifies whether SSL is required for the anti-forgery system /// to operate. If this setting is 'true' and a non-SSL request /// comes into the system, all anti-forgery APIs will fail. /// - public bool RequireSSL - { - get; - set; - } + public bool RequireSSL { get; set; } /// /// Specifies whether to suppress the generation of X-Frame-Options header @@ -71,10 +40,6 @@ namespace Microsoft.AspNet.Antiforgery /// header is generated with the value SAMEORIGIN. If this setting is 'true', /// the X-Frame-Options header will not be generated for the response. /// - public bool SuppressXFrameOptionsHeader - { - get; - set; - } + public bool SuppressXFrameOptionsHeader { get; set; } } } \ No newline at end of file diff --git a/src/Microsoft.AspNet.Antiforgery/AntiforgeryOptionsSetup.cs b/src/Microsoft.AspNet.Antiforgery/AntiforgeryOptionsSetup.cs new file mode 100644 index 0000000000..76030662ad --- /dev/null +++ b/src/Microsoft.AspNet.Antiforgery/AntiforgeryOptionsSetup.cs @@ -0,0 +1,41 @@ +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System.Linq; +using System.Security.Cryptography; +using System.Text; +using Microsoft.AspNet.DataProtection; +using Microsoft.AspNet.WebUtilities; +using Microsoft.Framework.OptionsModel; + +namespace Microsoft.AspNet.Antiforgery +{ + public class AntiforgeryOptionsSetup : ConfigureOptions + { + public AntiforgeryOptionsSetup(IOptions dataProtectionOptionsAccessor) + : base((options) => ConfigureOptions(options, dataProtectionOptionsAccessor.Options)) + { + // We want this to run after any user setups to compute a default name if needed. + Order = 10000; + } + + public static void ConfigureOptions(AntiforgeryOptions options, DataProtectionOptions dataProtectionOptions) + { + if (options.CookieName == null) + { + var applicationId = dataProtectionOptions.ApplicationDiscriminator ?? string.Empty; + options.CookieName = ComputeCookieName(applicationId); + } + } + + private static string ComputeCookieName(string applicationId) + { + using (var sha256 = SHA256.Create()) + { + var hash = sha256.ComputeHash(Encoding.UTF8.GetBytes(applicationId)); + var subHash = hash.Take(8).ToArray(); + return WebEncoders.Base64UrlEncode(subHash); + } + } + } +} diff --git a/src/Microsoft.AspNet.Antiforgery/AntiforgeryTokenProvider.cs b/src/Microsoft.AspNet.Antiforgery/AntiforgeryTokenGenerator.cs similarity index 89% rename from src/Microsoft.AspNet.Antiforgery/AntiforgeryTokenProvider.cs rename to src/Microsoft.AspNet.Antiforgery/AntiforgeryTokenGenerator.cs index cdb02b986f..493e4a3495 100644 --- a/src/Microsoft.AspNet.Antiforgery/AntiforgeryTokenProvider.cs +++ b/src/Microsoft.AspNet.Antiforgery/AntiforgeryTokenGenerator.cs @@ -5,21 +5,22 @@ using System; using System.Diagnostics; using System.Security.Claims; using Microsoft.AspNet.Http; +using Microsoft.Framework.OptionsModel; namespace Microsoft.AspNet.Antiforgery { - public sealed class AntiforgeryTokenProvider : IAntiforgeryTokenValidator, IAntiforgeryTokenGenerator + public class AntiforgeryTokenGenerator : IAntiforgeryTokenGenerator { private readonly IClaimUidExtractor _claimUidExtractor; - private readonly AntiforgeryOptions _config; + private readonly AntiforgeryOptions _options; private readonly IAntiforgeryAdditionalDataProvider _additionalDataProvider; - internal AntiforgeryTokenProvider( - AntiforgeryOptions config, + public AntiforgeryTokenGenerator( + IOptions optionsAccessor, IClaimUidExtractor claimUidExtractor, IAntiforgeryAdditionalDataProvider additionalDataProvider) { - _config = config; + _options = optionsAccessor.Options; _claimUidExtractor = claimUidExtractor; _additionalDataProvider = additionalDataProvider; } @@ -33,9 +34,9 @@ namespace Microsoft.AspNet.Antiforgery }; } - public AntiforgeryToken GenerateFormToken(HttpContext httpContext, - ClaimsIdentity identity, - AntiforgeryToken cookieToken) + public AntiforgeryToken GenerateFormToken( + HttpContext httpContext, + AntiforgeryToken cookieToken) { Debug.Assert(IsCookieTokenValid(cookieToken)); @@ -46,6 +47,7 @@ namespace Microsoft.AspNet.Antiforgery }; var isIdentityAuthenticated = false; + var identity = httpContext.User?.Identity as ClaimsIdentity; // populate Username and ClaimUid if (identity != null && identity.IsAuthenticated) @@ -84,7 +86,6 @@ namespace Microsoft.AspNet.Antiforgery public void ValidateTokens( HttpContext httpContext, - ClaimsIdentity identity, AntiforgeryToken sessionToken, AntiforgeryToken fieldToken) { @@ -92,19 +93,19 @@ namespace Microsoft.AspNet.Antiforgery if (sessionToken == null) { throw new InvalidOperationException( - Resources.FormatAntiforgeryToken_CookieMissing(_config.CookieName)); + Resources.FormatAntiforgeryToken_CookieMissing(_options.CookieName)); } if (fieldToken == null) { throw new InvalidOperationException( - Resources.FormatAntiforgeryToken_FormFieldMissing(_config.FormFieldName)); + Resources.FormatAntiforgeryToken_FormFieldMissing(_options.FormFieldName)); } // Do the tokens have the correct format? if (!sessionToken.IsSessionToken || fieldToken.IsSessionToken) { throw new InvalidOperationException( - Resources.FormatAntiforgeryToken_TokensSwapped(_config.CookieName, _config.FormFieldName)); + Resources.FormatAntiforgeryToken_TokensSwapped(_options.CookieName, _options.FormFieldName)); } // Are the security tokens embedded in each incoming token identical? @@ -117,6 +118,7 @@ namespace Microsoft.AspNet.Antiforgery var currentUsername = string.Empty; BinaryBlob currentClaimUid = null; + var identity = httpContext.User?.Identity as ClaimsIdentity; if (identity != null && identity.IsAuthenticated) { currentClaimUid = GetClaimUidBlob(_claimUidExtractor.ExtractClaimUid(identity)); diff --git a/src/Microsoft.AspNet.Antiforgery/AntiforgeryTokenSerializer.cs b/src/Microsoft.AspNet.Antiforgery/AntiforgeryTokenSerializer.cs index 9022f77b13..f3d79844f7 100644 --- a/src/Microsoft.AspNet.Antiforgery/AntiforgeryTokenSerializer.cs +++ b/src/Microsoft.AspNet.Antiforgery/AntiforgeryTokenSerializer.cs @@ -9,14 +9,16 @@ using Microsoft.Framework.Internal; namespace Microsoft.AspNet.Antiforgery { - public sealed class AntiforgeryTokenSerializer : IAntiforgeryTokenSerializer + public class AntiforgeryTokenSerializer : IAntiforgeryTokenSerializer { + private static readonly string Purpose = "Microsoft.AspNet.Antiforgery.AntiforgeryToken.v1"; + private readonly IDataProtector _cryptoSystem; private const byte TokenVersion = 0x01; - public AntiforgeryTokenSerializer([NotNull] IDataProtector cryptoSystem) + public AntiforgeryTokenSerializer([NotNull] IDataProtectionProvider provider) { - _cryptoSystem = cryptoSystem; + _cryptoSystem = provider.CreateProtector(Purpose); } public AntiforgeryToken Deserialize(string serializedToken) diff --git a/src/Microsoft.AspNet.Antiforgery/AntiforgeryTokenStore.cs b/src/Microsoft.AspNet.Antiforgery/AntiforgeryTokenStore.cs index e288c1c786..ecf17ad0a7 100644 --- a/src/Microsoft.AspNet.Antiforgery/AntiforgeryTokenStore.cs +++ b/src/Microsoft.AspNet.Antiforgery/AntiforgeryTokenStore.cs @@ -6,74 +6,77 @@ using System.Threading.Tasks; using Microsoft.AspNet.Http; using Microsoft.Framework.DependencyInjection; using Microsoft.Framework.Internal; +using Microsoft.Framework.OptionsModel; namespace Microsoft.AspNet.Antiforgery { // Saves anti-XSRF tokens split between HttpRequest.Cookies and HttpRequest.Form - public sealed class AntiforgeryTokenStore : IAntiforgeryTokenStore + public class AntiforgeryTokenStore : IAntiforgeryTokenStore { - private readonly AntiforgeryOptions _config; - private readonly IAntiforgeryTokenSerializer _serializer; + private readonly AntiforgeryOptions _options; + private readonly IAntiforgeryTokenSerializer _tokenSerializer; - public AntiforgeryTokenStore([NotNull] AntiforgeryOptions config, - [NotNull] IAntiforgeryTokenSerializer serializer) + public AntiforgeryTokenStore( + [NotNull] IOptions optionsAccessor, + [NotNull] IAntiforgeryTokenSerializer tokenSerializer) { - _config = config; - _serializer = serializer; + _options = optionsAccessor.Options; + _tokenSerializer = tokenSerializer; } public AntiforgeryToken GetCookieToken(HttpContext httpContext) { - var contextAccessor = - httpContext.RequestServices.GetRequiredService(); + var services = httpContext.RequestServices; + var contextAccessor = services.GetRequiredService(); if (contextAccessor.Value != null) { return contextAccessor.Value.CookieToken; } - var requestCookie = httpContext.Request.Cookies[_config.CookieName]; + var requestCookie = httpContext.Request.Cookies[_options.CookieName]; if (string.IsNullOrEmpty(requestCookie)) { // unable to find the cookie. return null; } - return _serializer.Deserialize(requestCookie); + return _tokenSerializer.Deserialize(requestCookie); } public async Task GetFormTokenAsync(HttpContext httpContext) { var form = await httpContext.Request.ReadFormAsync(); - var value = form[_config.FormFieldName]; + var value = form[_options.FormFieldName]; if (string.IsNullOrEmpty(value)) { // did not exist return null; } - return _serializer.Deserialize(value); + return _tokenSerializer.Deserialize(value); } public void SaveCookieToken(HttpContext httpContext, AntiforgeryToken token) { // Add the cookie to the request based context. // This is useful if the cookie needs to be reloaded in the context of the same request. - var contextAccessor = - httpContext.RequestServices.GetRequiredService(); + + var services = httpContext.RequestServices; + var contextAccessor = services.GetRequiredService(); Debug.Assert(contextAccessor.Value == null, "AntiforgeryContext should be set only once per request."); contextAccessor.Value = new AntiforgeryContext() { CookieToken = token }; - var serializedToken = _serializer.Serialize(token); + var serializedToken = _tokenSerializer.Serialize(token); var options = new CookieOptions() { HttpOnly = true }; - // Note: don't use "newCookie.Secure = _config.RequireSSL;" since the default + // Note: don't use "newCookie.Secure = _options.RequireSSL;" since the default // value of newCookie.Secure is poulated out of band. - if (_config.RequireSSL) + if (_options.RequireSSL) { options.Secure = true; } - httpContext.Response.Cookies.Append(_config.CookieName, serializedToken, options); + httpContext.Response.Cookies.Append(_options.CookieName, serializedToken, options); } } } \ No newline at end of file diff --git a/src/Microsoft.AspNet.Antiforgery/IAntiforgeryTokenGenerator.cs b/src/Microsoft.AspNet.Antiforgery/IAntiforgeryTokenGenerator.cs index 87d936dec3..8ca4510bf7 100644 --- a/src/Microsoft.AspNet.Antiforgery/IAntiforgeryTokenGenerator.cs +++ b/src/Microsoft.AspNet.Antiforgery/IAntiforgeryTokenGenerator.cs @@ -6,7 +6,9 @@ using Microsoft.AspNet.Http; namespace Microsoft.AspNet.Antiforgery { - // Provides configuration information about the anti-forgery system. + /// + /// Generates and validates antiforgery tokens. + /// public interface IAntiforgeryTokenGenerator { // Generates a new random cookie token. @@ -16,7 +18,16 @@ namespace Microsoft.AspNet.Antiforgery // The incoming cookie token must be valid. AntiforgeryToken GenerateFormToken( HttpContext httpContext, - ClaimsIdentity identity, AntiforgeryToken cookieToken); + + // Determines whether an existing cookie token is valid (well-formed). + // If it is not, the caller must call GenerateCookieToken() before calling GenerateFormToken(). + bool IsCookieTokenValid(AntiforgeryToken cookieToken); + + // Validates a (cookie, form) token pair. + void ValidateTokens( + HttpContext httpContext, + AntiforgeryToken cookieToken, + AntiforgeryToken formToken); } } \ No newline at end of file diff --git a/src/Microsoft.AspNet.Antiforgery/IAntiforgeryTokenValidator.cs b/src/Microsoft.AspNet.Antiforgery/IAntiforgeryTokenValidator.cs deleted file mode 100644 index ed75a9de45..0000000000 --- a/src/Microsoft.AspNet.Antiforgery/IAntiforgeryTokenValidator.cs +++ /dev/null @@ -1,23 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System.Security.Claims; -using Microsoft.AspNet.Http; - -namespace Microsoft.AspNet.Antiforgery -{ - // Provides an abstraction around something that can validate anti-XSRF tokens - public interface IAntiforgeryTokenValidator - { - // Determines whether an existing cookie token is valid (well-formed). - // If it is not, the caller must call GenerateCookieToken() before calling GenerateFormToken(). - bool IsCookieTokenValid(AntiforgeryToken cookieToken); - - // Validates a (cookie, form) token pair. - void ValidateTokens( - HttpContext httpContext, - ClaimsIdentity identity, - AntiforgeryToken cookieToken, - AntiforgeryToken formToken); - } -} \ No newline at end of file diff --git a/src/Microsoft.AspNet.Antiforgery/Internal/AntiforgeryWorker.cs b/src/Microsoft.AspNet.Antiforgery/Internal/AntiforgeryWorker.cs deleted file mode 100644 index ac4dd9e0b8..0000000000 --- a/src/Microsoft.AspNet.Antiforgery/Internal/AntiforgeryWorker.cs +++ /dev/null @@ -1,251 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Diagnostics; -using System.Security.Claims; -using System.Threading.Tasks; -using Microsoft.AspNet.Http; -using Microsoft.Framework.Internal; -using Microsoft.Framework.WebEncoders; - -namespace Microsoft.AspNet.Antiforgery.Internal -{ - public sealed class AntiforgeryWorker - { - private readonly AntiforgeryOptions _config; - private readonly IAntiforgeryTokenSerializer _serializer; - private readonly IAntiforgeryTokenStore _tokenStore; - private readonly IAntiforgeryTokenValidator _validator; - private readonly IAntiforgeryTokenGenerator _generator; - private readonly IHtmlEncoder _htmlEncoder; - - public AntiforgeryWorker( - [NotNull] IAntiforgeryTokenSerializer serializer, - [NotNull] AntiforgeryOptions config, - [NotNull] IAntiforgeryTokenStore tokenStore, - [NotNull] IAntiforgeryTokenGenerator generator, - [NotNull] IAntiforgeryTokenValidator validator, - [NotNull] IHtmlEncoder htmlEncoder) - { - _serializer = serializer; - _config = config; - _tokenStore = tokenStore; - _generator = generator; - _validator = validator; - _htmlEncoder = htmlEncoder; - } - - private void CheckSSLConfig(HttpContext httpContext) - { - if (_config.RequireSSL && !httpContext.Request.IsHttps) - { - throw new InvalidOperationException(Resources.AntiforgeryWorker_RequireSSL); - } - } - - private AntiforgeryToken DeserializeToken(string serializedToken) - { - return (!string.IsNullOrEmpty(serializedToken)) - ? _serializer.Deserialize(serializedToken) - : null; - } - - private AntiforgeryToken DeserializeTokenDoesNotThrow(string serializedToken) - { - try - { - return DeserializeToken(serializedToken); - } - catch - { - // ignore failures since we'll just generate a new token - return null; - } - } - - private static ClaimsIdentity ExtractIdentity(HttpContext httpContext) - { - if (httpContext != null) - { - var user = httpContext.User; - - if (user != null) - { - // We only support ClaimsIdentity. - return user.Identity as ClaimsIdentity; - } - } - - return null; - } - - private AntiforgeryToken GetCookieTokenDoesNotThrow(HttpContext httpContext) - { - try - { - return _tokenStore.GetCookieToken(httpContext); - } - catch - { - // ignore failures since we'll just generate a new token - return null; - } - } - - // [ ENTRY POINT ] - // Generates an anti-XSRF token pair for the current user. The return - // value is the hidden input form element that should be rendered in - // the
. This method has a side effect: it may set a response - // cookie. - public string GetFormInputElement([NotNull] HttpContext httpContext) - { - CheckSSLConfig(httpContext); - - var cookieToken = GetCookieTokenDoesNotThrow(httpContext); - var tokenSet = GetTokens(httpContext, cookieToken); - cookieToken = tokenSet.CookieToken; - var formToken = tokenSet.FormToken; - - SaveCookieTokenAndHeader(httpContext, cookieToken); - - var inputTag = string.Format( - "", - _htmlEncoder.HtmlEncode(_config.FormFieldName), - _htmlEncoder.HtmlEncode("hidden"), - _htmlEncoder.HtmlEncode(_serializer.Serialize(formToken))); - return inputTag; - } - - // [ ENTRY POINT ] - // Generates a (cookie, form) serialized token pair for the current user. - // The caller may specify an existing cookie value if one exists. If the - // 'new cookie value' out param is non-null, the caller *must* persist - // the new value to cookie storage since the original value was null or - // invalid. This method is side-effect free. - public AntiforgeryTokenSet GetTokens([NotNull] HttpContext httpContext, string cookieToken) - { - CheckSSLConfig(httpContext); - var deSerializedcookieToken = DeserializeTokenDoesNotThrow(cookieToken); - var tokenSet = GetTokens(httpContext, deSerializedcookieToken); - - var serializedCookieToken = Serialize(tokenSet.CookieToken); - var serializedFormToken = Serialize(tokenSet.FormToken); - return new AntiforgeryTokenSet(serializedFormToken, serializedCookieToken); - } - - private AntiforgeryTokenSetInternal GetTokens(HttpContext httpContext, AntiforgeryToken cookieToken) - { - var newCookieToken = ValidateAndGenerateNewCookieToken(cookieToken); - if (newCookieToken != null) - { - cookieToken = newCookieToken; - } - var formToken = _generator.GenerateFormToken( - httpContext, - ExtractIdentity(httpContext), - cookieToken); - - return new AntiforgeryTokenSetInternal() - { - // Note : The new cookie would be null if the old cookie is valid. - CookieToken = newCookieToken, - FormToken = formToken - }; - } - - private string Serialize(AntiforgeryToken token) - { - return (token != null) ? _serializer.Serialize(token) : null; - } - - // [ ENTRY POINT ] - // Given an HttpContext, validates that the anti-XSRF tokens contained - // in the cookies & form are OK for this request. - public async Task ValidateAsync([NotNull] HttpContext httpContext) - { - CheckSSLConfig(httpContext); - - // Extract cookie & form tokens - var cookieToken = _tokenStore.GetCookieToken(httpContext); - var formToken = await _tokenStore.GetFormTokenAsync(httpContext); - - // Validate - _validator.ValidateTokens(httpContext, ExtractIdentity(httpContext), cookieToken, formToken); - } - - // [ ENTRY POINT ] - // Given the serialized string representations of a cookie & form token, - // validates that the pair is OK for this request. - public void Validate([NotNull] HttpContext httpContext, string cookieToken, string formToken) - { - CheckSSLConfig(httpContext); - - // Extract cookie & form tokens - var deserializedCookieToken = DeserializeToken(cookieToken); - var deserializedFormToken = DeserializeToken(formToken); - - // Validate - _validator.ValidateTokens( - httpContext, - ExtractIdentity(httpContext), - deserializedCookieToken, - deserializedFormToken); - } - - - /// - /// Generates and sets an anti-forgery cookie if one is not available or not valid. Also sets response headers. - /// - /// The HTTP context associated with the current call. - public void SetCookieTokenAndHeader([NotNull] HttpContext httpContext) - { - CheckSSLConfig(httpContext); - - var cookieToken = GetCookieTokenDoesNotThrow(httpContext); - cookieToken = ValidateAndGenerateNewCookieToken(cookieToken); - - SaveCookieTokenAndHeader(httpContext, cookieToken); - } - - // This method returns null if oldCookieToken is valid. - private AntiforgeryToken ValidateAndGenerateNewCookieToken(AntiforgeryToken cookieToken) - { - if (!_validator.IsCookieTokenValid(cookieToken)) - { - // Need to make sure we're always operating with a good cookie token. - var newCookieToken = _generator.GenerateCookieToken(); - Debug.Assert(_validator.IsCookieTokenValid(newCookieToken)); - return newCookieToken; - } - - return null; - } - - private void SaveCookieTokenAndHeader( - [NotNull] HttpContext httpContext, - AntiforgeryToken cookieToken) - { - if (cookieToken != null) - { - // Persist the new cookie if it is not null. - _tokenStore.SaveCookieToken(httpContext, cookieToken); - } - - if (!_config.SuppressXFrameOptionsHeader) - { - // Adding X-Frame-Options header to prevent ClickJacking. See - // http://tools.ietf.org/html/draft-ietf-websec-x-frame-options-10 - // for more information. - httpContext.Response.Headers.Set("X-Frame-Options", "SAMEORIGIN"); - } - } - - private class AntiforgeryTokenSetInternal - { - public AntiforgeryToken FormToken { get; set; } - - public AntiforgeryToken CookieToken { get; set; } - } - } -} \ No newline at end of file diff --git a/src/Microsoft.AspNet.Antiforgery/ServiceCollectionExtensions.cs b/src/Microsoft.AspNet.Antiforgery/ServiceCollectionExtensions.cs index 22ad5f2202..f6dcee30e1 100644 --- a/src/Microsoft.AspNet.Antiforgery/ServiceCollectionExtensions.cs +++ b/src/Microsoft.AspNet.Antiforgery/ServiceCollectionExtensions.cs @@ -4,6 +4,7 @@ using System; using Microsoft.AspNet.Antiforgery; using Microsoft.Framework.Internal; +using Microsoft.Framework.OptionsModel; namespace Microsoft.Framework.DependencyInjection { @@ -14,11 +15,17 @@ namespace Microsoft.Framework.DependencyInjection services.AddDataProtection(); services.AddWebEncoders(); - services.TryAdd(ServiceDescriptor.Singleton()); - services.TryAdd(ServiceDescriptor.Singleton()); - services.TryAdd(ServiceDescriptor.Scoped()); - services.TryAdd( - ServiceDescriptor.Singleton()); + // Don't overwrite any options setups that a user may have added. + services.TryAddEnumerable( + ServiceDescriptor.Transient, AntiforgeryOptionsSetup>()); + + services.TryAddSingleton(); + services.TryAddSingleton(); + services.TryAddSingleton(); + services.TryAddSingleton(); + services.TryAddSingleton(); + services.TryAddScoped(); + services.TryAddSingleton(); return services; } diff --git a/test/Microsoft.AspNet.Antiforgery.Test/AntiforgeryOptionsSetupTest.cs b/test/Microsoft.AspNet.Antiforgery.Test/AntiforgeryOptionsSetupTest.cs new file mode 100644 index 0000000000..68bd517548 --- /dev/null +++ b/test/Microsoft.AspNet.Antiforgery.Test/AntiforgeryOptionsSetupTest.cs @@ -0,0 +1,58 @@ +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using Microsoft.Framework.DependencyInjection; +using Microsoft.Framework.OptionsModel; +using Xunit; + +namespace Microsoft.AspNet.Antiforgery +{ + public class AntiforgeryOptionsSetupTest + { + [Theory] + [InlineData("HelloWorldApp", "tGmK82_ckDw")] + [InlineData("TodoCalendar", "7mK1hBEBwYs")] + public void AntiforgeryOptionsSetup_SetsDefaultCookieName_BasedOnApplicationId( + string applicationId, + string expectedCookieName) + { + // Arrange + var serviceCollection = new ServiceCollection(); + serviceCollection.AddAntiforgery(); + serviceCollection.ConfigureDataProtection(o => o.SetApplicationName(applicationId)); + + var services = serviceCollection.BuildServiceProvider(); + var options = services.GetRequiredService>(); + + // Act + var cookieName = options.Options.CookieName; + + // Assert + Assert.Equal(expectedCookieName, cookieName); + } + + [Fact] + public void AntiforgeryOptionsSetup_UserOptionsSetup_CanSetCookieName() + { + // Arrange + var serviceCollection = new ServiceCollection(); + serviceCollection.AddAntiforgery(); + serviceCollection.ConfigureDataProtection(o => o.SetApplicationName("HelloWorldApp")); + + serviceCollection.Configure(o => + { + Assert.Null(o.CookieName); + o.CookieName = "antiforgery"; + }, order: 9999); + + var services = serviceCollection.BuildServiceProvider(); + var options = services.GetRequiredService>(); + + // Act + var cookieName = options.Options.CookieName; + + // Assert + Assert.Equal("antiforgery", cookieName); + } + } +} diff --git a/test/Microsoft.AspNet.Antiforgery.Test/AntiforgeryWorkerTest.cs b/test/Microsoft.AspNet.Antiforgery.Test/AntiforgeryTest.cs similarity index 58% rename from test/Microsoft.AspNet.Antiforgery.Test/AntiforgeryWorkerTest.cs rename to test/Microsoft.AspNet.Antiforgery.Test/AntiforgeryTest.cs index 899a1f0225..6b1e4c5368 100644 --- a/test/Microsoft.AspNet.Antiforgery.Test/AntiforgeryWorkerTest.cs +++ b/test/Microsoft.AspNet.Antiforgery.Test/AntiforgeryTest.cs @@ -1,160 +1,127 @@ // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. -#if DNX451 - using System; -using System.Collections.Generic; using System.Security.Claims; using System.Threading.Tasks; -using Microsoft.AspNet.Antiforgery.Internal; using Microsoft.AspNet.Http; using Microsoft.AspNet.Http.Internal; +using Microsoft.Framework.OptionsModel; using Microsoft.Framework.WebEncoders.Testing; +#if DNX451 using Moq; +#endif using Xunit; namespace Microsoft.AspNet.Antiforgery { - public class AntiforgeryWorkerTest + public class AntiforgeryTest { - [Fact] public async Task ChecksSSL_ValidateAsync_Throws() { // Arrange - var mockHttpContext = new Mock(); - mockHttpContext.Setup(o => o.Request.IsHttps) - .Returns(false); + var httpContext = new DefaultHttpContext(); - var config = new AntiforgeryOptions() + var options = new AntiforgeryOptions() { RequireSSL = true }; - var worker = new AntiforgeryWorker( - config: config, - serializer: null, - tokenStore: null, - generator: null, - validator: null, - htmlEncoder: new CommonTestEncoder()); + var antiforgery = GetAntiforgery(options); - // Act & assert - var ex = - await - Assert.ThrowsAsync( - async () => await worker.ValidateAsync(mockHttpContext.Object)); + // Act & Assert + var exception = await Assert.ThrowsAsync( + async () => await antiforgery.ValidateAsync(httpContext)); Assert.Equal( @"The anti-forgery system has the configuration value AntiforgeryOptions.RequireSsl = true, " + "but the current request is not an SSL request.", - ex.Message); + exception.Message); } [Fact] public void ChecksSSL_Validate_Throws() { // Arrange - var mockHttpContext = new Mock(); - mockHttpContext.Setup(o => o.Request.IsHttps) - .Returns(false); + var httpContext = new DefaultHttpContext(); - var config = new AntiforgeryOptions() + var options = new AntiforgeryOptions() { RequireSSL = true }; - var worker = new AntiforgeryWorker( - config: config, - serializer: null, - tokenStore: null, - generator: null, - validator: null, - htmlEncoder: new CommonTestEncoder()); + var antiforgery = GetAntiforgery(options); - // Act & assert - var ex = Assert.Throws( - () => worker.Validate(mockHttpContext.Object, cookieToken: null, formToken: null)); - Assert.Equal( - @"The anti-forgery system has the configuration value AntiforgeryOptions.RequireSsl = true, " + - "but the current request is not an SSL request.", - ex.Message); - } - - [Fact] - public void ChecksSSL_GetFormInputElement_Throws() - { - // Arrange - var mockHttpContext = new Mock(); - mockHttpContext.Setup(o => o.Request.IsHttps) - .Returns(false); - - var config = new AntiforgeryOptions() - { - RequireSSL = true - }; - - var worker = new AntiforgeryWorker( - config: config, - serializer: null, - tokenStore: null, - generator: null, - validator: null, - htmlEncoder: new CommonTestEncoder()); - - // Act & assert - var ex = Assert.Throws(() => worker.GetFormInputElement(mockHttpContext.Object)); + // Act & Assert + var exception = Assert.Throws( + () => antiforgery.Validate(httpContext, cookieToken: null, formToken: null)); Assert.Equal( @"The anti-forgery system has the configuration value AntiforgeryOptions.RequireSsl = true, " + "but the current request is not an SSL request.", - ex.Message); + exception.Message); + } + + [Fact] + public void ChecksSSL_GetHtml_Throws() + { + // Arrange + var httpContext = new DefaultHttpContext(); + + var options = new AntiforgeryOptions() + { + RequireSSL = true + }; + + var antiforgery = GetAntiforgery(options); + + // Act & Assert + var exception = Assert.Throws( + () => antiforgery.GetHtml(httpContext)); + Assert.Equal( + @"The anti-forgery system has the configuration value AntiforgeryOptions.RequireSsl = true, " + + "but the current request is not an SSL request.", + exception.Message); } [Fact] public void ChecksSSL_GetTokens_Throws() { // Arrange - var mockHttpContext = new Mock(); - mockHttpContext.Setup(o => o.Request.IsHttps) - .Returns(false); + var httpContext = new DefaultHttpContext(); - var config = new AntiforgeryOptions() + var options = new AntiforgeryOptions() { RequireSSL = true }; - var worker = new AntiforgeryWorker( - config: config, - serializer: null, - tokenStore: null, - generator: null, - validator: null, - htmlEncoder: new CommonTestEncoder()); + var antiforgery = GetAntiforgery(options); - // Act & assert - var ex = Assert.Throws(() => - worker.GetTokens(mockHttpContext.Object, "cookie-token")); + // Act & Assert + var exception = Assert.Throws( + () => antiforgery.GetTokens(httpContext, "dkfkfkf")); Assert.Equal( - @"The anti-forgery system has the configuration value AntiforgeryOptions.RequireSsl = true, " + - "but the current request is not an SSL request.", - ex.Message); + @"The anti-forgery system has the configuration value AntiforgeryOptions.RequireSsl = true, " + + "but the current request is not an SSL request.", + exception.Message); } +#if DNX451 + [Fact] public void GetFormInputElement_ExistingInvalidCookieToken_GeneratesANewCookieAndAnAntiforgeryToken() { // Arrange - var config = new AntiforgeryOptions() + var options = new AntiforgeryOptions() { FormFieldName = "form-field-name" }; // Make sure the existing cookie is invalid. - var context = GetAntiforgeryWorkerContext(config, isOldCookieValid: false); - var worker = GetAntiforgeryWorker(context); + var context = CreateMockContext(options, isOldCookieValid: false); + var antiforgery = GetAntiforgery(context); // Act - var inputElement = worker.GetFormInputElement(context.HttpContext.Object); + var inputElement = antiforgery.GetHtml(context.HttpContext); // Assert Assert.Equal( @@ -168,25 +135,25 @@ namespace Microsoft.AspNet.Antiforgery public void GetFormInputElement_ExistingInvalidCookieToken_SwallowsExceptions() { // Arrange - var config = new AntiforgeryOptions() + var options = new AntiforgeryOptions() { FormFieldName = "form-field-name" }; // Make sure the existing cookie is invalid. - var context = GetAntiforgeryWorkerContext(config, isOldCookieValid: false); - var worker = GetAntiforgeryWorker(context); + var context = CreateMockContext(options, isOldCookieValid: false); + var antiforgery = GetAntiforgery(context); // This will cause the cookieToken to be null. - context.TokenStore.Setup(o => o.GetCookieToken(context.HttpContext.Object)) + context.TokenStore.Setup(o => o.GetCookieToken(context.HttpContext)) .Throws(new Exception("should be swallowed")); // Setup so that the null cookie token returned is treated as invalid. - context.TokenValidator.Setup(o => o.IsCookieTokenValid(null)) + context.TokenGenerator.Setup(o => o.IsCookieTokenValid(null)) .Returns(false); // Act - var inputElement = worker.GetFormInputElement(context.HttpContext.Object); + var inputElement = antiforgery.GetHtml(context.HttpContext); // Assert Assert.Equal( @@ -206,11 +173,11 @@ namespace Microsoft.AspNet.Antiforgery }; // Make sure the existing cookie is valid and use the same cookie for the mock Token Provider. - var context = GetAntiforgeryWorkerContext(options, useOldCookie: true, isOldCookieValid: true); - var worker = GetAntiforgeryWorker(context); + var context = CreateMockContext(options, useOldCookie: true, isOldCookieValid: true); + var antiforgery = GetAntiforgery(context); // Act - var inputElement = worker.GetFormInputElement(context.HttpContext.Object); + var inputElement = antiforgery.GetHtml(context.HttpContext); // Assert Assert.Equal( @@ -231,14 +198,14 @@ namespace Microsoft.AspNet.Antiforgery }; // Genreate a new cookie. - var context = GetAntiforgeryWorkerContext(options, useOldCookie: false, isOldCookieValid: false); - var worker = GetAntiforgeryWorker(context); + var context = CreateMockContext(options, useOldCookie: false, isOldCookieValid: false); + var antiforgery = GetAntiforgery(context); // Act - var inputElement = worker.GetFormInputElement(context.HttpContext.Object); + var inputElement = antiforgery.GetHtml(context.HttpContext); // Assert - string xFrameOptions = context.HttpContext.Object.Response.Headers["X-Frame-Options"]; + string xFrameOptions = context.HttpContext.Response.Headers["X-Frame-Options"]; Assert.Equal(expectedHeaderValue, xFrameOptions); } @@ -247,14 +214,14 @@ namespace Microsoft.AspNet.Antiforgery { // Arrange // Genreate a new cookie. - var context = GetAntiforgeryWorkerContext( + var context = CreateMockContext( new AntiforgeryOptions(), useOldCookie: false, isOldCookieValid: false); - var worker = GetAntiforgeryWorker(context); + var antiforgery = GetAntiforgery(context); // Act - var tokenset = worker.GetTokens(context.HttpContext.Object, "serialized-old-cookie-token"); + var tokenset = antiforgery.GetTokens(context.HttpContext, "serialized-old-cookie-token"); // Assert Assert.Equal("serialized-new-cookie-token", tokenset.CookieToken); @@ -266,7 +233,7 @@ namespace Microsoft.AspNet.Antiforgery { // Arrange // Make sure the existing cookie is invalid. - var context = GetAntiforgeryWorkerContext( + var context = CreateMockContext( new AntiforgeryOptions(), useOldCookie: false, isOldCookieValid: false); @@ -276,12 +243,12 @@ namespace Microsoft.AspNet.Antiforgery .Throws(new Exception("should be swallowed")); // Setup so that the null cookie token returned is treated as invalid. - context.TokenValidator.Setup(o => o.IsCookieTokenValid(null)) + context.TokenGenerator.Setup(o => o.IsCookieTokenValid(null)) .Returns(false); - var worker = GetAntiforgeryWorker(context); + var antiforgery = GetAntiforgery(context); // Act - var tokenset = worker.GetTokens(context.HttpContext.Object, "serialized-old-cookie-token"); + var tokenset = antiforgery.GetTokens(context.HttpContext, "serialized-old-cookie-token"); // Assert Assert.Equal("serialized-new-cookie-token", tokenset.CookieToken); @@ -292,15 +259,15 @@ namespace Microsoft.AspNet.Antiforgery public void GetTokens_ExistingValidCookieToken_GeneratesANewFormToken() { // Arrange - var context = GetAntiforgeryWorkerContext( + var context = CreateMockContext( new AntiforgeryOptions(), useOldCookie: true, isOldCookieValid: true); context.TokenStore = null; - var worker = GetAntiforgeryWorker(context); + var antiforgery = GetAntiforgery(context); // Act - var tokenset = worker.GetTokens(context.HttpContext.Object, "serialized-old-cookie-token"); + var tokenset = antiforgery.GetTokens(context.HttpContext, "serialized-old-cookie-token"); // Assert Assert.Null(tokenset.CookieToken); @@ -311,95 +278,88 @@ namespace Microsoft.AspNet.Antiforgery public void Validate_FromInvalidStrings_Throws() { // Arrange - var context = GetAntiforgeryWorkerContext(new AntiforgeryOptions()); + var context = CreateMockContext(new AntiforgeryOptions()); context.TokenSerializer.Setup(o => o.Deserialize("cookie-token")) .Returns(context.TestTokenSet.OldCookieToken); context.TokenSerializer.Setup(o => o.Deserialize("form-token")) .Returns(context.TestTokenSet.FormToken); - context.TokenValidator.Setup(o => o.ValidateTokens( - context.HttpContext.Object, - context.HttpContext.Object.User.Identity as ClaimsIdentity, + context.TokenGenerator.Setup(o => o.ValidateTokens( + context.HttpContext, context.TestTokenSet.OldCookieToken, context.TestTokenSet.FormToken)) .Throws(new InvalidOperationException("my-message")); context.TokenStore = null; - var worker = GetAntiforgeryWorker(context); + var antiforgery = GetAntiforgery(context); // Act & assert - var ex = - Assert.Throws( - () => worker.Validate(context.HttpContext.Object, "cookie-token", "form-token")); - Assert.Equal("my-message", ex.Message); + var exception = Assert.Throws( + () => antiforgery.Validate(context.HttpContext, "cookie-token", "form-token")); + Assert.Equal("my-message", exception.Message); } [Fact] public void Validate_FromValidStrings_TokensValidatedSuccessfully() { // Arrange - var context = GetAntiforgeryWorkerContext(new AntiforgeryOptions()); + var context = CreateMockContext(new AntiforgeryOptions()); context.TokenSerializer.Setup(o => o.Deserialize("cookie-token")) .Returns(context.TestTokenSet.OldCookieToken); context.TokenSerializer.Setup(o => o.Deserialize("form-token")) .Returns(context.TestTokenSet.FormToken); - context.TokenValidator.Setup(o => o.ValidateTokens( - context.HttpContext.Object, - context.HttpContext.Object.User.Identity as ClaimsIdentity, + context.TokenGenerator.Setup(o => o.ValidateTokens( + context.HttpContext, context.TestTokenSet.OldCookieToken, context.TestTokenSet.FormToken)) .Verifiable(); context.TokenStore = null; - var worker = GetAntiforgeryWorker(context); + var antiforgery = GetAntiforgery(context); // Act - worker.Validate(context.HttpContext.Object, "cookie-token", "form-token"); + antiforgery.Validate(context.HttpContext, "cookie-token", "form-token"); // Assert - context.TokenValidator.Verify(); + context.TokenGenerator.Verify(); } [Fact] public async Task Validate_FromStore_Failure() { // Arrange - var context = GetAntiforgeryWorkerContext(new AntiforgeryOptions()); + var context = CreateMockContext(new AntiforgeryOptions()); - context.TokenValidator.Setup(o => o.ValidateTokens( - context.HttpContext.Object, - context.HttpContext.Object.User.Identity as ClaimsIdentity, + context.TokenGenerator.Setup(o => o.ValidateTokens( + context.HttpContext, context.TestTokenSet.OldCookieToken, context.TestTokenSet.FormToken)) .Throws(new InvalidOperationException("my-message")); context.TokenSerializer = null; - var worker = GetAntiforgeryWorker(context); + var antiforgery = GetAntiforgery(context); // Act & assert - var ex = - await - Assert.ThrowsAsync( - async () => await worker.ValidateAsync(context.HttpContext.Object)); - Assert.Equal("my-message", ex.Message); + var exception = await Assert.ThrowsAsync( + async () => await antiforgery.ValidateAsync(context.HttpContext)); + Assert.Equal("my-message", exception.Message); } [Fact] public async Task Validate_FromStore_Success() { // Arrange - var context = GetAntiforgeryWorkerContext(new AntiforgeryOptions()); + var context = CreateMockContext(new AntiforgeryOptions()); - context.TokenValidator.Setup(o => o.ValidateTokens( - context.HttpContext.Object, - context.HttpContext.Object.User.Identity as ClaimsIdentity, + context.TokenGenerator.Setup(o => o.ValidateTokens( + context.HttpContext, context.TestTokenSet.OldCookieToken, context.TestTokenSet.FormToken)) .Verifiable(); context.TokenSerializer = null; - var worker = GetAntiforgeryWorker(context); + var antiforgery = GetAntiforgery(context); // Act - await worker.ValidateAsync(context.HttpContext.Object); + await antiforgery.ValidateAsync(context.HttpContext); // Assert - context.TokenValidator.Verify(); + context.TokenGenerator.Verify(); } [Theory] @@ -416,45 +376,55 @@ namespace Microsoft.AspNet.Antiforgery }; // Genreate a new cookie. - var context = GetAntiforgeryWorkerContext(options, useOldCookie: false, isOldCookieValid: false); - var worker = GetAntiforgeryWorker(context); + var context = CreateMockContext(options, useOldCookie: false, isOldCookieValid: false); + var antiforgery = GetAntiforgery(context); // Act - worker.SetCookieTokenAndHeader(context.HttpContext.Object); + antiforgery.SetCookieTokenAndHeader(context.HttpContext); // Assert - var xFrameOptions = context.HttpContext.Object.Response.Headers["X-Frame-Options"]; + var xFrameOptions = context.HttpContext.Response.Headers["X-Frame-Options"]; Assert.Equal(expectedHeaderValue, xFrameOptions); } - private AntiforgeryWorker GetAntiforgeryWorker(AntiforgeryWorkerContext context) - { - return new AntiforgeryWorker( - config: context.Options, - serializer: context.TokenSerializer != null ? context.TokenSerializer.Object : null, - tokenStore: context.TokenStore != null ? context.TokenStore.Object : null, - generator: context.TokenGenerator != null ? context.TokenGenerator.Object : null, - validator: context.TokenValidator != null ? context.TokenValidator.Object : null, - htmlEncoder: new CommonTestEncoder()); - } +#endif - private Mock GetHttpContext(bool setupResponse = true) + private Antiforgery GetAntiforgery( + AntiforgeryOptions options = null, + IAntiforgeryTokenGenerator tokenGenerator = null, + IAntiforgeryTokenSerializer tokenSerializer = null, + IAntiforgeryTokenStore tokenStore = null) { - var identity = new ClaimsIdentity("some-auth"); - var mockHttpContext = new Mock(); - mockHttpContext.Setup(o => o.User) - .Returns(new ClaimsPrincipal(identity)); - - if (setupResponse) + var optionsManager = new TestOptionsManager(); + if (options != null) { - var mockResponse = new Mock(); - mockResponse.Setup(r => r.Headers) - .Returns(new HeaderDictionary(new Dictionary())); - mockHttpContext.Setup(o => o.Response) - .Returns(mockResponse.Object); + optionsManager.Options = options; } - return mockHttpContext; + return new Antiforgery( + antiforgeryOptionsAccessor: optionsManager, + tokenGenerator: tokenGenerator, + tokenSerializer: tokenSerializer, + tokenStore: tokenStore, + htmlEncoder: new CommonTestEncoder()); + } + + private HttpContext GetHttpContext() + { + var httpContext = new DefaultHttpContext(); + httpContext.User = new ClaimsPrincipal(new ClaimsIdentity("some-auth")); + return httpContext; + } + +#if DNX451 + + private Antiforgery GetAntiforgery(AntiforgeryMockContext context) + { + return GetAntiforgery( + context.Options, + context.TokenGenerator?.Object, + context.TokenSerializer?.Object, + context.TokenStore?.Object); } private Mock GetTokenStore( @@ -495,6 +465,49 @@ namespace Microsoft.AspNet.Antiforgery return mockSerializer; } + private AntiforgeryMockContext CreateMockContext( + AntiforgeryOptions options, + bool useOldCookie = false, + bool isOldCookieValid = true) + { + // Arrange + var httpContext = GetHttpContext(); + var testTokenSet = GetTokenSet(isOldCookieTokenSessionToken: true, isNewCookieSessionToken: true); + + var mockSerializer = GetTokenSerializer(testTokenSet); + + var mockTokenStore = GetTokenStore(httpContext, testTokenSet); + + var mockGenerator = new Mock(MockBehavior.Strict); + mockGenerator + .Setup(o => o.GenerateFormToken( + httpContext, + useOldCookie ? testTokenSet.OldCookieToken : testTokenSet.NewCookieToken)) + .Returns(testTokenSet.FormToken); + + mockGenerator + .Setup(o => o.GenerateCookieToken()) + .Returns(useOldCookie ? testTokenSet.OldCookieToken : testTokenSet.NewCookieToken); + + mockGenerator + .Setup(o => o.IsCookieTokenValid(testTokenSet.OldCookieToken)) + .Returns(isOldCookieValid); + + mockGenerator + .Setup(o => o.IsCookieTokenValid(testTokenSet.NewCookieToken)) + .Returns(!isOldCookieValid); + + return new AntiforgeryMockContext() + { + Options = options, + HttpContext = httpContext, + TokenGenerator = mockGenerator, + TokenSerializer = mockSerializer, + TokenStore = mockTokenStore, + TestTokenSet = testTokenSet + }; + } + private TestTokenSet GetTokenSet(bool isOldCookieTokenSessionToken = true, bool isNewCookieSessionToken = true) { return new TestTokenSet() @@ -505,79 +518,46 @@ namespace Microsoft.AspNet.Antiforgery }; } - private AntiforgeryWorkerContext GetAntiforgeryWorkerContext( - AntiforgeryOptions config, - bool useOldCookie = false, - bool isOldCookieValid = true) - { - // Arrange - var mockHttpContext = GetHttpContext(); - var testTokenSet = GetTokenSet(isOldCookieTokenSessionToken: true, isNewCookieSessionToken: true); - - var mockSerializer = GetTokenSerializer(testTokenSet); - - var mockTokenStore = GetTokenStore(mockHttpContext.Object, testTokenSet); - - var mockGenerator = new Mock(MockBehavior.Strict); - mockGenerator - .Setup(o => o.GenerateFormToken( - mockHttpContext.Object, - mockHttpContext.Object.User.Identity as ClaimsIdentity, - useOldCookie ? testTokenSet.OldCookieToken : testTokenSet.NewCookieToken)) - .Returns(testTokenSet.FormToken); - - mockGenerator - .Setup(o => o.GenerateCookieToken()) - .Returns(useOldCookie ? testTokenSet.OldCookieToken : testTokenSet.NewCookieToken); - - var mockValidator = new Mock(MockBehavior.Strict); - mockValidator - .Setup(o => o.IsCookieTokenValid(testTokenSet.OldCookieToken)) - .Returns(isOldCookieValid); - - mockValidator - .Setup(o => o.IsCookieTokenValid(testTokenSet.NewCookieToken)) - .Returns(!isOldCookieValid); - - return new AntiforgeryWorkerContext() - { - Options = config, - HttpContext = mockHttpContext, - TokenGenerator = mockGenerator, - TokenValidator = mockValidator, - TokenSerializer = mockSerializer, - TokenStore = mockTokenStore, - TestTokenSet = testTokenSet - }; - } - private class TestTokenSet { public AntiforgeryToken FormToken { get; set; } + public string FormTokenString { get; set; } + public AntiforgeryToken OldCookieToken { get; set; } + public string OldCookieTokenString { get; set; } + public AntiforgeryToken NewCookieToken { get; set; } + public string NewCookieTokenString { get; set; } } - private class AntiforgeryWorkerContext + private class AntiforgeryMockContext { public AntiforgeryOptions Options { get; set; } public TestTokenSet TestTokenSet { get; set; } - public Mock HttpContext { get; set; } + public HttpContext HttpContext { get; set; } public Mock TokenGenerator { get; set; } - public Mock TokenValidator { get; set; } - public Mock TokenStore { get; set; } public Mock TokenSerializer { get; set; } } - } -} -#endif \ No newline at end of file +#endif + + private class TestOptionsManager : IOptions + { + public AntiforgeryOptions Options { get; set; } = new AntiforgeryOptions(); + + public AntiforgeryOptions GetNamedOptions(string name) + { + throw new NotImplementedException(); + } + } + } +} \ No newline at end of file diff --git a/test/Microsoft.AspNet.Antiforgery.Test/TokenProviderTest.cs b/test/Microsoft.AspNet.Antiforgery.Test/AntiforgeryTokenGeneratorTest.cs similarity index 72% rename from test/Microsoft.AspNet.Antiforgery.Test/TokenProviderTest.cs rename to test/Microsoft.AspNet.Antiforgery.Test/AntiforgeryTokenGeneratorTest.cs index ea3955511f..8cf4a67cbb 100644 --- a/test/Microsoft.AspNet.Antiforgery.Test/TokenProviderTest.cs +++ b/test/Microsoft.AspNet.Antiforgery.Test/AntiforgeryTokenGeneratorTest.cs @@ -4,7 +4,7 @@ using System; using System.Security.Claims; using System.Security.Cryptography; -using Microsoft.AspNet.Http; +using Microsoft.AspNet.Http.Internal; #if DNX451 using Moq; #endif @@ -12,44 +12,40 @@ using Xunit; namespace Microsoft.AspNet.Antiforgery { - public class TokenProviderTest + public class AntiforgeryTokenGeneratorProviderTest { [Fact] public void GenerateCookieToken() { // Arrange - var tokenProvider = new AntiforgeryTokenProvider( - config: null, - claimUidExtractor: null, - additionalDataProvider: null); + var tokenProvider = new AntiforgeryTokenGenerator( + optionsAccessor: new TestOptionsManager(), + claimUidExtractor: null, + additionalDataProvider: null); // Act - var retVal = tokenProvider.GenerateCookieToken(); + var token = tokenProvider.GenerateCookieToken(); // Assert - Assert.NotNull(retVal); + Assert.NotNull(token); } -#if DNX451 [Fact] public void GenerateFormToken_AnonymousUser() { // Arrange var cookieToken = new AntiforgeryToken() { IsSessionToken = true }; - var httpContext = new Mock().Object; - var mockIdentity = new Mock(); - mockIdentity.Setup(o => o.IsAuthenticated) - .Returns(false); + var httpContext = new DefaultHttpContext(); + httpContext.User = new ClaimsPrincipal(new ClaimsIdentity()); + Assert.False(httpContext.User.Identity.IsAuthenticated); - var config = new AntiforgeryOptions(); - - var tokenProvider = new AntiforgeryTokenProvider( - config: config, + var tokenProvider = new AntiforgeryTokenGenerator( + optionsAccessor: new TestOptionsManager(), claimUidExtractor: null, additionalDataProvider: null); // Act - var fieldToken = tokenProvider.GenerateFormToken(httpContext, mockIdentity.Object, cookieToken); + var fieldToken = tokenProvider.GenerateFormToken(httpContext, cookieToken); // Assert Assert.NotNull(fieldToken); @@ -60,6 +56,8 @@ namespace Microsoft.AspNet.Antiforgery Assert.Empty(fieldToken.AdditionalData); } +#if DNX451 + [Fact] public void GenerateFormToken_AuthenticatedWithoutUsernameAndNoAdditionalData_NoAdditionalData() { @@ -69,20 +67,20 @@ namespace Microsoft.AspNet.Antiforgery IsSessionToken = true }; - var httpContext = new Mock().Object; - ClaimsIdentity identity = new MyAuthenticatedIdentityWithoutUsername(); - var config = new AntiforgeryOptions(); - IClaimUidExtractor claimUidExtractor = new Mock().Object; + var httpContext = new DefaultHttpContext(); + httpContext.User = new ClaimsPrincipal(new MyAuthenticatedIdentityWithoutUsername()); - var tokenProvider = new AntiforgeryTokenProvider( - config: config, + var options = new AntiforgeryOptions(); + var claimUidExtractor = new Mock().Object; + + var tokenProvider = new AntiforgeryTokenGenerator( + optionsAccessor: new TestOptionsManager(), claimUidExtractor: claimUidExtractor, additionalDataProvider: null); // Act & assert - var ex = - Assert.Throws( - () => tokenProvider.GenerateFormToken(httpContext, identity, cookieToken)); + var exception = Assert.Throws( + () => tokenProvider.GenerateFormToken(httpContext, cookieToken)); Assert.Equal( "The provided identity of type " + $"'{typeof(MyAuthenticatedIdentityWithoutUsername).FullName}' " + @@ -91,7 +89,7 @@ namespace Microsoft.AspNet.Antiforgery "If it is not possible to provide a unique Name for this identity, " + "consider extending IAdditionalDataProvider by overriding the DefaultAdditionalDataProvider " + "or a custom type that can provide some form of unique identifier for the current user.", - ex.Message); + exception.Message); } [Fact] @@ -99,23 +97,23 @@ namespace Microsoft.AspNet.Antiforgery { // Arrange var cookieToken = new AntiforgeryToken() { IsSessionToken = true }; - var httpContext = new Mock().Object; - ClaimsIdentity identity = new MyAuthenticatedIdentityWithoutUsername(); + + var httpContext = new DefaultHttpContext(); + httpContext.User = new ClaimsPrincipal(new MyAuthenticatedIdentityWithoutUsername()); var mockAdditionalDataProvider = new Mock(); mockAdditionalDataProvider.Setup(o => o.GetAdditionalData(httpContext)) .Returns("additional-data"); - var config = new AntiforgeryOptions(); - IClaimUidExtractor claimUidExtractor = new Mock().Object; + var claimUidExtractor = new Mock().Object; - var tokenProvider = new AntiforgeryTokenProvider( - config: config, + var tokenProvider = new AntiforgeryTokenGenerator( + optionsAccessor: new TestOptionsManager(), claimUidExtractor: claimUidExtractor, additionalDataProvider: mockAdditionalDataProvider.Object); // Act - var fieldToken = tokenProvider.GenerateFormToken(httpContext, identity, cookieToken); + var fieldToken = tokenProvider.GenerateFormToken(httpContext, cookieToken); // Assert Assert.NotNull(fieldToken); @@ -131,10 +129,10 @@ namespace Microsoft.AspNet.Antiforgery { // Arrange var cookieToken = new AntiforgeryToken() { IsSessionToken = true }; - var httpContext = new Mock().Object; - var identity = GetAuthenticatedIdentity("some-identity"); - var config = new AntiforgeryOptions(); + var identity = GetAuthenticatedIdentity("some-identity"); + var httpContext = new DefaultHttpContext(); + httpContext.User = new ClaimsPrincipal(identity); byte[] data = new byte[256 / 8]; using (var rng = RandomNumberGenerator.Create()) @@ -148,13 +146,13 @@ namespace Microsoft.AspNet.Antiforgery mockClaimUidExtractor.Setup(o => o.ExtractClaimUid(identity)) .Returns(base64ClaimUId); - var tokenProvider = new AntiforgeryTokenProvider( - config: config, + var tokenProvider = new AntiforgeryTokenGenerator( + optionsAccessor: new TestOptionsManager(), claimUidExtractor: mockClaimUidExtractor.Object, additionalDataProvider: null); // Act - var fieldToken = tokenProvider.GenerateFormToken(httpContext, identity, cookieToken); + var fieldToken = tokenProvider.GenerateFormToken(httpContext, cookieToken); // Assert Assert.NotNull(fieldToken); @@ -171,23 +169,24 @@ namespace Microsoft.AspNet.Antiforgery // Arrange var cookieToken = new AntiforgeryToken() { IsSessionToken = true }; - var httpContext = new Mock().Object; + var httpContext = new DefaultHttpContext(); var mockIdentity = new Mock(); mockIdentity.Setup(o => o.IsAuthenticated) .Returns(true); mockIdentity.Setup(o => o.Name) .Returns("my-username"); - var config = new AntiforgeryOptions(); - IClaimUidExtractor claimUidExtractor = new Mock().Object; + httpContext.User = new ClaimsPrincipal(mockIdentity.Object); + + var claimUidExtractor = new Mock().Object; - var tokenProvider = new AntiforgeryTokenProvider( - config: config, + var tokenProvider = new AntiforgeryTokenGenerator( + optionsAccessor: new TestOptionsManager(), claimUidExtractor: claimUidExtractor, additionalDataProvider: null); // Act - var fieldToken = tokenProvider.GenerateFormToken(httpContext, mockIdentity.Object, cookieToken); + var fieldToken = tokenProvider.GenerateFormToken(httpContext, cookieToken); // Assert Assert.NotNull(fieldToken); @@ -208,8 +207,8 @@ namespace Microsoft.AspNet.Antiforgery IsSessionToken = false }; - var tokenProvider = new AntiforgeryTokenProvider( - config: null, + var tokenProvider = new AntiforgeryTokenGenerator( + optionsAccessor: new TestOptionsManager(), claimUidExtractor: null, additionalDataProvider: null); @@ -225,16 +224,16 @@ namespace Microsoft.AspNet.Antiforgery { // Arrange AntiforgeryToken cookieToken = null; - var tokenProvider = new AntiforgeryTokenProvider( - config: null, + var tokenProvider = new AntiforgeryTokenGenerator( + optionsAccessor: new TestOptionsManager(), claimUidExtractor: null, additionalDataProvider: null); // Act - bool retVal = tokenProvider.IsCookieTokenValid(cookieToken); + var isValid = tokenProvider.IsCookieTokenValid(cookieToken); // Assert - Assert.False(retVal); + Assert.False(isValid); } [Fact] @@ -246,41 +245,42 @@ namespace Microsoft.AspNet.Antiforgery IsSessionToken = true }; - var tokenProvider = new AntiforgeryTokenProvider( - config: null, + var tokenProvider = new AntiforgeryTokenGenerator( + optionsAccessor: new TestOptionsManager(), claimUidExtractor: null, additionalDataProvider: null); // Act - bool retVal = tokenProvider.IsCookieTokenValid(cookieToken); + var isValid = tokenProvider.IsCookieTokenValid(cookieToken); // Assert - Assert.True(retVal); + Assert.True(isValid); } -#if DNX451 + [Fact] public void ValidateTokens_SessionTokenMissing() { // Arrange - var httpContext = new Mock().Object; - ClaimsIdentity identity = new Mock().Object; - AntiforgeryToken sessionToken = null; + var httpContext = new DefaultHttpContext(); + httpContext.User = new ClaimsPrincipal(new ClaimsIdentity()); + var fieldtoken = new AntiforgeryToken() { IsSessionToken = false }; - var config = new AntiforgeryOptions() + var options = new AntiforgeryOptions() { CookieName = "my-cookie-name" }; - var tokenProvider = new AntiforgeryTokenProvider( - config: config, + + var tokenProvider = new AntiforgeryTokenGenerator( + optionsAccessor: new TestOptionsManager(options), claimUidExtractor: null, additionalDataProvider: null); // Act & assert var ex = Assert.Throws( - () => tokenProvider.ValidateTokens(httpContext, identity, sessionToken, fieldtoken)); + () => tokenProvider.ValidateTokens(httpContext, null, fieldtoken)); Assert.Equal(@"The required anti-forgery cookie ""my-cookie-name"" is not present.", ex.Message); } @@ -288,25 +288,25 @@ namespace Microsoft.AspNet.Antiforgery public void ValidateTokens_FieldTokenMissing() { // Arrange - var httpContext = new Mock().Object; - ClaimsIdentity identity = new Mock().Object; - var sessionToken = new AntiforgeryToken() { IsSessionToken = true }; - AntiforgeryToken fieldtoken = null; + var httpContext = new DefaultHttpContext(); + httpContext.User = new ClaimsPrincipal(new ClaimsIdentity()); - var config = new AntiforgeryOptions() + var sessionToken = new AntiforgeryToken() { IsSessionToken = true }; + + var options = new AntiforgeryOptions() { FormFieldName = "my-form-field-name" }; - var tokenProvider = new AntiforgeryTokenProvider( - config: config, + var tokenProvider = new AntiforgeryTokenGenerator( + optionsAccessor: new TestOptionsManager(options), claimUidExtractor: null, additionalDataProvider: null); // Act & assert var ex = Assert.Throws( - () => tokenProvider.ValidateTokens(httpContext, identity, sessionToken, fieldtoken)); + () => tokenProvider.ValidateTokens(httpContext, sessionToken, null)); Assert.Equal(@"The required anti-forgery form field ""my-form-field-name"" is not present.", ex.Message); } @@ -314,26 +314,27 @@ namespace Microsoft.AspNet.Antiforgery public void ValidateTokens_FieldAndSessionTokensSwapped() { // Arrange - var httpContext = new Mock().Object; - ClaimsIdentity identity = new Mock().Object; + var httpContext = new DefaultHttpContext(); + httpContext.User = new ClaimsPrincipal(new ClaimsIdentity()); + var sessionToken = new AntiforgeryToken() { IsSessionToken = true }; var fieldtoken = new AntiforgeryToken() { IsSessionToken = false }; - var config = new AntiforgeryOptions() + var options = new AntiforgeryOptions() { CookieName = "my-cookie-name", FormFieldName = "my-form-field-name" }; - var tokenProvider = new AntiforgeryTokenProvider( - config: config, + var tokenProvider = new AntiforgeryTokenGenerator( + optionsAccessor: new TestOptionsManager(options), claimUidExtractor: null, additionalDataProvider: null); // Act & assert var ex1 = Assert.Throws( - () => tokenProvider.ValidateTokens(httpContext, identity, fieldtoken, fieldtoken)); + () => tokenProvider.ValidateTokens(httpContext, fieldtoken, fieldtoken)); Assert.Equal( "Validation of the provided anti-forgery token failed. " + @"The cookie ""my-cookie-name"" and the form field ""my-form-field-name"" were swapped.", @@ -341,7 +342,7 @@ namespace Microsoft.AspNet.Antiforgery var ex2 = Assert.Throws( - () => tokenProvider.ValidateTokens(httpContext, identity, sessionToken, sessionToken)); + () => tokenProvider.ValidateTokens(httpContext, sessionToken, sessionToken)); Assert.Equal( "Validation of the provided anti-forgery token failed. " + @"The cookie ""my-cookie-name"" and the form field ""my-form-field-name"" were swapped.", @@ -352,23 +353,27 @@ namespace Microsoft.AspNet.Antiforgery public void ValidateTokens_FieldAndSessionTokensHaveDifferentSecurityKeys() { // Arrange - var httpContext = new Mock().Object; - ClaimsIdentity identity = new Mock().Object; + var httpContext = new DefaultHttpContext(); + httpContext.User = new ClaimsPrincipal(new ClaimsIdentity()); + var sessionToken = new AntiforgeryToken() { IsSessionToken = true }; var fieldtoken = new AntiforgeryToken() { IsSessionToken = false }; - var tokenProvider = new AntiforgeryTokenProvider( - config: null, + var tokenProvider = new AntiforgeryTokenGenerator( + optionsAccessor: new TestOptionsManager(), claimUidExtractor: null, additionalDataProvider: null); - // Act & assert - var ex = - Assert.Throws( - () => tokenProvider.ValidateTokens(httpContext, identity, sessionToken, fieldtoken)); - Assert.Equal(@"The anti-forgery cookie token and form field token do not match.", ex.Message); + // Act & Assert + var exception = Assert.Throws( + () => tokenProvider.ValidateTokens(httpContext, sessionToken, fieldtoken)); + Assert.Equal( + @"The anti-forgery cookie token and form field token do not match.", + exception.Message); } +#if DNX451 + [Theory] [InlineData("the-user", "the-other-user")] [InlineData("http://example.com/uri-casing", "http://example.com/URI-casing")] @@ -376,8 +381,10 @@ namespace Microsoft.AspNet.Antiforgery public void ValidateTokens_UsernameMismatch(string identityUsername, string embeddedUsername) { // Arrange - var httpContext = new Mock().Object; + var httpContext = new DefaultHttpContext(); var identity = GetAuthenticatedIdentity(identityUsername); + httpContext.User = new ClaimsPrincipal(identity); + var sessionToken = new AntiforgeryToken() { IsSessionToken = true }; var fieldtoken = new AntiforgeryToken() { @@ -390,26 +397,28 @@ namespace Microsoft.AspNet.Antiforgery mockClaimUidExtractor.Setup(o => o.ExtractClaimUid(identity)) .Returns((string)null); - var tokenProvider = new AntiforgeryTokenProvider( - config: null, + var tokenProvider = new AntiforgeryTokenGenerator( + optionsAccessor: new TestOptionsManager(), claimUidExtractor: mockClaimUidExtractor.Object, additionalDataProvider: null); - // Act & assert - var ex = - Assert.Throws( - () => tokenProvider.ValidateTokens(httpContext, identity, sessionToken, fieldtoken)); + // Act & Assert + var exception = Assert.Throws( + () => tokenProvider.ValidateTokens(httpContext, sessionToken, fieldtoken)); Assert.Equal( @"The provided anti-forgery token was meant for user """ + embeddedUsername + - @""", but the current user is """ + identityUsername + @""".", ex.Message); + @""", but the current user is """ + identityUsername + @""".", + exception.Message); } [Fact] public void ValidateTokens_ClaimUidMismatch() { // Arrange - var httpContext = new Mock().Object; + var httpContext = new DefaultHttpContext(); var identity = GetAuthenticatedIdentity("the-user"); + httpContext.User = new ClaimsPrincipal(identity); + var sessionToken = new AntiforgeryToken() { IsSessionToken = true }; var fieldtoken = new AntiforgeryToken() { @@ -423,26 +432,27 @@ namespace Microsoft.AspNet.Antiforgery mockClaimUidExtractor.Setup(o => o.ExtractClaimUid(identity)) .Returns(Convert.ToBase64String(differentToken.GetData())); - var tokenProvider = new AntiforgeryTokenProvider( - config: null, + var tokenProvider = new AntiforgeryTokenGenerator( + optionsAccessor: new TestOptionsManager(), claimUidExtractor: mockClaimUidExtractor.Object, additionalDataProvider: null); // Act & assert - var ex = - Assert.Throws( - () => tokenProvider.ValidateTokens(httpContext, identity, sessionToken, fieldtoken)); + var exception = Assert.Throws( + () => tokenProvider.ValidateTokens(httpContext, sessionToken, fieldtoken)); Assert.Equal( @"The provided anti-forgery token was meant for a different claims-based user than the current user.", - ex.Message); + exception.Message); } [Fact] public void ValidateTokens_AdditionalDataRejected() { // Arrange - var httpContext = new Mock().Object; + var httpContext = new DefaultHttpContext(); var identity = new ClaimsIdentity(); + httpContext.User = new ClaimsPrincipal(identity); + var sessionToken = new AntiforgeryToken() { IsSessionToken = true }; var fieldtoken = new AntiforgeryToken() { @@ -456,25 +466,25 @@ namespace Microsoft.AspNet.Antiforgery mockAdditionalDataProvider.Setup(o => o.ValidateAdditionalData(httpContext, "some-additional-data")) .Returns(false); - var config = new AntiforgeryOptions(); - var tokenProvider = new AntiforgeryTokenProvider( - config: config, + var tokenProvider = new AntiforgeryTokenGenerator( + optionsAccessor: new TestOptionsManager(), claimUidExtractor: null, additionalDataProvider: mockAdditionalDataProvider.Object); // Act & assert - var ex = - Assert.Throws( - () => tokenProvider.ValidateTokens(httpContext, identity, sessionToken, fieldtoken)); - Assert.Equal(@"The provided anti-forgery token failed a custom data check.", ex.Message); + var exception = Assert.Throws( + () => tokenProvider.ValidateTokens(httpContext, sessionToken, fieldtoken)); + Assert.Equal(@"The provided anti-forgery token failed a custom data check.", exception.Message); } [Fact] public void ValidateTokens_Success_AnonymousUser() { // Arrange - var httpContext = new Mock().Object; + var httpContext = new DefaultHttpContext(); var identity = new ClaimsIdentity(); + httpContext.User = new ClaimsPrincipal(identity); + var sessionToken = new AntiforgeryToken() { IsSessionToken = true }; var fieldtoken = new AntiforgeryToken() { @@ -488,14 +498,13 @@ namespace Microsoft.AspNet.Antiforgery mockAdditionalDataProvider.Setup(o => o.ValidateAdditionalData(httpContext, "some-additional-data")) .Returns(true); - var config = new AntiforgeryOptions(); - var tokenProvider = new AntiforgeryTokenProvider( - config: config, + var tokenProvider = new AntiforgeryTokenGenerator( + optionsAccessor: new TestOptionsManager(), claimUidExtractor: null, additionalDataProvider: mockAdditionalDataProvider.Object); // Act - tokenProvider.ValidateTokens(httpContext, identity, sessionToken, fieldtoken); + tokenProvider.ValidateTokens(httpContext, sessionToken, fieldtoken); // Assert // Nothing to assert - if we got this far, success! @@ -505,8 +514,10 @@ namespace Microsoft.AspNet.Antiforgery public void ValidateTokens_Success_AuthenticatedUserWithUsername() { // Arrange - var httpContext = new Mock().Object; + var httpContext = new DefaultHttpContext(); var identity = GetAuthenticatedIdentity("the-user"); + httpContext.User = new ClaimsPrincipal(identity); + var sessionToken = new AntiforgeryToken() { IsSessionToken = true }; var fieldtoken = new AntiforgeryToken() { @@ -520,14 +531,13 @@ namespace Microsoft.AspNet.Antiforgery mockAdditionalDataProvider.Setup(o => o.ValidateAdditionalData(httpContext, "some-additional-data")) .Returns(true); - var config = new AntiforgeryOptions(); - var tokenProvider = new AntiforgeryTokenProvider( - config: config, + var tokenProvider = new AntiforgeryTokenGenerator( + optionsAccessor: new TestOptionsManager(), claimUidExtractor: new Mock().Object, additionalDataProvider: mockAdditionalDataProvider.Object); // Act - tokenProvider.ValidateTokens(httpContext, identity, sessionToken, fieldtoken); + tokenProvider.ValidateTokens(httpContext, sessionToken, fieldtoken); // Assert // Nothing to assert - if we got this far, success! @@ -537,8 +547,10 @@ namespace Microsoft.AspNet.Antiforgery public void ValidateTokens_Success_ClaimsBasedUser() { // Arrange - var httpContext = new Mock().Object; + var httpContext = new DefaultHttpContext(); var identity = GetAuthenticatedIdentity("the-user"); + httpContext.User = new ClaimsPrincipal(identity); + var sessionToken = new AntiforgeryToken() { IsSessionToken = true }; var fieldtoken = new AntiforgeryToken() { @@ -551,15 +563,13 @@ namespace Microsoft.AspNet.Antiforgery mockClaimUidExtractor.Setup(o => o.ExtractClaimUid(identity)) .Returns(Convert.ToBase64String(fieldtoken.ClaimUid.GetData())); - var config = new AntiforgeryOptions(); - - var tokenProvider = new AntiforgeryTokenProvider( - config: config, + var tokenProvider = new AntiforgeryTokenGenerator( + optionsAccessor: new TestOptionsManager(), claimUidExtractor: mockClaimUidExtractor.Object, additionalDataProvider: null); // Act - tokenProvider.ValidateTokens(httpContext, identity, sessionToken, fieldtoken); + tokenProvider.ValidateTokens(httpContext, sessionToken, fieldtoken); // Assert // Nothing to assert - if we got this far, success! diff --git a/test/Microsoft.AspNet.Antiforgery.Test/AntiforgeryTokenSerializerTest.cs b/test/Microsoft.AspNet.Antiforgery.Test/AntiforgeryTokenSerializerTest.cs index dae7de6a17..31fc024721 100644 --- a/test/Microsoft.AspNet.Antiforgery.Test/AntiforgeryTokenSerializerTest.cs +++ b/test/Microsoft.AspNet.Antiforgery.Test/AntiforgeryTokenSerializerTest.cs @@ -13,7 +13,7 @@ namespace Microsoft.AspNet.Antiforgery { public class AntiforgeryTokenSerializerTest { - private static readonly Mock _dataProtector = GetDataProtector(); + private static readonly Mock _dataProtector = GetDataProtector(); private static readonly BinaryBlob _claimUid = new BinaryBlob(256, new byte[] { 0x6F, 0x16, 0x48, 0xE9, 0x72, 0x49, 0xAA, 0x58, 0x75, 0x40, 0x36, 0xA6, 0x7E, 0x24, 0x8C, 0xF0, 0x44, 0xF0, 0x7E, 0xCF, 0xB0, 0xED, 0x38, 0x75, 0x56, 0xCE, 0x02, 0x9A, 0x4F, 0x9A, 0x40, 0xE0 }); private static readonly BinaryBlob _securityToken = new BinaryBlob(128, new byte[] { 0x70, 0x5E, 0xED, 0xCC, 0x7D, 0x42, 0xF1, 0xD6, 0xB3, 0xB9, 0x8A, 0x59, 0x36, 0x25, 0xBB, 0x4C }); private const byte _salt = 0x05; @@ -138,7 +138,7 @@ namespace Microsoft.AspNet.Antiforgery _dataProtector.Verify(); } - private static Mock GetDataProtector() + private static Mock GetDataProtector() { var mockCryptoSystem = new Mock(); mockCryptoSystem.Setup(o => o.Protect(It.IsAny())) @@ -147,7 +147,12 @@ namespace Microsoft.AspNet.Antiforgery mockCryptoSystem.Setup(o => o.Unprotect(It.IsAny())) .Returns(UnProtect) .Verifiable(); - return mockCryptoSystem; + + var provider = new Mock(); + provider + .Setup(p => p.CreateProtector(It.IsAny())) + .Returns(mockCryptoSystem.Object); + return provider; } private static byte[] Protect(byte[] data) diff --git a/test/Microsoft.AspNet.Antiforgery.Test/AntiforgeryTokenStoreTest.cs b/test/Microsoft.AspNet.Antiforgery.Test/AntiforgeryTokenStoreTest.cs index b8e45bc0e1..1753b8ce0e 100644 --- a/test/Microsoft.AspNet.Antiforgery.Test/AntiforgeryTokenStoreTest.cs +++ b/test/Microsoft.AspNet.Antiforgery.Test/AntiforgeryTokenStoreTest.cs @@ -32,14 +32,14 @@ namespace Microsoft.AspNet.Antiforgery var contextAccessor = new AntiforgeryContextAccessor(); mockHttpContext.SetupGet(o => o.RequestServices) .Returns(GetServiceProvider(contextAccessor)); - var config = new AntiforgeryOptions() + var options = new AntiforgeryOptions() { CookieName = _cookieName }; var tokenStore = new AntiforgeryTokenStore( - config: config, - serializer: null); + optionsAccessor: new TestOptionsManager(options), + tokenSerializer: null); // Act var token = tokenStore.GetCookieToken(mockHttpContext.Object); @@ -67,14 +67,14 @@ namespace Microsoft.AspNet.Antiforgery // add a cookie explicitly. var cookie = new AntiforgeryToken(); contextAccessor.Value = new AntiforgeryContext() { CookieToken = cookie }; - var config = new AntiforgeryOptions() + var options = new AntiforgeryOptions() { CookieName = _cookieName }; var tokenStore = new AntiforgeryTokenStore( - config: config, - serializer: null); + optionsAccessor: new TestOptionsManager(options), + tokenSerializer: null); // Act var token = tokenStore.GetCookieToken(mockHttpContext.Object); @@ -89,14 +89,14 @@ namespace Microsoft.AspNet.Antiforgery // Arrange var mockHttpContext = GetMockHttpContext(_cookieName, string.Empty); - var config = new AntiforgeryOptions() + var options = new AntiforgeryOptions() { CookieName = _cookieName }; var tokenStore = new AntiforgeryTokenStore( - config: config, - serializer: null); + optionsAccessor: new TestOptionsManager(options), + tokenSerializer: null); // Act var token = tokenStore.GetCookieToken(mockHttpContext); @@ -110,10 +110,6 @@ namespace Microsoft.AspNet.Antiforgery { // Arrange var mockHttpContext = GetMockHttpContext(_cookieName, "invalid-value"); - var config = new AntiforgeryOptions() - { - CookieName = _cookieName - }; var expectedException = new InvalidOperationException("some exception"); var mockSerializer = new Mock(); @@ -121,9 +117,14 @@ namespace Microsoft.AspNet.Antiforgery .Setup(o => o.Deserialize("invalid-value")) .Throws(expectedException); + var options = new AntiforgeryOptions() + { + CookieName = _cookieName + }; + var tokenStore = new AntiforgeryTokenStore( - config: config, - serializer: mockSerializer.Object); + optionsAccessor: new TestOptionsManager(options), + tokenSerializer: mockSerializer.Object); // Act & assert var ex = Assert.Throws(() => tokenStore.GetCookieToken(mockHttpContext)); @@ -137,19 +138,19 @@ namespace Microsoft.AspNet.Antiforgery var expectedToken = new AntiforgeryToken(); var mockHttpContext = GetMockHttpContext(_cookieName, "valid-value"); - var config = new AntiforgeryOptions() - { - CookieName = _cookieName - }; - var mockSerializer = new Mock(); mockSerializer .Setup(o => o.Deserialize("valid-value")) .Returns(expectedToken); + var options = new AntiforgeryOptions() + { + CookieName = _cookieName + }; + var tokenStore = new AntiforgeryTokenStore( - config: config, - serializer: mockSerializer.Object); + optionsAccessor: new TestOptionsManager(options), + tokenSerializer: mockSerializer.Object); // Act AntiforgeryToken retVal = tokenStore.GetCookieToken(mockHttpContext); @@ -170,14 +171,15 @@ namespace Microsoft.AspNet.Antiforgery .Returns(Task.FromResult(formCollection.Object)); mockHttpContext.Setup(o => o.Request) .Returns(requestContext.Object); - var config = new AntiforgeryOptions() + + var options = new AntiforgeryOptions() { - FormFieldName = "form-field-name" + FormFieldName = "form-field-name", }; var tokenStore = new AntiforgeryTokenStore( - config: config, - serializer: null); + optionsAccessor: new TestOptionsManager(options), + tokenSerializer: null); // Act var token = await tokenStore.GetFormTokenAsync(mockHttpContext.Object); @@ -201,26 +203,24 @@ namespace Microsoft.AspNet.Antiforgery mockHttpContext.Setup(o => o.Request) .Returns(requestContext.Object); - var config = new AntiforgeryOptions() - { - FormFieldName = "form-field-name" - }; - var expectedException = new InvalidOperationException("some exception"); var mockSerializer = new Mock(); mockSerializer.Setup(o => o.Deserialize("invalid-value")) .Throws(expectedException); + var options = new AntiforgeryOptions() + { + FormFieldName = "form-field-name", + }; + var tokenStore = new AntiforgeryTokenStore( - config: config, - serializer: mockSerializer.Object); + optionsAccessor: new TestOptionsManager(options), + tokenSerializer: mockSerializer.Object); // Act & assert - var ex = - await - Assert.ThrowsAsync( + var exception = await Assert.ThrowsAsync( async () => await tokenStore.GetFormTokenAsync(mockHttpContext.Object)); - Assert.Same(expectedException, ex); + Assert.Same(expectedException, exception); } [Fact] @@ -239,18 +239,18 @@ namespace Microsoft.AspNet.Antiforgery mockHttpContext.Setup(o => o.Request) .Returns(requestContext.Object); - var config = new AntiforgeryOptions() - { - FormFieldName = "form-field-name" - }; - var mockSerializer = new Mock(); mockSerializer.Setup(o => o.Deserialize("valid-value")) .Returns(expectedToken); + var options = new AntiforgeryOptions() + { + FormFieldName = "form-field-name", + }; + var tokenStore = new AntiforgeryTokenStore( - config: config, - serializer: mockSerializer.Object); + optionsAccessor: new TestOptionsManager(options), + tokenSerializer: mockSerializer.Object); // Act var retVal = await tokenStore.GetFormTokenAsync(mockHttpContext.Object); @@ -283,15 +283,15 @@ namespace Microsoft.AspNet.Antiforgery mockSerializer.Setup(o => o.Serialize(token)) .Returns("serialized-value"); - var config = new AntiforgeryOptions() + var options = new AntiforgeryOptions() { CookieName = _cookieName, RequireSSL = requireSsl }; var tokenStore = new AntiforgeryTokenStore( - config: config, - serializer: mockSerializer.Object); + optionsAccessor: new TestOptionsManager(options), + tokenSerializer: mockSerializer.Object); // Act tokenStore.SaveCookieToken(mockHttpContext.Object, token); diff --git a/test/Microsoft.AspNet.Antiforgery.Test/TestOptionsManager.cs b/test/Microsoft.AspNet.Antiforgery.Test/TestOptionsManager.cs new file mode 100644 index 0000000000..2a74d9764e --- /dev/null +++ b/test/Microsoft.AspNet.Antiforgery.Test/TestOptionsManager.cs @@ -0,0 +1,27 @@ +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System; +using Microsoft.Framework.OptionsModel; + +namespace Microsoft.AspNet.Antiforgery +{ + public class TestOptionsManager : IOptions + { + public TestOptionsManager() + { + } + + public TestOptionsManager(AntiforgeryOptions options) + { + Options = options; + } + + public AntiforgeryOptions Options { get; set; } = new AntiforgeryOptions(); + + public AntiforgeryOptions GetNamedOptions(string name) + { + throw new NotImplementedException(); + } + } +} From b3e92da7d81285575047aaae564d1761655032c2 Mon Sep 17 00:00:00 2001 From: Ryan Nowak Date: Wed, 24 Jun 2015 15:52:39 -0700 Subject: [PATCH 011/296] Add an IAntiforgery interface and simplify API --- .../FormPostSampleMiddleware.cs | 11 +- .../{Antiforgery.cs => DefaultAntiforgery.cs} | 131 ++++++------------ ...s => DefaultAntiforgeryContextAccessor.cs} | 2 +- ...cs => DefaultAntiforgeryTokenGenerator.cs} | 4 +- ...s => DefaultAntiforgeryTokenSerializer.cs} | 4 +- ...ore.cs => DefaultAntiforgeryTokenStore.cs} | 4 +- .../IAntiforgery.cs | 74 ++++++++++ .../ServiceCollectionExtensions.cs | 10 +- ...rgeryTest.cs => DefaultAntiforgeryTest.cs} | 85 +++++++++--- ...> DefaultAntiforgeryTokenGeneratorTest.cs} | 40 +++--- ... DefaultAntiforgeryTokenSerializerTest.cs} | 10 +- ...cs => DefaultAntiforgeryTokenStoreTest.cs} | 28 ++-- ...est.cs => DefaultClaimUidExtractorTest.cs} | 2 +- 13 files changed, 237 insertions(+), 168 deletions(-) rename src/Microsoft.AspNet.Antiforgery/{Antiforgery.cs => DefaultAntiforgery.cs} (52%) rename src/Microsoft.AspNet.Antiforgery/{AntiforgeryContextAccessor.cs => DefaultAntiforgeryContextAccessor.cs} (77%) rename src/Microsoft.AspNet.Antiforgery/{AntiforgeryTokenGenerator.cs => DefaultAntiforgeryTokenGenerator.cs} (98%) rename src/Microsoft.AspNet.Antiforgery/{AntiforgeryTokenSerializer.cs => DefaultAntiforgeryTokenSerializer.cs} (96%) rename src/Microsoft.AspNet.Antiforgery/{AntiforgeryTokenStore.cs => DefaultAntiforgeryTokenStore.cs} (96%) create mode 100644 src/Microsoft.AspNet.Antiforgery/IAntiforgery.cs rename test/Microsoft.AspNet.Antiforgery.Test/{AntiforgeryTest.cs => DefaultAntiforgeryTest.cs} (87%) rename test/Microsoft.AspNet.Antiforgery.Test/{AntiforgeryTokenGeneratorTest.cs => DefaultAntiforgeryTokenGeneratorTest.cs} (94%) rename test/Microsoft.AspNet.Antiforgery.Test/{AntiforgeryTokenSerializerTest.cs => DefaultAntiforgeryTokenSerializerTest.cs} (93%) rename test/Microsoft.AspNet.Antiforgery.Test/{AntiforgeryTokenStoreTest.cs => DefaultAntiforgeryTokenStoreTest.cs} (94%) rename test/Microsoft.AspNet.Antiforgery.Test/{ClaimUidExtractorTest.cs => DefaultClaimUidExtractorTest.cs} (98%) diff --git a/samples/AntiforgerySample/FormPostSampleMiddleware.cs b/samples/AntiforgerySample/FormPostSampleMiddleware.cs index 946513badd..dc27fb7abe 100644 --- a/samples/AntiforgerySample/FormPostSampleMiddleware.cs +++ b/samples/AntiforgerySample/FormPostSampleMiddleware.cs @@ -11,13 +11,13 @@ namespace AntiforgerySample { public class FormPostSampleMiddleware { - private readonly Antiforgery _antiforgery; + private readonly IAntiforgery _antiforgery; private readonly AntiforgeryOptions _options; private readonly RequestDelegate _next; public FormPostSampleMiddleware( RequestDelegate next, - Antiforgery antiforgery, + IAntiforgery antiforgery, IOptions options) { _next = next; @@ -39,20 +39,19 @@ namespace AntiforgerySample "; - var tokenSet = _antiforgery.GetTokens(context, oldCookieToken: null); - context.Response.Cookies.Delete(_options.CookieName); - context.Response.Cookies.Append(_options.CookieName, tokenSet.CookieToken); + var tokenSet = _antiforgery.GetAndStoreTokens(context); await context.Response.WriteAsync(string.Format(page, _options.FormFieldName, tokenSet.FormToken)); } else if (context.Request.Method == "POST") { // This will throw if invalid. - await _antiforgery.ValidateAsync(context); + await _antiforgery.ValidateRequestAsync(context); var page = @"

Everything is fine

+

Try Again

"; diff --git a/src/Microsoft.AspNet.Antiforgery/Antiforgery.cs b/src/Microsoft.AspNet.Antiforgery/DefaultAntiforgery.cs similarity index 52% rename from src/Microsoft.AspNet.Antiforgery/Antiforgery.cs rename to src/Microsoft.AspNet.Antiforgery/DefaultAntiforgery.cs index b2c2838643..aba5de914b 100644 --- a/src/Microsoft.AspNet.Antiforgery/Antiforgery.cs +++ b/src/Microsoft.AspNet.Antiforgery/DefaultAntiforgery.cs @@ -15,7 +15,7 @@ namespace Microsoft.AspNet.Antiforgery /// Provides access to the anti-forgery system, which provides protection against /// Cross-site Request Forgery (XSRF, also called CSRF) attacks. ///
- public class Antiforgery + public class DefaultAntiforgery : IAntiforgery { private readonly IHtmlEncoder _htmlEncoder; private readonly AntiforgeryOptions _options; @@ -23,7 +23,7 @@ namespace Microsoft.AspNet.Antiforgery private readonly IAntiforgeryTokenSerializer _tokenSerializer; private readonly IAntiforgeryTokenStore _tokenStore; - public Antiforgery( + public DefaultAntiforgery( IOptions antiforgeryOptionsAccessor, IAntiforgeryTokenGenerator tokenGenerator, IAntiforgeryTokenSerializer tokenSerializer, @@ -37,74 +37,42 @@ namespace Microsoft.AspNet.Antiforgery _htmlEncoder = htmlEncoder; } - /// - /// Generates an anti-forgery token for this request. This token can - /// be validated by calling the Validate() method. - /// - /// The HTTP context associated with the current call. - /// An HTML string corresponding to an <input type="hidden"> - /// element. This element should be put inside a <form>. - /// - /// This method has a side effect: - /// A response cookie is set if there is no valid cookie associated with the request. - /// + /// public string GetHtml([NotNull] HttpContext context) { CheckSSLConfig(context); - var cookieToken = GetCookieTokenDoesNotThrow(context); - var tokenSet = GetTokens(context, cookieToken); - cookieToken = tokenSet.CookieToken; - var formToken = tokenSet.FormToken; - - SaveCookieTokenAndHeader(context, cookieToken); + var tokenSet = GetAndStoreTokens(context); var inputTag = string.Format( "", _htmlEncoder.HtmlEncode(_options.FormFieldName), _htmlEncoder.HtmlEncode("hidden"), - _htmlEncoder.HtmlEncode(_tokenSerializer.Serialize(formToken))); + _htmlEncoder.HtmlEncode(tokenSet.FormToken)); return inputTag; } - /// - /// Generates an anti-forgery token pair (cookie and form token) for this request. - /// This method is similar to GetHtml(HttpContext context), but this method gives the caller control - /// over how to persist the returned values. To validate these tokens, call the - /// appropriate overload of Validate. - /// - /// The HTTP context associated with the current call. - /// The anti-forgery token - if any - that already existed - /// for this request. May be null. The anti-forgery system will try to reuse this cookie - /// value when generating a matching form token. - /// - /// Unlike the GetHtml(HttpContext context) method, this method has no side effect. The caller - /// is responsible for setting the response cookie and injecting the returned - /// form token as appropriate. - /// - public AntiforgeryTokenSet GetTokens([NotNull] HttpContext context, string oldCookieToken) + /// + public AntiforgeryTokenSet GetAndStoreTokens([NotNull] HttpContext context) { - // Will contain a new cookie value if the old cookie token - // was null or invalid. If this value is non-null when the method completes, the caller - // must persist this value in the form of a response cookie, and the existing cookie value - // should be discarded. If this value is null when the method completes, the existing - // cookie value was valid and needn't be modified. CheckSSLConfig(context); - - var deserializedcookieToken = DeserializeTokenDoesNotThrow(oldCookieToken); - var tokenSet = GetTokens(context, deserializedcookieToken); - - var serializedCookieToken = Serialize(tokenSet.CookieToken); - var serializedFormToken = Serialize(tokenSet.FormToken); - return new AntiforgeryTokenSet(serializedFormToken, serializedCookieToken); + + var tokenSet = GetTokensInternal(context); + SaveCookieTokenAndHeader(context, tokenSet.CookieToken); + return Serialize(tokenSet); } - /// - /// Validates an anti-forgery token that was supplied for this request. - /// The anti-forgery token may be generated by calling GetHtml(HttpContext context). - /// - /// The HTTP context associated with the current call. - public async Task ValidateAsync([NotNull] HttpContext context) + /// + public AntiforgeryTokenSet GetTokens([NotNull] HttpContext context) + { + CheckSSLConfig(context); + + var tokenSet = GetTokensInternal(context); + return Serialize(tokenSet); + } + + /// + public async Task ValidateRequestAsync([NotNull] HttpContext context) { CheckSSLConfig(context); @@ -116,19 +84,14 @@ namespace Microsoft.AspNet.Antiforgery _tokenGenerator.ValidateTokens(context, cookieToken, formToken); } - /// - /// Validates an anti-forgery token pair that was generated by the GetTokens method. - /// - /// The HTTP context associated with the current call. - /// The token that was supplied in the request cookie. - /// The token that was supplied in the request form body. - public void Validate([NotNull] HttpContext context, string cookieToken, string formToken) + /// + public void ValidateTokens([NotNull] HttpContext context, AntiforgeryTokenSet antiforgeryTokenSet) { CheckSSLConfig(context); // Extract cookie & form tokens - var deserializedCookieToken = DeserializeToken(cookieToken); - var deserializedFormToken = DeserializeToken(formToken); + var deserializedCookieToken = DeserializeToken(antiforgeryTokenSet.CookieToken); + var deserializedFormToken = DeserializeToken(antiforgeryTokenSet.FormToken); // Validate _tokenGenerator.ValidateTokens( @@ -137,28 +100,13 @@ namespace Microsoft.AspNet.Antiforgery deserializedFormToken); } - /// - /// Validates an anti-forgery token pair that was generated by the GetTokens method. - /// - /// The HTTP context associated with the current call. - /// The anti-forgery token pair (cookie and form token) for this request. - /// - public void Validate([NotNull] HttpContext context, AntiforgeryTokenSet AntiforgeryTokenSet) - { - Validate(context, AntiforgeryTokenSet.CookieToken, AntiforgeryTokenSet.FormToken); - } - - /// - /// Generates and sets an anti-forgery cookie if one is not available or not valid. Also sets response headers. - /// - /// The HTTP context associated with the current call. + /// public void SetCookieTokenAndHeader([NotNull] HttpContext context) { CheckSSLConfig(context); var cookieToken = GetCookieTokenDoesNotThrow(context); cookieToken = ValidateAndGenerateNewCookieToken(cookieToken); - SaveCookieTokenAndHeader(context, cookieToken); } @@ -177,13 +125,13 @@ namespace Microsoft.AspNet.Antiforgery } private void SaveCookieTokenAndHeader( - [NotNull] HttpContext httpContext, + [NotNull] HttpContext context, AntiforgeryToken cookieToken) { if (cookieToken != null) { // Persist the new cookie if it is not null. - _tokenStore.SaveCookieToken(httpContext, cookieToken); + _tokenStore.SaveCookieToken(context, cookieToken); } if (!_options.SuppressXFrameOptionsHeader) @@ -191,13 +139,13 @@ namespace Microsoft.AspNet.Antiforgery // Adding X-Frame-Options header to prevent ClickJacking. See // http://tools.ietf.org/html/draft-ietf-websec-x-frame-options-10 // for more information. - httpContext.Response.Headers.Set("X-Frame-Options", "SAMEORIGIN"); + context.Response.Headers.Set("X-Frame-Options", "SAMEORIGIN"); } } - private void CheckSSLConfig(HttpContext httpContext) + private void CheckSSLConfig(HttpContext context) { - if (_options.RequireSSL && !httpContext.Request.IsHttps) + if (_options.RequireSSL && !context.Request.IsHttps) { throw new InvalidOperationException(Resources.AntiforgeryWorker_RequireSSL); } @@ -223,11 +171,11 @@ namespace Microsoft.AspNet.Antiforgery } } - private AntiforgeryToken GetCookieTokenDoesNotThrow(HttpContext httpContext) + private AntiforgeryToken GetCookieTokenDoesNotThrow(HttpContext context) { try { - return _tokenStore.GetCookieToken(httpContext); + return _tokenStore.GetCookieToken(context); } catch { @@ -236,15 +184,16 @@ namespace Microsoft.AspNet.Antiforgery } } - private AntiforgeryTokenSetInternal GetTokens(HttpContext httpContext, AntiforgeryToken cookieToken) + private AntiforgeryTokenSetInternal GetTokensInternal(HttpContext context) { + var cookieToken = GetCookieTokenDoesNotThrow(context); var newCookieToken = ValidateAndGenerateNewCookieToken(cookieToken); if (newCookieToken != null) { cookieToken = newCookieToken; } var formToken = _tokenGenerator.GenerateFormToken( - httpContext, + context, cookieToken); return new AntiforgeryTokenSetInternal() @@ -255,9 +204,11 @@ namespace Microsoft.AspNet.Antiforgery }; } - private string Serialize(AntiforgeryToken token) + private AntiforgeryTokenSet Serialize(AntiforgeryTokenSetInternal tokenSet) { - return (token != null) ? _tokenSerializer.Serialize(token) : null; + return new AntiforgeryTokenSet( + tokenSet.FormToken != null ? _tokenSerializer.Serialize(tokenSet.FormToken) : null, + tokenSet.CookieToken != null ? _tokenSerializer.Serialize(tokenSet.CookieToken) : null); } private class AntiforgeryTokenSetInternal diff --git a/src/Microsoft.AspNet.Antiforgery/AntiforgeryContextAccessor.cs b/src/Microsoft.AspNet.Antiforgery/DefaultAntiforgeryContextAccessor.cs similarity index 77% rename from src/Microsoft.AspNet.Antiforgery/AntiforgeryContextAccessor.cs rename to src/Microsoft.AspNet.Antiforgery/DefaultAntiforgeryContextAccessor.cs index 3a2806a10f..c19eb312e2 100644 --- a/src/Microsoft.AspNet.Antiforgery/AntiforgeryContextAccessor.cs +++ b/src/Microsoft.AspNet.Antiforgery/DefaultAntiforgeryContextAccessor.cs @@ -3,7 +3,7 @@ namespace Microsoft.AspNet.Antiforgery { - public class AntiforgeryContextAccessor : IAntiforgeryContextAccessor + public class DefaultAntiforgeryContextAccessor : IAntiforgeryContextAccessor { public AntiforgeryContext Value { get; set; } } diff --git a/src/Microsoft.AspNet.Antiforgery/AntiforgeryTokenGenerator.cs b/src/Microsoft.AspNet.Antiforgery/DefaultAntiforgeryTokenGenerator.cs similarity index 98% rename from src/Microsoft.AspNet.Antiforgery/AntiforgeryTokenGenerator.cs rename to src/Microsoft.AspNet.Antiforgery/DefaultAntiforgeryTokenGenerator.cs index 493e4a3495..6ecc8048fb 100644 --- a/src/Microsoft.AspNet.Antiforgery/AntiforgeryTokenGenerator.cs +++ b/src/Microsoft.AspNet.Antiforgery/DefaultAntiforgeryTokenGenerator.cs @@ -9,13 +9,13 @@ using Microsoft.Framework.OptionsModel; namespace Microsoft.AspNet.Antiforgery { - public class AntiforgeryTokenGenerator : IAntiforgeryTokenGenerator + public class DefaultAntiforgeryTokenGenerator : IAntiforgeryTokenGenerator { private readonly IClaimUidExtractor _claimUidExtractor; private readonly AntiforgeryOptions _options; private readonly IAntiforgeryAdditionalDataProvider _additionalDataProvider; - public AntiforgeryTokenGenerator( + public DefaultAntiforgeryTokenGenerator( IOptions optionsAccessor, IClaimUidExtractor claimUidExtractor, IAntiforgeryAdditionalDataProvider additionalDataProvider) diff --git a/src/Microsoft.AspNet.Antiforgery/AntiforgeryTokenSerializer.cs b/src/Microsoft.AspNet.Antiforgery/DefaultAntiforgeryTokenSerializer.cs similarity index 96% rename from src/Microsoft.AspNet.Antiforgery/AntiforgeryTokenSerializer.cs rename to src/Microsoft.AspNet.Antiforgery/DefaultAntiforgeryTokenSerializer.cs index f3d79844f7..971af9c3a0 100644 --- a/src/Microsoft.AspNet.Antiforgery/AntiforgeryTokenSerializer.cs +++ b/src/Microsoft.AspNet.Antiforgery/DefaultAntiforgeryTokenSerializer.cs @@ -9,14 +9,14 @@ using Microsoft.Framework.Internal; namespace Microsoft.AspNet.Antiforgery { - public class AntiforgeryTokenSerializer : IAntiforgeryTokenSerializer + public class DefaultAntiforgeryTokenSerializer : IAntiforgeryTokenSerializer { private static readonly string Purpose = "Microsoft.AspNet.Antiforgery.AntiforgeryToken.v1"; private readonly IDataProtector _cryptoSystem; private const byte TokenVersion = 0x01; - public AntiforgeryTokenSerializer([NotNull] IDataProtectionProvider provider) + public DefaultAntiforgeryTokenSerializer([NotNull] IDataProtectionProvider provider) { _cryptoSystem = provider.CreateProtector(Purpose); } diff --git a/src/Microsoft.AspNet.Antiforgery/AntiforgeryTokenStore.cs b/src/Microsoft.AspNet.Antiforgery/DefaultAntiforgeryTokenStore.cs similarity index 96% rename from src/Microsoft.AspNet.Antiforgery/AntiforgeryTokenStore.cs rename to src/Microsoft.AspNet.Antiforgery/DefaultAntiforgeryTokenStore.cs index ecf17ad0a7..7ea53b3d8b 100644 --- a/src/Microsoft.AspNet.Antiforgery/AntiforgeryTokenStore.cs +++ b/src/Microsoft.AspNet.Antiforgery/DefaultAntiforgeryTokenStore.cs @@ -11,12 +11,12 @@ using Microsoft.Framework.OptionsModel; namespace Microsoft.AspNet.Antiforgery { // Saves anti-XSRF tokens split between HttpRequest.Cookies and HttpRequest.Form - public class AntiforgeryTokenStore : IAntiforgeryTokenStore + public class DefaultAntiforgeryTokenStore : IAntiforgeryTokenStore { private readonly AntiforgeryOptions _options; private readonly IAntiforgeryTokenSerializer _tokenSerializer; - public AntiforgeryTokenStore( + public DefaultAntiforgeryTokenStore( [NotNull] IOptions optionsAccessor, [NotNull] IAntiforgeryTokenSerializer tokenSerializer) { diff --git a/src/Microsoft.AspNet.Antiforgery/IAntiforgery.cs b/src/Microsoft.AspNet.Antiforgery/IAntiforgery.cs new file mode 100644 index 0000000000..2be08cacab --- /dev/null +++ b/src/Microsoft.AspNet.Antiforgery/IAntiforgery.cs @@ -0,0 +1,74 @@ +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System.Threading.Tasks; +using Microsoft.AspNet.Http; +using Microsoft.Framework.Internal; + +namespace Microsoft.AspNet.Antiforgery +{ + /// + /// Provides access to the antiforgery system, which provides protection against + /// Cross-site Request Forgery (XSRF, also called CSRF) attacks. + /// + public interface IAntiforgery + { + /// + /// Generates an input field for an antiforgery token. + /// + /// The associated with the current call. + /// + /// A string containing an <input type="hidden"> element. This element should be put inside + /// a <form>. + /// + /// + /// This method has a side effect: + /// A response cookie is set if there is no valid cookie associated with the request. + /// + string GetHtml([NotNull] HttpContext context); + + /// + /// Generates an for this request and stores the cookie token + /// in the response. + /// + /// The associated with the current call. + /// An with tokens for the response. + /// + /// This method has a side effect: + /// A response cookie is set if there is no valid cookie associated with the request. + /// + AntiforgeryTokenSet GetAndStoreTokens([NotNull] HttpContext context); + + /// + /// Generates an for this request. + /// + /// The associated with the current call. + /// + /// Unlike , this method has no side effect. The caller + /// is responsible for setting the response cookie and injecting the returned + /// form token as appropriate. + /// + AntiforgeryTokenSet GetTokens([NotNull] HttpContext context); + + /// + /// Validates an antiforgery token that was supplied as part of the request. + /// + /// The associated with the current call. + Task ValidateRequestAsync([NotNull] HttpContext context); + + /// + /// Validates an for the current request. + /// + /// The associated with the current call. + /// + /// The (cookie and form token) for this request. + /// + void ValidateTokens([NotNull] HttpContext context, AntiforgeryTokenSet antiforgeryTokenSet); + + /// + /// Generates and stores an antiforgery cookie token if one is not available or not valid. + /// + /// The associated with the current call. + void SetCookieTokenAndHeader([NotNull] HttpContext context); + } +} diff --git a/src/Microsoft.AspNet.Antiforgery/ServiceCollectionExtensions.cs b/src/Microsoft.AspNet.Antiforgery/ServiceCollectionExtensions.cs index f6dcee30e1..34db9b5026 100644 --- a/src/Microsoft.AspNet.Antiforgery/ServiceCollectionExtensions.cs +++ b/src/Microsoft.AspNet.Antiforgery/ServiceCollectionExtensions.cs @@ -19,12 +19,12 @@ namespace Microsoft.Framework.DependencyInjection services.TryAddEnumerable( ServiceDescriptor.Transient, AntiforgeryOptionsSetup>()); - services.TryAddSingleton(); - services.TryAddSingleton(); - services.TryAddSingleton(); + services.TryAddSingleton(); + services.TryAddSingleton(); + services.TryAddSingleton(); + services.TryAddSingleton(); services.TryAddSingleton(); - services.TryAddSingleton(); - services.TryAddScoped(); + services.TryAddScoped(); services.TryAddSingleton(); return services; } diff --git a/test/Microsoft.AspNet.Antiforgery.Test/AntiforgeryTest.cs b/test/Microsoft.AspNet.Antiforgery.Test/DefaultAntiforgeryTest.cs similarity index 87% rename from test/Microsoft.AspNet.Antiforgery.Test/AntiforgeryTest.cs rename to test/Microsoft.AspNet.Antiforgery.Test/DefaultAntiforgeryTest.cs index 6b1e4c5368..ee297fe0d8 100644 --- a/test/Microsoft.AspNet.Antiforgery.Test/AntiforgeryTest.cs +++ b/test/Microsoft.AspNet.Antiforgery.Test/DefaultAntiforgeryTest.cs @@ -18,7 +18,7 @@ namespace Microsoft.AspNet.Antiforgery public class AntiforgeryTest { [Fact] - public async Task ChecksSSL_ValidateAsync_Throws() + public async Task ChecksSSL_ValidateRequestAsync_Throws() { // Arrange var httpContext = new DefaultHttpContext(); @@ -32,7 +32,7 @@ namespace Microsoft.AspNet.Antiforgery // Act & Assert var exception = await Assert.ThrowsAsync( - async () => await antiforgery.ValidateAsync(httpContext)); + async () => await antiforgery.ValidateRequestAsync(httpContext)); Assert.Equal( @"The anti-forgery system has the configuration value AntiforgeryOptions.RequireSsl = true, " + "but the current request is not an SSL request.", @@ -40,7 +40,7 @@ namespace Microsoft.AspNet.Antiforgery } [Fact] - public void ChecksSSL_Validate_Throws() + public void ChecksSSL_ValidateTokens_Throws() { // Arrange var httpContext = new DefaultHttpContext(); @@ -54,7 +54,7 @@ namespace Microsoft.AspNet.Antiforgery // Act & Assert var exception = Assert.Throws( - () => antiforgery.Validate(httpContext, cookieToken: null, formToken: null)); + () => antiforgery.ValidateTokens(httpContext, new AntiforgeryTokenSet("hello", "world"))); Assert.Equal( @"The anti-forgery system has the configuration value AntiforgeryOptions.RequireSsl = true, " + "but the current request is not an SSL request.", @@ -83,6 +83,28 @@ namespace Microsoft.AspNet.Antiforgery exception.Message); } + [Fact] + public void ChecksSSL_GetAndStoreTokens_Throws() + { + // Arrange + var httpContext = new DefaultHttpContext(); + + var options = new AntiforgeryOptions() + { + RequireSSL = true + }; + + var antiforgery = GetAntiforgery(options); + + // Act & Assert + var exception = Assert.Throws( + () => antiforgery.GetAndStoreTokens(httpContext)); + Assert.Equal( + @"The anti-forgery system has the configuration value AntiforgeryOptions.RequireSsl = true, " + + "but the current request is not an SSL request.", + exception.Message); + } + [Fact] public void ChecksSSL_GetTokens_Throws() { @@ -98,7 +120,29 @@ namespace Microsoft.AspNet.Antiforgery // Act & Assert var exception = Assert.Throws( - () => antiforgery.GetTokens(httpContext, "dkfkfkf")); + () => antiforgery.GetTokens(httpContext)); + Assert.Equal( + @"The anti-forgery system has the configuration value AntiforgeryOptions.RequireSsl = true, " + + "but the current request is not an SSL request.", + exception.Message); + } + + [Fact] + public void ChecksSSL_SetCookieTokenAndHeader_Throws() + { + // Arrange + var httpContext = new DefaultHttpContext(); + + var options = new AntiforgeryOptions() + { + RequireSSL = true + }; + + var antiforgery = GetAntiforgery(options); + + // Act & Assert + var exception = Assert.Throws( + () => antiforgery.SetCookieTokenAndHeader(httpContext)); Assert.Equal( @"The anti-forgery system has the configuration value AntiforgeryOptions.RequireSsl = true, " + "but the current request is not an SSL request.", @@ -108,7 +152,7 @@ namespace Microsoft.AspNet.Antiforgery #if DNX451 [Fact] - public void GetFormInputElement_ExistingInvalidCookieToken_GeneratesANewCookieAndAnAntiforgeryToken() + public void GetHtml_ExistingInvalidCookieToken_GeneratesANewCookieAndAnAntiforgeryToken() { // Arrange var options = new AntiforgeryOptions() @@ -132,7 +176,7 @@ namespace Microsoft.AspNet.Antiforgery } [Fact] - public void GetFormInputElement_ExistingInvalidCookieToken_SwallowsExceptions() + public void GetHtml_ExistingInvalidCookieToken_SwallowsExceptions() { // Arrange var options = new AntiforgeryOptions() @@ -164,7 +208,7 @@ namespace Microsoft.AspNet.Antiforgery } [Fact] - public void GetFormInputElement_ExistingValidCookieToken_GeneratesAnAntiforgeryToken() + public void GetHtml_ExistingValidCookieToken_GeneratesAnAntiforgeryToken() { // Arrange var options = new AntiforgeryOptions() @@ -189,7 +233,7 @@ namespace Microsoft.AspNet.Antiforgery [Theory] [InlineData(false, "SAMEORIGIN")] [InlineData(true, null)] - public void GetFormInputElement_AddsXFrameOptionsHeader(bool suppressXFrameOptions, string expectedHeaderValue) + public void GetHtml_AddsXFrameOptionsHeader(bool suppressXFrameOptions, string expectedHeaderValue) { // Arrange var options = new AntiforgeryOptions() @@ -221,7 +265,7 @@ namespace Microsoft.AspNet.Antiforgery var antiforgery = GetAntiforgery(context); // Act - var tokenset = antiforgery.GetTokens(context.HttpContext, "serialized-old-cookie-token"); + var tokenset = antiforgery.GetTokens(context.HttpContext); // Assert Assert.Equal("serialized-new-cookie-token", tokenset.CookieToken); @@ -248,7 +292,7 @@ namespace Microsoft.AspNet.Antiforgery var antiforgery = GetAntiforgery(context); // Act - var tokenset = antiforgery.GetTokens(context.HttpContext, "serialized-old-cookie-token"); + var tokenset = antiforgery.GetTokens(context.HttpContext); // Assert Assert.Equal("serialized-new-cookie-token", tokenset.CookieToken); @@ -263,11 +307,10 @@ namespace Microsoft.AspNet.Antiforgery new AntiforgeryOptions(), useOldCookie: true, isOldCookieValid: true); - context.TokenStore = null; var antiforgery = GetAntiforgery(context); // Act - var tokenset = antiforgery.GetTokens(context.HttpContext, "serialized-old-cookie-token"); + var tokenset = antiforgery.GetTokens(context.HttpContext); // Assert Assert.Null(tokenset.CookieToken); @@ -294,7 +337,9 @@ namespace Microsoft.AspNet.Antiforgery // Act & assert var exception = Assert.Throws( - () => antiforgery.Validate(context.HttpContext, "cookie-token", "form-token")); + () => antiforgery.ValidateTokens( + context.HttpContext, + new AntiforgeryTokenSet("form-token", "cookie-token"))); Assert.Equal("my-message", exception.Message); } @@ -317,7 +362,7 @@ namespace Microsoft.AspNet.Antiforgery var antiforgery = GetAntiforgery(context); // Act - antiforgery.Validate(context.HttpContext, "cookie-token", "form-token"); + antiforgery.ValidateTokens(context.HttpContext, new AntiforgeryTokenSet("form-token", "cookie-token")); // Assert context.TokenGenerator.Verify(); @@ -338,7 +383,7 @@ namespace Microsoft.AspNet.Antiforgery // Act & assert var exception = await Assert.ThrowsAsync( - async () => await antiforgery.ValidateAsync(context.HttpContext)); + async () => await antiforgery.ValidateRequestAsync(context.HttpContext)); Assert.Equal("my-message", exception.Message); } @@ -356,7 +401,7 @@ namespace Microsoft.AspNet.Antiforgery var antiforgery = GetAntiforgery(context); // Act - await antiforgery.ValidateAsync(context.HttpContext); + await antiforgery.ValidateRequestAsync(context.HttpContext); // Assert context.TokenGenerator.Verify(); @@ -389,7 +434,7 @@ namespace Microsoft.AspNet.Antiforgery #endif - private Antiforgery GetAntiforgery( + private DefaultAntiforgery GetAntiforgery( AntiforgeryOptions options = null, IAntiforgeryTokenGenerator tokenGenerator = null, IAntiforgeryTokenSerializer tokenSerializer = null, @@ -401,7 +446,7 @@ namespace Microsoft.AspNet.Antiforgery optionsManager.Options = options; } - return new Antiforgery( + return new DefaultAntiforgery( antiforgeryOptionsAccessor: optionsManager, tokenGenerator: tokenGenerator, tokenSerializer: tokenSerializer, @@ -418,7 +463,7 @@ namespace Microsoft.AspNet.Antiforgery #if DNX451 - private Antiforgery GetAntiforgery(AntiforgeryMockContext context) + private DefaultAntiforgery GetAntiforgery(AntiforgeryMockContext context) { return GetAntiforgery( context.Options, diff --git a/test/Microsoft.AspNet.Antiforgery.Test/AntiforgeryTokenGeneratorTest.cs b/test/Microsoft.AspNet.Antiforgery.Test/DefaultAntiforgeryTokenGeneratorTest.cs similarity index 94% rename from test/Microsoft.AspNet.Antiforgery.Test/AntiforgeryTokenGeneratorTest.cs rename to test/Microsoft.AspNet.Antiforgery.Test/DefaultAntiforgeryTokenGeneratorTest.cs index 8cf4a67cbb..905a1444a9 100644 --- a/test/Microsoft.AspNet.Antiforgery.Test/AntiforgeryTokenGeneratorTest.cs +++ b/test/Microsoft.AspNet.Antiforgery.Test/DefaultAntiforgeryTokenGeneratorTest.cs @@ -12,13 +12,13 @@ using Xunit; namespace Microsoft.AspNet.Antiforgery { - public class AntiforgeryTokenGeneratorProviderTest + public class DefaultAntiforgeryTokenGeneratorProviderTest { [Fact] public void GenerateCookieToken() { // Arrange - var tokenProvider = new AntiforgeryTokenGenerator( + var tokenProvider = new DefaultAntiforgeryTokenGenerator( optionsAccessor: new TestOptionsManager(), claimUidExtractor: null, additionalDataProvider: null); @@ -39,7 +39,7 @@ namespace Microsoft.AspNet.Antiforgery httpContext.User = new ClaimsPrincipal(new ClaimsIdentity()); Assert.False(httpContext.User.Identity.IsAuthenticated); - var tokenProvider = new AntiforgeryTokenGenerator( + var tokenProvider = new DefaultAntiforgeryTokenGenerator( optionsAccessor: new TestOptionsManager(), claimUidExtractor: null, additionalDataProvider: null); @@ -73,7 +73,7 @@ namespace Microsoft.AspNet.Antiforgery var options = new AntiforgeryOptions(); var claimUidExtractor = new Mock().Object; - var tokenProvider = new AntiforgeryTokenGenerator( + var tokenProvider = new DefaultAntiforgeryTokenGenerator( optionsAccessor: new TestOptionsManager(), claimUidExtractor: claimUidExtractor, additionalDataProvider: null); @@ -107,7 +107,7 @@ namespace Microsoft.AspNet.Antiforgery var claimUidExtractor = new Mock().Object; - var tokenProvider = new AntiforgeryTokenGenerator( + var tokenProvider = new DefaultAntiforgeryTokenGenerator( optionsAccessor: new TestOptionsManager(), claimUidExtractor: claimUidExtractor, additionalDataProvider: mockAdditionalDataProvider.Object); @@ -146,7 +146,7 @@ namespace Microsoft.AspNet.Antiforgery mockClaimUidExtractor.Setup(o => o.ExtractClaimUid(identity)) .Returns(base64ClaimUId); - var tokenProvider = new AntiforgeryTokenGenerator( + var tokenProvider = new DefaultAntiforgeryTokenGenerator( optionsAccessor: new TestOptionsManager(), claimUidExtractor: mockClaimUidExtractor.Object, additionalDataProvider: null); @@ -180,7 +180,7 @@ namespace Microsoft.AspNet.Antiforgery var claimUidExtractor = new Mock().Object; - var tokenProvider = new AntiforgeryTokenGenerator( + var tokenProvider = new DefaultAntiforgeryTokenGenerator( optionsAccessor: new TestOptionsManager(), claimUidExtractor: claimUidExtractor, additionalDataProvider: null); @@ -207,7 +207,7 @@ namespace Microsoft.AspNet.Antiforgery IsSessionToken = false }; - var tokenProvider = new AntiforgeryTokenGenerator( + var tokenProvider = new DefaultAntiforgeryTokenGenerator( optionsAccessor: new TestOptionsManager(), claimUidExtractor: null, additionalDataProvider: null); @@ -224,7 +224,7 @@ namespace Microsoft.AspNet.Antiforgery { // Arrange AntiforgeryToken cookieToken = null; - var tokenProvider = new AntiforgeryTokenGenerator( + var tokenProvider = new DefaultAntiforgeryTokenGenerator( optionsAccessor: new TestOptionsManager(), claimUidExtractor: null, additionalDataProvider: null); @@ -245,7 +245,7 @@ namespace Microsoft.AspNet.Antiforgery IsSessionToken = true }; - var tokenProvider = new AntiforgeryTokenGenerator( + var tokenProvider = new DefaultAntiforgeryTokenGenerator( optionsAccessor: new TestOptionsManager(), claimUidExtractor: null, additionalDataProvider: null); @@ -272,7 +272,7 @@ namespace Microsoft.AspNet.Antiforgery CookieName = "my-cookie-name" }; - var tokenProvider = new AntiforgeryTokenGenerator( + var tokenProvider = new DefaultAntiforgeryTokenGenerator( optionsAccessor: new TestOptionsManager(options), claimUidExtractor: null, additionalDataProvider: null); @@ -298,7 +298,7 @@ namespace Microsoft.AspNet.Antiforgery FormFieldName = "my-form-field-name" }; - var tokenProvider = new AntiforgeryTokenGenerator( + var tokenProvider = new DefaultAntiforgeryTokenGenerator( optionsAccessor: new TestOptionsManager(options), claimUidExtractor: null, additionalDataProvider: null); @@ -326,7 +326,7 @@ namespace Microsoft.AspNet.Antiforgery FormFieldName = "my-form-field-name" }; - var tokenProvider = new AntiforgeryTokenGenerator( + var tokenProvider = new DefaultAntiforgeryTokenGenerator( optionsAccessor: new TestOptionsManager(options), claimUidExtractor: null, additionalDataProvider: null); @@ -359,7 +359,7 @@ namespace Microsoft.AspNet.Antiforgery var sessionToken = new AntiforgeryToken() { IsSessionToken = true }; var fieldtoken = new AntiforgeryToken() { IsSessionToken = false }; - var tokenProvider = new AntiforgeryTokenGenerator( + var tokenProvider = new DefaultAntiforgeryTokenGenerator( optionsAccessor: new TestOptionsManager(), claimUidExtractor: null, additionalDataProvider: null); @@ -397,7 +397,7 @@ namespace Microsoft.AspNet.Antiforgery mockClaimUidExtractor.Setup(o => o.ExtractClaimUid(identity)) .Returns((string)null); - var tokenProvider = new AntiforgeryTokenGenerator( + var tokenProvider = new DefaultAntiforgeryTokenGenerator( optionsAccessor: new TestOptionsManager(), claimUidExtractor: mockClaimUidExtractor.Object, additionalDataProvider: null); @@ -432,7 +432,7 @@ namespace Microsoft.AspNet.Antiforgery mockClaimUidExtractor.Setup(o => o.ExtractClaimUid(identity)) .Returns(Convert.ToBase64String(differentToken.GetData())); - var tokenProvider = new AntiforgeryTokenGenerator( + var tokenProvider = new DefaultAntiforgeryTokenGenerator( optionsAccessor: new TestOptionsManager(), claimUidExtractor: mockClaimUidExtractor.Object, additionalDataProvider: null); @@ -466,7 +466,7 @@ namespace Microsoft.AspNet.Antiforgery mockAdditionalDataProvider.Setup(o => o.ValidateAdditionalData(httpContext, "some-additional-data")) .Returns(false); - var tokenProvider = new AntiforgeryTokenGenerator( + var tokenProvider = new DefaultAntiforgeryTokenGenerator( optionsAccessor: new TestOptionsManager(), claimUidExtractor: null, additionalDataProvider: mockAdditionalDataProvider.Object); @@ -498,7 +498,7 @@ namespace Microsoft.AspNet.Antiforgery mockAdditionalDataProvider.Setup(o => o.ValidateAdditionalData(httpContext, "some-additional-data")) .Returns(true); - var tokenProvider = new AntiforgeryTokenGenerator( + var tokenProvider = new DefaultAntiforgeryTokenGenerator( optionsAccessor: new TestOptionsManager(), claimUidExtractor: null, additionalDataProvider: mockAdditionalDataProvider.Object); @@ -531,7 +531,7 @@ namespace Microsoft.AspNet.Antiforgery mockAdditionalDataProvider.Setup(o => o.ValidateAdditionalData(httpContext, "some-additional-data")) .Returns(true); - var tokenProvider = new AntiforgeryTokenGenerator( + var tokenProvider = new DefaultAntiforgeryTokenGenerator( optionsAccessor: new TestOptionsManager(), claimUidExtractor: new Mock().Object, additionalDataProvider: mockAdditionalDataProvider.Object); @@ -563,7 +563,7 @@ namespace Microsoft.AspNet.Antiforgery mockClaimUidExtractor.Setup(o => o.ExtractClaimUid(identity)) .Returns(Convert.ToBase64String(fieldtoken.ClaimUid.GetData())); - var tokenProvider = new AntiforgeryTokenGenerator( + var tokenProvider = new DefaultAntiforgeryTokenGenerator( optionsAccessor: new TestOptionsManager(), claimUidExtractor: mockClaimUidExtractor.Object, additionalDataProvider: null); diff --git a/test/Microsoft.AspNet.Antiforgery.Test/AntiforgeryTokenSerializerTest.cs b/test/Microsoft.AspNet.Antiforgery.Test/DefaultAntiforgeryTokenSerializerTest.cs similarity index 93% rename from test/Microsoft.AspNet.Antiforgery.Test/AntiforgeryTokenSerializerTest.cs rename to test/Microsoft.AspNet.Antiforgery.Test/DefaultAntiforgeryTokenSerializerTest.cs index 31fc024721..45d4646fc2 100644 --- a/test/Microsoft.AspNet.Antiforgery.Test/AntiforgeryTokenSerializerTest.cs +++ b/test/Microsoft.AspNet.Antiforgery.Test/DefaultAntiforgeryTokenSerializerTest.cs @@ -11,7 +11,7 @@ using Xunit; namespace Microsoft.AspNet.Antiforgery { - public class AntiforgeryTokenSerializerTest + public class DefaultAntiforgeryTokenSerializerTest { private static readonly Mock _dataProtector = GetDataProtector(); private static readonly BinaryBlob _claimUid = new BinaryBlob(256, new byte[] { 0x6F, 0x16, 0x48, 0xE9, 0x72, 0x49, 0xAA, 0x58, 0x75, 0x40, 0x36, 0xA6, 0x7E, 0x24, 0x8C, 0xF0, 0x44, 0xF0, 0x7E, 0xCF, 0xB0, 0xED, 0x38, 0x75, 0x56, 0xCE, 0x02, 0x9A, 0x4F, 0x9A, 0x40, 0xE0 }); @@ -46,7 +46,7 @@ namespace Microsoft.AspNet.Antiforgery public void Deserialize_BadToken_Throws(string serializedToken) { // Arrange - var testSerializer = new AntiforgeryTokenSerializer(_dataProtector.Object); + var testSerializer = new DefaultAntiforgeryTokenSerializer(_dataProtector.Object); // Act & assert var ex = Assert.Throws(() => testSerializer.Deserialize(serializedToken)); @@ -57,7 +57,7 @@ namespace Microsoft.AspNet.Antiforgery public void Serialize_FieldToken_WithClaimUid_TokenRoundTripSuccessful() { // Arrange - var testSerializer = new AntiforgeryTokenSerializer(_dataProtector.Object); + var testSerializer = new DefaultAntiforgeryTokenSerializer(_dataProtector.Object); //"01" // Version //+ "705EEDCC7D42F1D6B3B98A593625BB4C" // SecurityToken @@ -87,7 +87,7 @@ namespace Microsoft.AspNet.Antiforgery public void Serialize_FieldToken_WithUsername_TokenRoundTripSuccessful() { // Arrange - var testSerializer = new AntiforgeryTokenSerializer(_dataProtector.Object); + var testSerializer = new DefaultAntiforgeryTokenSerializer(_dataProtector.Object); //"01" // Version //+ "705EEDCC7D42F1D6B3B98A593625BB4C" // SecurityToken @@ -118,7 +118,7 @@ namespace Microsoft.AspNet.Antiforgery public void Serialize_SessionToken_TokenRoundTripSuccessful() { // Arrange - var testSerializer = new AntiforgeryTokenSerializer(_dataProtector.Object); + var testSerializer = new DefaultAntiforgeryTokenSerializer(_dataProtector.Object); //"01" // Version //+ "705EEDCC7D42F1D6B3B98A593625BB4C" // SecurityToken diff --git a/test/Microsoft.AspNet.Antiforgery.Test/AntiforgeryTokenStoreTest.cs b/test/Microsoft.AspNet.Antiforgery.Test/DefaultAntiforgeryTokenStoreTest.cs similarity index 94% rename from test/Microsoft.AspNet.Antiforgery.Test/AntiforgeryTokenStoreTest.cs rename to test/Microsoft.AspNet.Antiforgery.Test/DefaultAntiforgeryTokenStoreTest.cs index 1753b8ce0e..b1c251e5f2 100644 --- a/test/Microsoft.AspNet.Antiforgery.Test/AntiforgeryTokenStoreTest.cs +++ b/test/Microsoft.AspNet.Antiforgery.Test/DefaultAntiforgeryTokenStoreTest.cs @@ -13,7 +13,7 @@ using Xunit; namespace Microsoft.AspNet.Antiforgery { - public class AntiforgeryTokenStoreTest + public class DefaultAntiforgeryTokenStoreTest { private readonly string _cookieName = "cookie-name"; @@ -29,7 +29,7 @@ namespace Microsoft.AspNet.Antiforgery mockHttpContext .Setup(o => o.Request.Cookies) .Returns(requestCookies.Object); - var contextAccessor = new AntiforgeryContextAccessor(); + var contextAccessor = new DefaultAntiforgeryContextAccessor(); mockHttpContext.SetupGet(o => o.RequestServices) .Returns(GetServiceProvider(contextAccessor)); var options = new AntiforgeryOptions() @@ -37,7 +37,7 @@ namespace Microsoft.AspNet.Antiforgery CookieName = _cookieName }; - var tokenStore = new AntiforgeryTokenStore( + var tokenStore = new DefaultAntiforgeryTokenStore( optionsAccessor: new TestOptionsManager(options), tokenSerializer: null); @@ -60,7 +60,7 @@ namespace Microsoft.AspNet.Antiforgery mockHttpContext .Setup(o => o.Request.Cookies) .Returns(requestCookies.Object); - var contextAccessor = new AntiforgeryContextAccessor(); + var contextAccessor = new DefaultAntiforgeryContextAccessor(); mockHttpContext.SetupGet(o => o.RequestServices) .Returns(GetServiceProvider(contextAccessor)); @@ -72,7 +72,7 @@ namespace Microsoft.AspNet.Antiforgery CookieName = _cookieName }; - var tokenStore = new AntiforgeryTokenStore( + var tokenStore = new DefaultAntiforgeryTokenStore( optionsAccessor: new TestOptionsManager(options), tokenSerializer: null); @@ -94,7 +94,7 @@ namespace Microsoft.AspNet.Antiforgery CookieName = _cookieName }; - var tokenStore = new AntiforgeryTokenStore( + var tokenStore = new DefaultAntiforgeryTokenStore( optionsAccessor: new TestOptionsManager(options), tokenSerializer: null); @@ -122,7 +122,7 @@ namespace Microsoft.AspNet.Antiforgery CookieName = _cookieName }; - var tokenStore = new AntiforgeryTokenStore( + var tokenStore = new DefaultAntiforgeryTokenStore( optionsAccessor: new TestOptionsManager(options), tokenSerializer: mockSerializer.Object); @@ -148,7 +148,7 @@ namespace Microsoft.AspNet.Antiforgery CookieName = _cookieName }; - var tokenStore = new AntiforgeryTokenStore( + var tokenStore = new DefaultAntiforgeryTokenStore( optionsAccessor: new TestOptionsManager(options), tokenSerializer: mockSerializer.Object); @@ -177,7 +177,7 @@ namespace Microsoft.AspNet.Antiforgery FormFieldName = "form-field-name", }; - var tokenStore = new AntiforgeryTokenStore( + var tokenStore = new DefaultAntiforgeryTokenStore( optionsAccessor: new TestOptionsManager(options), tokenSerializer: null); @@ -213,7 +213,7 @@ namespace Microsoft.AspNet.Antiforgery FormFieldName = "form-field-name", }; - var tokenStore = new AntiforgeryTokenStore( + var tokenStore = new DefaultAntiforgeryTokenStore( optionsAccessor: new TestOptionsManager(options), tokenSerializer: mockSerializer.Object); @@ -248,7 +248,7 @@ namespace Microsoft.AspNet.Antiforgery FormFieldName = "form-field-name", }; - var tokenStore = new AntiforgeryTokenStore( + var tokenStore = new DefaultAntiforgeryTokenStore( optionsAccessor: new TestOptionsManager(options), tokenSerializer: mockSerializer.Object); @@ -275,7 +275,7 @@ namespace Microsoft.AspNet.Antiforgery var mockHttpContext = new Mock(); mockHttpContext.Setup(o => o.Response.Cookies) .Returns(cookies); - var contextAccessor = new AntiforgeryContextAccessor(); + var contextAccessor = new DefaultAntiforgeryContextAccessor(); mockHttpContext.SetupGet(o => o.RequestServices) .Returns(GetServiceProvider(contextAccessor)); @@ -289,7 +289,7 @@ namespace Microsoft.AspNet.Antiforgery RequireSSL = requireSsl }; - var tokenStore = new AntiforgeryTokenStore( + var tokenStore = new DefaultAntiforgeryTokenStore( optionsAccessor: new TestOptionsManager(options), tokenSerializer: mockSerializer.Object); @@ -317,7 +317,7 @@ namespace Microsoft.AspNet.Antiforgery mockHttpContext.Setup(o => o.Request) .Returns(request.Object); - var contextAccessor = new AntiforgeryContextAccessor(); + var contextAccessor = new DefaultAntiforgeryContextAccessor(); mockHttpContext.SetupGet(o => o.RequestServices) .Returns(GetServiceProvider(contextAccessor)); diff --git a/test/Microsoft.AspNet.Antiforgery.Test/ClaimUidExtractorTest.cs b/test/Microsoft.AspNet.Antiforgery.Test/DefaultClaimUidExtractorTest.cs similarity index 98% rename from test/Microsoft.AspNet.Antiforgery.Test/ClaimUidExtractorTest.cs rename to test/Microsoft.AspNet.Antiforgery.Test/DefaultClaimUidExtractorTest.cs index 1a8dd5c8c7..fe5511db95 100644 --- a/test/Microsoft.AspNet.Antiforgery.Test/ClaimUidExtractorTest.cs +++ b/test/Microsoft.AspNet.Antiforgery.Test/DefaultClaimUidExtractorTest.cs @@ -11,7 +11,7 @@ using Xunit; namespace Microsoft.AspNet.Antiforgery { - public class ClaimUidExtractorTest + public class DefaultClaimUidExtractorTest { [Fact] public void ExtractClaimUid_NullIdentity() From e13e7075039b9f42fad2957913ea278a9022f367 Mon Sep 17 00:00:00 2001 From: Ryan Nowak Date: Thu, 25 Jun 2015 13:25:52 -0700 Subject: [PATCH 012/296] CR feedback and naming/resource cleanup --- .../AntiforgeryOptions.cs | 12 ++--- .../AntiforgeryTokenSet.cs | 4 +- .../DefaultAntiforgery.cs | 9 ++-- .../DefaultAntiforgeryTokenGenerator.cs | 9 +++- .../DefaultAntiforgeryTokenStore.cs | 2 +- .../IAntiforgery.cs | 12 ++--- .../IAntiforgeryAdditionalDataProvider.cs | 12 ++--- .../IAntiforgeryTokenSerializer.cs | 2 +- .../Properties/Resources.Designer.cs | 48 +++++++++---------- .../Resources.resx | 22 +++++---- .../DefaultAntiforgeryTest.cs | 26 +++++----- .../DefaultAntiforgeryTokenGeneratorTest.cs | 21 ++++---- .../DefaultAntiforgeryTokenSerializerTest.cs | 2 +- .../DefaultAntiforgeryTokenStoreTest.cs | 2 +- 14 files changed, 98 insertions(+), 85 deletions(-) diff --git a/src/Microsoft.AspNet.Antiforgery/AntiforgeryOptions.cs b/src/Microsoft.AspNet.Antiforgery/AntiforgeryOptions.cs index d8db3df2cb..6955481157 100644 --- a/src/Microsoft.AspNet.Antiforgery/AntiforgeryOptions.cs +++ b/src/Microsoft.AspNet.Antiforgery/AntiforgeryOptions.cs @@ -6,14 +6,14 @@ using Microsoft.Framework.Internal; namespace Microsoft.AspNet.Antiforgery { /// - /// Provides programmatic configuration for the anti-forgery token system. + /// Provides programmatic configuration for the antiforgery token system. /// public class AntiforgeryOptions { private const string AntiforgeryTokenFieldName = "__RequestVerificationToken"; /// - /// Specifies the name of the cookie that is used by the anti-forgery + /// Specifies the name of the cookie that is used by the antiforgery /// system. /// /// @@ -23,16 +23,16 @@ namespace Microsoft.AspNet.Antiforgery public string CookieName { get; [param: NotNull] set; } /// - /// Specifies the name of the anti-forgery token field that is used by the anti-forgery system. + /// Specifies the name of the antiforgery token field that is used by the antiforgery system. /// public string FormFieldName { get; [param: NotNull] set; } = AntiforgeryTokenFieldName; /// - /// Specifies whether SSL is required for the anti-forgery system + /// Specifies whether SSL is required for the antiforgery system /// to operate. If this setting is 'true' and a non-SSL request - /// comes into the system, all anti-forgery APIs will fail. + /// comes into the system, all antiforgery APIs will fail. /// - public bool RequireSSL { get; set; } + public bool RequireSsl { get; set; } /// /// Specifies whether to suppress the generation of X-Frame-Options header diff --git a/src/Microsoft.AspNet.Antiforgery/AntiforgeryTokenSet.cs b/src/Microsoft.AspNet.Antiforgery/AntiforgeryTokenSet.cs index c18e15dd4f..973e6883e9 100644 --- a/src/Microsoft.AspNet.Antiforgery/AntiforgeryTokenSet.cs +++ b/src/Microsoft.AspNet.Antiforgery/AntiforgeryTokenSet.cs @@ -6,12 +6,12 @@ using System; namespace Microsoft.AspNet.Antiforgery { /// - /// The anti-forgery token pair (cookie and form token) for a request. + /// The antiforgery token pair (cookie and form token) for a request. /// public class AntiforgeryTokenSet { /// - /// Creates the anti-forgery token pair (cookie and form token) for a request. + /// Creates the antiforgery token pair (cookie and form token) for a request. /// /// The token that is supplied in the request form body. /// The token that is supplied in the request cookie. diff --git a/src/Microsoft.AspNet.Antiforgery/DefaultAntiforgery.cs b/src/Microsoft.AspNet.Antiforgery/DefaultAntiforgery.cs index aba5de914b..93bb6e855b 100644 --- a/src/Microsoft.AspNet.Antiforgery/DefaultAntiforgery.cs +++ b/src/Microsoft.AspNet.Antiforgery/DefaultAntiforgery.cs @@ -12,7 +12,7 @@ using Microsoft.Framework.WebEncoders; namespace Microsoft.AspNet.Antiforgery { /// - /// Provides access to the anti-forgery system, which provides protection against + /// Provides access to the antiforgery system, which provides protection against /// Cross-site Request Forgery (XSRF, also called CSRF) attacks. /// public class DefaultAntiforgery : IAntiforgery @@ -145,9 +145,12 @@ namespace Microsoft.AspNet.Antiforgery private void CheckSSLConfig(HttpContext context) { - if (_options.RequireSSL && !context.Request.IsHttps) + if (_options.RequireSsl && !context.Request.IsHttps) { - throw new InvalidOperationException(Resources.AntiforgeryWorker_RequireSSL); + throw new InvalidOperationException(Resources.FormatAntiforgeryWorker_RequireSSL( + nameof(AntiforgeryOptions), + nameof(AntiforgeryOptions.RequireSsl), + "true")); } } diff --git a/src/Microsoft.AspNet.Antiforgery/DefaultAntiforgeryTokenGenerator.cs b/src/Microsoft.AspNet.Antiforgery/DefaultAntiforgeryTokenGenerator.cs index 6ecc8048fb..05ab540c4e 100644 --- a/src/Microsoft.AspNet.Antiforgery/DefaultAntiforgeryTokenGenerator.cs +++ b/src/Microsoft.AspNet.Antiforgery/DefaultAntiforgeryTokenGenerator.cs @@ -4,6 +4,7 @@ using System; using System.Diagnostics; using System.Security.Claims; +using System.Security.Principal; using Microsoft.AspNet.Http; using Microsoft.Framework.OptionsModel; @@ -73,7 +74,13 @@ namespace Microsoft.AspNet.Antiforgery { // Application says user is authenticated, but we have no identifier for the user. throw new InvalidOperationException( - Resources.FormatAntiforgeryTokenValidator_AuthenticatedUserWithoutUsername(identity.GetType())); + Resources.FormatAntiforgeryTokenValidator_AuthenticatedUserWithoutUsername( + identity.GetType(), + nameof(IIdentity.IsAuthenticated), + "true", + nameof(IIdentity.Name), + nameof(IAntiforgeryAdditionalDataProvider), + nameof(DefaultAntiforgeryAdditionalDataProvider))); } return formToken; diff --git a/src/Microsoft.AspNet.Antiforgery/DefaultAntiforgeryTokenStore.cs b/src/Microsoft.AspNet.Antiforgery/DefaultAntiforgeryTokenStore.cs index 7ea53b3d8b..833730e525 100644 --- a/src/Microsoft.AspNet.Antiforgery/DefaultAntiforgeryTokenStore.cs +++ b/src/Microsoft.AspNet.Antiforgery/DefaultAntiforgeryTokenStore.cs @@ -71,7 +71,7 @@ namespace Microsoft.AspNet.Antiforgery // Note: don't use "newCookie.Secure = _options.RequireSSL;" since the default // value of newCookie.Secure is poulated out of band. - if (_options.RequireSSL) + if (_options.RequireSsl) { options.Secure = true; } diff --git a/src/Microsoft.AspNet.Antiforgery/IAntiforgery.cs b/src/Microsoft.AspNet.Antiforgery/IAntiforgery.cs index 2be08cacab..564dbd2b83 100644 --- a/src/Microsoft.AspNet.Antiforgery/IAntiforgery.cs +++ b/src/Microsoft.AspNet.Antiforgery/IAntiforgery.cs @@ -16,7 +16,7 @@ namespace Microsoft.AspNet.Antiforgery /// /// Generates an input field for an antiforgery token. /// - /// The associated with the current call. + /// The associated with the current request. /// /// A string containing an <input type="hidden"> element. This element should be put inside /// a <form>. @@ -31,7 +31,7 @@ namespace Microsoft.AspNet.Antiforgery /// Generates an for this request and stores the cookie token /// in the response. /// - /// The associated with the current call. + /// The associated with the current request. /// An with tokens for the response. /// /// This method has a side effect: @@ -42,7 +42,7 @@ namespace Microsoft.AspNet.Antiforgery /// /// Generates an for this request. /// - /// The associated with the current call. + /// The associated with the current request. /// /// Unlike , this method has no side effect. The caller /// is responsible for setting the response cookie and injecting the returned @@ -53,13 +53,13 @@ namespace Microsoft.AspNet.Antiforgery /// /// Validates an antiforgery token that was supplied as part of the request. /// - /// The associated with the current call. + /// The associated with the current request. Task ValidateRequestAsync([NotNull] HttpContext context); /// /// Validates an for the current request. /// - /// The associated with the current call. + /// The associated with the current request. /// /// The (cookie and form token) for this request. /// @@ -68,7 +68,7 @@ namespace Microsoft.AspNet.Antiforgery /// /// Generates and stores an antiforgery cookie token if one is not available or not valid. /// - /// The associated with the current call. + /// The associated with the current request. void SetCookieTokenAndHeader([NotNull] HttpContext context); } } diff --git a/src/Microsoft.AspNet.Antiforgery/IAntiforgeryAdditionalDataProvider.cs b/src/Microsoft.AspNet.Antiforgery/IAntiforgeryAdditionalDataProvider.cs index fb609768bc..b652619dd9 100644 --- a/src/Microsoft.AspNet.Antiforgery/IAntiforgeryAdditionalDataProvider.cs +++ b/src/Microsoft.AspNet.Antiforgery/IAntiforgeryAdditionalDataProvider.cs @@ -6,29 +6,29 @@ using Microsoft.AspNet.Http; namespace Microsoft.AspNet.Antiforgery { /// - /// Allows providing or validating additional custom data for anti-forgery tokens. + /// Allows providing or validating additional custom data for antiforgery tokens. /// For example, the developer could use this to supply a nonce when the token is /// generated, then he could validate the nonce when the token is validated. /// /// - /// The anti-forgery system already embeds the client's username within the + /// The antiforgery system already embeds the client's username within the /// generated tokens. This interface provides and consumes supplemental - /// data. If an incoming anti-forgery token contains supplemental data but no + /// data. If an incoming antiforgery token contains supplemental data but no /// additional data provider is configured, the supplemental data will not be /// validated. /// public interface IAntiforgeryAdditionalDataProvider { /// - /// Provides additional data to be stored for the anti-forgery tokens generated + /// Provides additional data to be stored for the antiforgery tokens generated /// during this request. /// /// Information about the current request. - /// Supplemental data to embed within the anti-forgery token. + /// Supplemental data to embed within the antiforgery token. string GetAdditionalData(HttpContext context); /// - /// Validates additional data that was embedded inside an incoming anti-forgery + /// Validates additional data that was embedded inside an incoming antiforgery /// token. /// /// Information about the current request. diff --git a/src/Microsoft.AspNet.Antiforgery/IAntiforgeryTokenSerializer.cs b/src/Microsoft.AspNet.Antiforgery/IAntiforgeryTokenSerializer.cs index 4ba30c5591..1864906983 100644 --- a/src/Microsoft.AspNet.Antiforgery/IAntiforgeryTokenSerializer.cs +++ b/src/Microsoft.AspNet.Antiforgery/IAntiforgeryTokenSerializer.cs @@ -3,7 +3,7 @@ namespace Microsoft.AspNet.Antiforgery { - // Abstracts out the serialization process for an anti-forgery token + // Abstracts out the serialization process for an antiforgery token public interface IAntiforgeryTokenSerializer { AntiforgeryToken Deserialize(string serializedToken); diff --git a/src/Microsoft.AspNet.Antiforgery/Properties/Resources.Designer.cs b/src/Microsoft.AspNet.Antiforgery/Properties/Resources.Designer.cs index af584b07c3..f012e4b91e 100644 --- a/src/Microsoft.AspNet.Antiforgery/Properties/Resources.Designer.cs +++ b/src/Microsoft.AspNet.Antiforgery/Properties/Resources.Designer.cs @@ -11,7 +11,7 @@ namespace Microsoft.AspNet.Antiforgery = new ResourceManager("Microsoft.AspNet.Antiforgery.Resources", typeof(Resources).GetTypeInfo().Assembly); /// - /// The provided identity of type '{0}' is marked IsAuthenticated = true but does not have a value for Name. By default, the anti-forgery system requires that all authenticated identities have a unique Name. If it is not possible to provide a unique Name for this identity, consider extending IAdditionalDataProvider by overriding the DefaultAdditionalDataProvider or a custom type that can provide some form of unique identifier for the current user. + /// The provided identity of type '{0}' is marked {1} = {2} but does not have a value for {3}. By default, the antiforgery system requires that all authenticated identities have a unique {3}. If it is not possible to provide a unique {3} for this identity, consider extending {4} by overriding the {5} or a custom type that can provide some form of unique identifier for the current user. /// internal static string AntiforgeryTokenValidator_AuthenticatedUserWithoutUsername { @@ -19,15 +19,15 @@ namespace Microsoft.AspNet.Antiforgery } /// - /// The provided identity of type '{0}' is marked IsAuthenticated = true but does not have a value for Name. By default, the anti-forgery system requires that all authenticated identities have a unique Name. If it is not possible to provide a unique Name for this identity, consider extending IAdditionalDataProvider by overriding the DefaultAdditionalDataProvider or a custom type that can provide some form of unique identifier for the current user. + /// The provided identity of type '{0}' is marked {1} = {2} but does not have a value for {3}. By default, the antiforgery system requires that all authenticated identities have a unique {3}. If it is not possible to provide a unique {3} for this identity, consider extending {4} by overriding the {5} or a custom type that can provide some form of unique identifier for the current user. /// - internal static string FormatAntiforgeryTokenValidator_AuthenticatedUserWithoutUsername(object p0) + internal static string FormatAntiforgeryTokenValidator_AuthenticatedUserWithoutUsername(object p0, object p1, object p2, object p3, object p4, object p5) { - return string.Format(CultureInfo.CurrentCulture, GetString("AntiforgeryTokenValidator_AuthenticatedUserWithoutUsername"), p0); + return string.Format(CultureInfo.CurrentCulture, GetString("AntiforgeryTokenValidator_AuthenticatedUserWithoutUsername"), p0, p1, p2, p3, p4, p5); } /// - /// The provided anti-forgery token failed a custom data check. + /// The provided antiforgery token failed a custom data check. /// internal static string AntiforgeryToken_AdditionalDataCheckFailed { @@ -35,7 +35,7 @@ namespace Microsoft.AspNet.Antiforgery } /// - /// The provided anti-forgery token failed a custom data check. + /// The provided antiforgery token failed a custom data check. /// internal static string FormatAntiforgeryToken_AdditionalDataCheckFailed() { @@ -43,7 +43,7 @@ namespace Microsoft.AspNet.Antiforgery } /// - /// The provided anti-forgery token was meant for a different claims-based user than the current user. + /// The provided antiforgery token was meant for a different claims-based user than the current user. /// internal static string AntiforgeryToken_ClaimUidMismatch { @@ -51,7 +51,7 @@ namespace Microsoft.AspNet.Antiforgery } /// - /// The provided anti-forgery token was meant for a different claims-based user than the current user. + /// The provided antiforgery token was meant for a different claims-based user than the current user. /// internal static string FormatAntiforgeryToken_ClaimUidMismatch() { @@ -59,7 +59,7 @@ namespace Microsoft.AspNet.Antiforgery } /// - /// The required anti-forgery cookie "{0}" is not present. + /// The required antiforgery cookie "{0}" is not present. /// internal static string AntiforgeryToken_CookieMissing { @@ -67,7 +67,7 @@ namespace Microsoft.AspNet.Antiforgery } /// - /// The required anti-forgery cookie "{0}" is not present. + /// The required antiforgery cookie "{0}" is not present. /// internal static string FormatAntiforgeryToken_CookieMissing(object p0) { @@ -75,7 +75,7 @@ namespace Microsoft.AspNet.Antiforgery } /// - /// The anti-forgery token could not be decrypted. + /// The antiforgery token could not be decrypted. /// internal static string AntiforgeryToken_DeserializationFailed { @@ -83,7 +83,7 @@ namespace Microsoft.AspNet.Antiforgery } /// - /// The anti-forgery token could not be decrypted. + /// The antiforgery token could not be decrypted. /// internal static string FormatAntiforgeryToken_DeserializationFailed() { @@ -91,7 +91,7 @@ namespace Microsoft.AspNet.Antiforgery } /// - /// The required anti-forgery form field "{0}" is not present. + /// The required antiforgery form field "{0}" is not present. /// internal static string AntiforgeryToken_FormFieldMissing { @@ -99,7 +99,7 @@ namespace Microsoft.AspNet.Antiforgery } /// - /// The required anti-forgery form field "{0}" is not present. + /// The required antiforgery form field "{0}" is not present. /// internal static string FormatAntiforgeryToken_FormFieldMissing(object p0) { @@ -107,7 +107,7 @@ namespace Microsoft.AspNet.Antiforgery } /// - /// The anti-forgery cookie token and form field token do not match. + /// The antiforgery cookie token and form field token do not match. /// internal static string AntiforgeryToken_SecurityTokenMismatch { @@ -115,7 +115,7 @@ namespace Microsoft.AspNet.Antiforgery } /// - /// The anti-forgery cookie token and form field token do not match. + /// The antiforgery cookie token and form field token do not match. /// internal static string FormatAntiforgeryToken_SecurityTokenMismatch() { @@ -123,7 +123,7 @@ namespace Microsoft.AspNet.Antiforgery } /// - /// Validation of the provided anti-forgery token failed. The cookie "{0}" and the form field "{1}" were swapped. + /// Validation of the provided antiforgery token failed. The cookie "{0}" and the form field "{1}" were swapped. /// internal static string AntiforgeryToken_TokensSwapped { @@ -131,7 +131,7 @@ namespace Microsoft.AspNet.Antiforgery } /// - /// Validation of the provided anti-forgery token failed. The cookie "{0}" and the form field "{1}" were swapped. + /// Validation of the provided antiforgery token failed. The cookie "{0}" and the form field "{1}" were swapped. /// internal static string FormatAntiforgeryToken_TokensSwapped(object p0, object p1) { @@ -139,7 +139,7 @@ namespace Microsoft.AspNet.Antiforgery } /// - /// The provided anti-forgery token was meant for user "{0}", but the current user is "{1}". + /// The provided antiforgery token was meant for user "{0}", but the current user is "{1}". /// internal static string AntiforgeryToken_UsernameMismatch { @@ -147,7 +147,7 @@ namespace Microsoft.AspNet.Antiforgery } /// - /// The provided anti-forgery token was meant for user "{0}", but the current user is "{1}". + /// The provided antiforgery token was meant for user "{0}", but the current user is "{1}". /// internal static string FormatAntiforgeryToken_UsernameMismatch(object p0, object p1) { @@ -155,7 +155,7 @@ namespace Microsoft.AspNet.Antiforgery } /// - /// The anti-forgery system has the configuration value AntiforgeryOptions.RequireSsl = true, but the current request is not an SSL request. + /// The antiforgery system has the configuration value {0}.{1} = {2}, but the current request is not an SSL request. /// internal static string AntiforgeryWorker_RequireSSL { @@ -163,11 +163,11 @@ namespace Microsoft.AspNet.Antiforgery } /// - /// The anti-forgery system has the configuration value AntiforgeryOptions.RequireSsl = true, but the current request is not an SSL request. + /// The antiforgery system has the configuration value {0}.{1} = {2}, but the current request is not an SSL request. /// - internal static string FormatAntiforgeryWorker_RequireSSL() + internal static string FormatAntiforgeryWorker_RequireSSL(object p0, object p1, object p2) { - return GetString("AntiforgeryWorker_RequireSSL"); + return string.Format(CultureInfo.CurrentCulture, GetString("AntiforgeryWorker_RequireSSL"), p0, p1, p2); } /// diff --git a/src/Microsoft.AspNet.Antiforgery/Resources.resx b/src/Microsoft.AspNet.Antiforgery/Resources.resx index e666385354..2cad9e6cf6 100644 --- a/src/Microsoft.AspNet.Antiforgery/Resources.resx +++ b/src/Microsoft.AspNet.Antiforgery/Resources.resx @@ -118,34 +118,36 @@ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - The provided identity of type '{0}' is marked IsAuthenticated = true but does not have a value for Name. By default, the anti-forgery system requires that all authenticated identities have a unique Name. If it is not possible to provide a unique Name for this identity, consider extending IAdditionalDataProvider by overriding the DefaultAdditionalDataProvider or a custom type that can provide some form of unique identifier for the current user. + The provided identity of type '{0}' is marked {1} = {2} but does not have a value for {3}. By default, the antiforgery system requires that all authenticated identities have a unique {3}. If it is not possible to provide a unique {3} for this identity, consider extending {4} by overriding the {5} or a custom type that can provide some form of unique identifier for the current user. + 0 = typeof(identity), 1 = nameof(IsAuthenticated), 2 = bool.TrueString, 3 = nameof(Name), 4 = nameof(IAdditionalDataProvider), 5 = nameof(DefaultAdditionalDataProvider) - The provided anti-forgery token failed a custom data check. + The provided antiforgery token failed a custom data check. - The provided anti-forgery token was meant for a different claims-based user than the current user. + The provided antiforgery token was meant for a different claims-based user than the current user. - The required anti-forgery cookie "{0}" is not present. + The required antiforgery cookie "{0}" is not present. - The anti-forgery token could not be decrypted. + The antiforgery token could not be decrypted. - The required anti-forgery form field "{0}" is not present. + The required antiforgery form field "{0}" is not present. - The anti-forgery cookie token and form field token do not match. + The antiforgery cookie token and form field token do not match. - Validation of the provided anti-forgery token failed. The cookie "{0}" and the form field "{1}" were swapped. + Validation of the provided antiforgery token failed. The cookie "{0}" and the form field "{1}" were swapped. - The provided anti-forgery token was meant for user "{0}", but the current user is "{1}". + The provided antiforgery token was meant for user "{0}", but the current user is "{1}". - The anti-forgery system has the configuration value AntiforgeryOptions.RequireSsl = true, but the current request is not an SSL request. + The antiforgery system has the configuration value {0}.{1} = {2}, but the current request is not an SSL request. + 0 = nameof(AntiforgeryOptions), 1 = nameof(RequireSsl), 2 = bool.TrueString Value cannot be null or empty. diff --git a/test/Microsoft.AspNet.Antiforgery.Test/DefaultAntiforgeryTest.cs b/test/Microsoft.AspNet.Antiforgery.Test/DefaultAntiforgeryTest.cs index ee297fe0d8..c775e5cd36 100644 --- a/test/Microsoft.AspNet.Antiforgery.Test/DefaultAntiforgeryTest.cs +++ b/test/Microsoft.AspNet.Antiforgery.Test/DefaultAntiforgeryTest.cs @@ -15,7 +15,7 @@ using Xunit; namespace Microsoft.AspNet.Antiforgery { - public class AntiforgeryTest + public class DefaultAntiforgeryTest { [Fact] public async Task ChecksSSL_ValidateRequestAsync_Throws() @@ -25,7 +25,7 @@ namespace Microsoft.AspNet.Antiforgery var options = new AntiforgeryOptions() { - RequireSSL = true + RequireSsl = true }; var antiforgery = GetAntiforgery(options); @@ -34,7 +34,7 @@ namespace Microsoft.AspNet.Antiforgery var exception = await Assert.ThrowsAsync( async () => await antiforgery.ValidateRequestAsync(httpContext)); Assert.Equal( - @"The anti-forgery system has the configuration value AntiforgeryOptions.RequireSsl = true, " + + @"The antiforgery system has the configuration value AntiforgeryOptions.RequireSsl = true, " + "but the current request is not an SSL request.", exception.Message); } @@ -47,7 +47,7 @@ namespace Microsoft.AspNet.Antiforgery var options = new AntiforgeryOptions() { - RequireSSL = true + RequireSsl = true }; var antiforgery = GetAntiforgery(options); @@ -56,7 +56,7 @@ namespace Microsoft.AspNet.Antiforgery var exception = Assert.Throws( () => antiforgery.ValidateTokens(httpContext, new AntiforgeryTokenSet("hello", "world"))); Assert.Equal( - @"The anti-forgery system has the configuration value AntiforgeryOptions.RequireSsl = true, " + + @"The antiforgery system has the configuration value AntiforgeryOptions.RequireSsl = true, " + "but the current request is not an SSL request.", exception.Message); } @@ -69,7 +69,7 @@ namespace Microsoft.AspNet.Antiforgery var options = new AntiforgeryOptions() { - RequireSSL = true + RequireSsl = true }; var antiforgery = GetAntiforgery(options); @@ -78,7 +78,7 @@ namespace Microsoft.AspNet.Antiforgery var exception = Assert.Throws( () => antiforgery.GetHtml(httpContext)); Assert.Equal( - @"The anti-forgery system has the configuration value AntiforgeryOptions.RequireSsl = true, " + + @"The antiforgery system has the configuration value AntiforgeryOptions.RequireSsl = true, " + "but the current request is not an SSL request.", exception.Message); } @@ -91,7 +91,7 @@ namespace Microsoft.AspNet.Antiforgery var options = new AntiforgeryOptions() { - RequireSSL = true + RequireSsl = true }; var antiforgery = GetAntiforgery(options); @@ -100,7 +100,7 @@ namespace Microsoft.AspNet.Antiforgery var exception = Assert.Throws( () => antiforgery.GetAndStoreTokens(httpContext)); Assert.Equal( - @"The anti-forgery system has the configuration value AntiforgeryOptions.RequireSsl = true, " + + @"The antiforgery system has the configuration value AntiforgeryOptions.RequireSsl = true, " + "but the current request is not an SSL request.", exception.Message); } @@ -113,7 +113,7 @@ namespace Microsoft.AspNet.Antiforgery var options = new AntiforgeryOptions() { - RequireSSL = true + RequireSsl = true }; var antiforgery = GetAntiforgery(options); @@ -122,7 +122,7 @@ namespace Microsoft.AspNet.Antiforgery var exception = Assert.Throws( () => antiforgery.GetTokens(httpContext)); Assert.Equal( - @"The anti-forgery system has the configuration value AntiforgeryOptions.RequireSsl = true, " + + @"The antiforgery system has the configuration value AntiforgeryOptions.RequireSsl = true, " + "but the current request is not an SSL request.", exception.Message); } @@ -135,7 +135,7 @@ namespace Microsoft.AspNet.Antiforgery var options = new AntiforgeryOptions() { - RequireSSL = true + RequireSsl = true }; var antiforgery = GetAntiforgery(options); @@ -144,7 +144,7 @@ namespace Microsoft.AspNet.Antiforgery var exception = Assert.Throws( () => antiforgery.SetCookieTokenAndHeader(httpContext)); Assert.Equal( - @"The anti-forgery system has the configuration value AntiforgeryOptions.RequireSsl = true, " + + @"The antiforgery system has the configuration value AntiforgeryOptions.RequireSsl = true, " + "but the current request is not an SSL request.", exception.Message); } diff --git a/test/Microsoft.AspNet.Antiforgery.Test/DefaultAntiforgeryTokenGeneratorTest.cs b/test/Microsoft.AspNet.Antiforgery.Test/DefaultAntiforgeryTokenGeneratorTest.cs index 905a1444a9..8412e95208 100644 --- a/test/Microsoft.AspNet.Antiforgery.Test/DefaultAntiforgeryTokenGeneratorTest.cs +++ b/test/Microsoft.AspNet.Antiforgery.Test/DefaultAntiforgeryTokenGeneratorTest.cs @@ -85,9 +85,10 @@ namespace Microsoft.AspNet.Antiforgery "The provided identity of type " + $"'{typeof(MyAuthenticatedIdentityWithoutUsername).FullName}' " + "is marked IsAuthenticated = true but does not have a value for Name. " + - "By default, the anti-forgery system requires that all authenticated identities have a unique Name. " + + "By default, the antiforgery system requires that all authenticated identities have a unique Name. " + "If it is not possible to provide a unique Name for this identity, " + - "consider extending IAdditionalDataProvider by overriding the DefaultAdditionalDataProvider " + + "consider extending IAntiforgeryAdditionalDataProvider by overriding the " + + "DefaultAntiforgeryAdditionalDataProvider " + "or a custom type that can provide some form of unique identifier for the current user.", exception.Message); } @@ -281,7 +282,7 @@ namespace Microsoft.AspNet.Antiforgery var ex = Assert.Throws( () => tokenProvider.ValidateTokens(httpContext, null, fieldtoken)); - Assert.Equal(@"The required anti-forgery cookie ""my-cookie-name"" is not present.", ex.Message); + Assert.Equal(@"The required antiforgery cookie ""my-cookie-name"" is not present.", ex.Message); } [Fact] @@ -307,7 +308,7 @@ namespace Microsoft.AspNet.Antiforgery var ex = Assert.Throws( () => tokenProvider.ValidateTokens(httpContext, sessionToken, null)); - Assert.Equal(@"The required anti-forgery form field ""my-form-field-name"" is not present.", ex.Message); + Assert.Equal(@"The required antiforgery form field ""my-form-field-name"" is not present.", ex.Message); } [Fact] @@ -336,7 +337,7 @@ namespace Microsoft.AspNet.Antiforgery Assert.Throws( () => tokenProvider.ValidateTokens(httpContext, fieldtoken, fieldtoken)); Assert.Equal( - "Validation of the provided anti-forgery token failed. " + + "Validation of the provided antiforgery token failed. " + @"The cookie ""my-cookie-name"" and the form field ""my-form-field-name"" were swapped.", ex1.Message); @@ -344,7 +345,7 @@ namespace Microsoft.AspNet.Antiforgery Assert.Throws( () => tokenProvider.ValidateTokens(httpContext, sessionToken, sessionToken)); Assert.Equal( - "Validation of the provided anti-forgery token failed. " + + "Validation of the provided antiforgery token failed. " + @"The cookie ""my-cookie-name"" and the form field ""my-form-field-name"" were swapped.", ex2.Message); } @@ -368,7 +369,7 @@ namespace Microsoft.AspNet.Antiforgery var exception = Assert.Throws( () => tokenProvider.ValidateTokens(httpContext, sessionToken, fieldtoken)); Assert.Equal( - @"The anti-forgery cookie token and form field token do not match.", + @"The antiforgery cookie token and form field token do not match.", exception.Message); } @@ -406,7 +407,7 @@ namespace Microsoft.AspNet.Antiforgery var exception = Assert.Throws( () => tokenProvider.ValidateTokens(httpContext, sessionToken, fieldtoken)); Assert.Equal( - @"The provided anti-forgery token was meant for user """ + embeddedUsername + + @"The provided antiforgery token was meant for user """ + embeddedUsername + @""", but the current user is """ + identityUsername + @""".", exception.Message); } @@ -441,7 +442,7 @@ namespace Microsoft.AspNet.Antiforgery var exception = Assert.Throws( () => tokenProvider.ValidateTokens(httpContext, sessionToken, fieldtoken)); Assert.Equal( - @"The provided anti-forgery token was meant for a different claims-based user than the current user.", + @"The provided antiforgery token was meant for a different claims-based user than the current user.", exception.Message); } @@ -474,7 +475,7 @@ namespace Microsoft.AspNet.Antiforgery // Act & assert var exception = Assert.Throws( () => tokenProvider.ValidateTokens(httpContext, sessionToken, fieldtoken)); - Assert.Equal(@"The provided anti-forgery token failed a custom data check.", exception.Message); + Assert.Equal(@"The provided antiforgery token failed a custom data check.", exception.Message); } [Fact] diff --git a/test/Microsoft.AspNet.Antiforgery.Test/DefaultAntiforgeryTokenSerializerTest.cs b/test/Microsoft.AspNet.Antiforgery.Test/DefaultAntiforgeryTokenSerializerTest.cs index 45d4646fc2..54fadd4399 100644 --- a/test/Microsoft.AspNet.Antiforgery.Test/DefaultAntiforgeryTokenSerializerTest.cs +++ b/test/Microsoft.AspNet.Antiforgery.Test/DefaultAntiforgeryTokenSerializerTest.cs @@ -50,7 +50,7 @@ namespace Microsoft.AspNet.Antiforgery // Act & assert var ex = Assert.Throws(() => testSerializer.Deserialize(serializedToken)); - Assert.Equal(@"The anti-forgery token could not be decrypted.", ex.Message); + Assert.Equal(@"The antiforgery token could not be decrypted.", ex.Message); } [Fact] diff --git a/test/Microsoft.AspNet.Antiforgery.Test/DefaultAntiforgeryTokenStoreTest.cs b/test/Microsoft.AspNet.Antiforgery.Test/DefaultAntiforgeryTokenStoreTest.cs index b1c251e5f2..d2bfc7b458 100644 --- a/test/Microsoft.AspNet.Antiforgery.Test/DefaultAntiforgeryTokenStoreTest.cs +++ b/test/Microsoft.AspNet.Antiforgery.Test/DefaultAntiforgeryTokenStoreTest.cs @@ -286,7 +286,7 @@ namespace Microsoft.AspNet.Antiforgery var options = new AntiforgeryOptions() { CookieName = _cookieName, - RequireSSL = requireSsl + RequireSsl = requireSsl }; var tokenStore = new DefaultAntiforgeryTokenStore( From 77d1b4737786320bcc754b9ae1a42bfad4787f69 Mon Sep 17 00:00:00 2001 From: Victor Hurdugaci Date: Wed, 1 Jul 2015 20:35:25 -0700 Subject: [PATCH 013/296] Add repository information to project files --- src/Microsoft.AspNet.Antiforgery/project.json | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/Microsoft.AspNet.Antiforgery/project.json b/src/Microsoft.AspNet.Antiforgery/project.json index d46ba0c895..54e6db9d6e 100644 --- a/src/Microsoft.AspNet.Antiforgery/project.json +++ b/src/Microsoft.AspNet.Antiforgery/project.json @@ -1,6 +1,10 @@ { "description": "An antiforgery system for ASP.NET designed to generate and validate tokens to prevent Cross-Site Request Forgery attacks.", "version": "1.0.0-*", + "repository": { + "type": "git", + "url": "git://github.com/aspnet/antiforgery" + }, "dependencies": { "Microsoft.AspNet.DataProtection": "1.0.0-*", "Microsoft.AspNet.Http.Abstractions": "1.0.0-*", From 468e64d3adb983eb59bb4d6121cd490382119de4 Mon Sep 17 00:00:00 2001 From: Pranav K Date: Thu, 16 Jul 2015 08:57:52 -0700 Subject: [PATCH 014/296] Updating to release NuGet.config --- NuGet.Config | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/NuGet.Config b/NuGet.Config index 46c3b3e36c..0e74a4912d 100644 --- a/NuGet.Config +++ b/NuGet.Config @@ -1,7 +1,8 @@  - + + From fbe9dc58e87609af810f7f43188a144d5c965f86 Mon Sep 17 00:00:00 2001 From: Troy Dai Date: Tue, 4 Aug 2015 10:15:20 -0700 Subject: [PATCH 015/296] Update CoreCLR versions --- src/Microsoft.AspNet.Antiforgery/project.json | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/Microsoft.AspNet.Antiforgery/project.json b/src/Microsoft.AspNet.Antiforgery/project.json index 54e6db9d6e..017b3d6d99 100644 --- a/src/Microsoft.AspNet.Antiforgery/project.json +++ b/src/Microsoft.AspNet.Antiforgery/project.json @@ -1,4 +1,4 @@ -{ +{ "description": "An antiforgery system for ASP.NET designed to generate and validate tokens to prevent Cross-Site Request Forgery attacks.", "version": "1.0.0-*", "repository": { @@ -19,12 +19,12 @@ "dnx451": { }, "dnxcore50" : { "dependencies": { - "System.Collections": "4.0.10-beta-*", - "System.Linq": "4.0.0-beta-*", + "System.Collections": "4.0.11-beta-*", + "System.Linq": "4.0.1-beta-*", "System.Security.Cryptography.RandomNumberGenerator": "4.0.0-beta-*", "System.Security.Cryptography.Hashing.Algorithms": "4.0.0-beta-*", - "System.Threading": "4.0.10-beta-*", - "Microsoft.CSharp": "4.0.0-beta-*" + "System.Threading": "4.0.11-beta-*", + "Microsoft.CSharp": "4.0.1-beta-*" } } } From 9bcecf39948ff9f7e5755b7972ec348af0eb900e Mon Sep 17 00:00:00 2001 From: Ryan Nowak Date: Thu, 30 Jul 2015 15:04:50 -0700 Subject: [PATCH 016/296] Fix #5 - better error message for missing tokens This fix changes the model for error messaging in antiforgery. Now only the token store will report a detailed error message including the names of form field and cookie. Other components will give more generic errors and assume that this was handled by the token store. This way you still see an error if the user creates a token store that doesn't throw, but it's a generic error that doesn't give incorrect information. --- .../DefaultAntiforgery.cs | 46 +++----- .../DefaultAntiforgeryTokenGenerator.cs | 19 ++-- .../DefaultAntiforgeryTokenStore.cs | 22 ++-- .../IAntiforgeryTokenGenerator.cs | 10 +- .../IAntiforgeryTokenStore.cs | 15 ++- .../Properties/Resources.Designer.cs | 104 ++++++++++++------ .../Resources.resx | 20 ++-- .../DefaultAntiforgeryTest.cs | 69 ++++++++---- .../DefaultAntiforgeryTokenGeneratorTest.cs | 57 ++-------- .../DefaultAntiforgeryTokenStoreTest.cs | 88 +++++++-------- 10 files changed, 239 insertions(+), 211 deletions(-) diff --git a/src/Microsoft.AspNet.Antiforgery/DefaultAntiforgery.cs b/src/Microsoft.AspNet.Antiforgery/DefaultAntiforgery.cs index 93bb6e855b..b4497ebfed 100644 --- a/src/Microsoft.AspNet.Antiforgery/DefaultAntiforgery.cs +++ b/src/Microsoft.AspNet.Antiforgery/DefaultAntiforgery.cs @@ -76,12 +76,8 @@ namespace Microsoft.AspNet.Antiforgery { CheckSSLConfig(context); - // Extract cookie & form tokens - var cookieToken = _tokenStore.GetCookieToken(context); - var formToken = await _tokenStore.GetFormTokenAsync(context); - - // Validate - _tokenGenerator.ValidateTokens(context, cookieToken, formToken); + var tokens = await _tokenStore.GetRequestTokensAsync(context); + ValidateTokens(context, tokens); } /// @@ -89,9 +85,23 @@ namespace Microsoft.AspNet.Antiforgery { CheckSSLConfig(context); + if (string.IsNullOrEmpty(antiforgeryTokenSet.CookieToken)) + { + throw new ArgumentException( + Resources.Antiforgery_CookieToken_MustBeProvided_Generic, + nameof(antiforgeryTokenSet)); + } + + if (string.IsNullOrEmpty(antiforgeryTokenSet.FormToken)) + { + throw new ArgumentException( + Resources.Antiforgery_FormToken_MustBeProvided_Generic, + nameof(antiforgeryTokenSet)); + } + // Extract cookie & form tokens - var deserializedCookieToken = DeserializeToken(antiforgeryTokenSet.CookieToken); - var deserializedFormToken = DeserializeToken(antiforgeryTokenSet.FormToken); + var deserializedCookieToken = _tokenSerializer.Deserialize(antiforgeryTokenSet.CookieToken); + var deserializedFormToken = _tokenSerializer.Deserialize(antiforgeryTokenSet.FormToken); // Validate _tokenGenerator.ValidateTokens( @@ -154,26 +164,6 @@ namespace Microsoft.AspNet.Antiforgery } } - private AntiforgeryToken DeserializeToken(string serializedToken) - { - return (!string.IsNullOrEmpty(serializedToken)) - ? _tokenSerializer.Deserialize(serializedToken) - : null; - } - - private AntiforgeryToken DeserializeTokenDoesNotThrow(string serializedToken) - { - try - { - return DeserializeToken(serializedToken); - } - catch - { - // ignore failures since we'll just generate a new token - return null; - } - } - private AntiforgeryToken GetCookieTokenDoesNotThrow(HttpContext context) { try diff --git a/src/Microsoft.AspNet.Antiforgery/DefaultAntiforgeryTokenGenerator.cs b/src/Microsoft.AspNet.Antiforgery/DefaultAntiforgeryTokenGenerator.cs index 05ab540c4e..700ecaaa6e 100644 --- a/src/Microsoft.AspNet.Antiforgery/DefaultAntiforgeryTokenGenerator.cs +++ b/src/Microsoft.AspNet.Antiforgery/DefaultAntiforgeryTokenGenerator.cs @@ -6,22 +6,18 @@ using System.Diagnostics; using System.Security.Claims; using System.Security.Principal; using Microsoft.AspNet.Http; -using Microsoft.Framework.OptionsModel; namespace Microsoft.AspNet.Antiforgery { public class DefaultAntiforgeryTokenGenerator : IAntiforgeryTokenGenerator { private readonly IClaimUidExtractor _claimUidExtractor; - private readonly AntiforgeryOptions _options; private readonly IAntiforgeryAdditionalDataProvider _additionalDataProvider; public DefaultAntiforgeryTokenGenerator( - IOptions optionsAccessor, IClaimUidExtractor claimUidExtractor, IAntiforgeryAdditionalDataProvider additionalDataProvider) { - _options = optionsAccessor.Options; _claimUidExtractor = claimUidExtractor; _additionalDataProvider = additionalDataProvider; } @@ -96,23 +92,24 @@ namespace Microsoft.AspNet.Antiforgery AntiforgeryToken sessionToken, AntiforgeryToken fieldToken) { - // Were the tokens even present at all? if (sessionToken == null) { - throw new InvalidOperationException( - Resources.FormatAntiforgeryToken_CookieMissing(_options.CookieName)); + throw new ArgumentNullException( + nameof(sessionToken), + Resources.Antiforgery_CookieToken_MustBeProvided_Generic); } + if (fieldToken == null) { - throw new InvalidOperationException( - Resources.FormatAntiforgeryToken_FormFieldMissing(_options.FormFieldName)); + throw new ArgumentNullException( + nameof(fieldToken), + Resources.Antiforgery_FormToken_MustBeProvided_Generic); } // Do the tokens have the correct format? if (!sessionToken.IsSessionToken || fieldToken.IsSessionToken) { - throw new InvalidOperationException( - Resources.FormatAntiforgeryToken_TokensSwapped(_options.CookieName, _options.FormFieldName)); + throw new InvalidOperationException(Resources.AntiforgeryToken_TokensSwapped); } // Are the security tokens embedded in each incoming token identical? diff --git a/src/Microsoft.AspNet.Antiforgery/DefaultAntiforgeryTokenStore.cs b/src/Microsoft.AspNet.Antiforgery/DefaultAntiforgeryTokenStore.cs index 833730e525..7a566d4295 100644 --- a/src/Microsoft.AspNet.Antiforgery/DefaultAntiforgeryTokenStore.cs +++ b/src/Microsoft.AspNet.Antiforgery/DefaultAntiforgeryTokenStore.cs @@ -1,6 +1,7 @@ // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. +using System; using System.Diagnostics; using System.Threading.Tasks; using Microsoft.AspNet.Http; @@ -43,17 +44,24 @@ namespace Microsoft.AspNet.Antiforgery return _tokenSerializer.Deserialize(requestCookie); } - public async Task GetFormTokenAsync(HttpContext httpContext) + public async Task GetRequestTokensAsync([NotNull] HttpContext httpContext) { - var form = await httpContext.Request.ReadFormAsync(); - var value = form[_options.FormFieldName]; - if (string.IsNullOrEmpty(value)) + var requestCookie = httpContext.Request.Cookies[_options.CookieName]; + if (string.IsNullOrEmpty(requestCookie)) { - // did not exist - return null; + throw new InvalidOperationException( + Resources.FormatAntiforgery_CookieToken_MustBeProvided(_options.CookieName)); } - return _tokenSerializer.Deserialize(value); + var form = await httpContext.Request.ReadFormAsync(); + var formField = form[_options.FormFieldName]; + if (string.IsNullOrEmpty(formField)) + { + throw new InvalidOperationException( + Resources.FormatAntiforgery_FormToken_MustBeProvided(_options.FormFieldName)); + } + + return new AntiforgeryTokenSet(formField, requestCookie); } public void SaveCookieToken(HttpContext httpContext, AntiforgeryToken token) diff --git a/src/Microsoft.AspNet.Antiforgery/IAntiforgeryTokenGenerator.cs b/src/Microsoft.AspNet.Antiforgery/IAntiforgeryTokenGenerator.cs index 8ca4510bf7..bdf01af11e 100644 --- a/src/Microsoft.AspNet.Antiforgery/IAntiforgeryTokenGenerator.cs +++ b/src/Microsoft.AspNet.Antiforgery/IAntiforgeryTokenGenerator.cs @@ -1,8 +1,8 @@ // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. -using System.Security.Claims; using Microsoft.AspNet.Http; +using Microsoft.Framework.Internal; namespace Microsoft.AspNet.Antiforgery { @@ -17,7 +17,7 @@ namespace Microsoft.AspNet.Antiforgery // Given a cookie token, generates a corresponding form token. // The incoming cookie token must be valid. AntiforgeryToken GenerateFormToken( - HttpContext httpContext, + [NotNull] HttpContext httpContext, AntiforgeryToken cookieToken); // Determines whether an existing cookie token is valid (well-formed). @@ -26,8 +26,8 @@ namespace Microsoft.AspNet.Antiforgery // Validates a (cookie, form) token pair. void ValidateTokens( - HttpContext httpContext, - AntiforgeryToken cookieToken, - AntiforgeryToken formToken); + [NotNull] HttpContext httpContext, + [NotNull] AntiforgeryToken cookieToken, + [NotNull] AntiforgeryToken formToken); } } \ No newline at end of file diff --git a/src/Microsoft.AspNet.Antiforgery/IAntiforgeryTokenStore.cs b/src/Microsoft.AspNet.Antiforgery/IAntiforgeryTokenStore.cs index 0f2ab27024..afa43014d6 100644 --- a/src/Microsoft.AspNet.Antiforgery/IAntiforgeryTokenStore.cs +++ b/src/Microsoft.AspNet.Antiforgery/IAntiforgeryTokenStore.cs @@ -3,14 +3,23 @@ using System.Threading.Tasks; using Microsoft.AspNet.Http; +using Microsoft.Framework.Internal; namespace Microsoft.AspNet.Antiforgery { // Provides an abstraction around how tokens are persisted and retrieved for a request public interface IAntiforgeryTokenStore { - AntiforgeryToken GetCookieToken(HttpContext httpContext); - Task GetFormTokenAsync(HttpContext httpContext); - void SaveCookieToken(HttpContext httpContext, AntiforgeryToken token); + AntiforgeryToken GetCookieToken([NotNull] HttpContext httpContext); + + /// + /// Gets the cookie and form tokens from the request. Will throw an exception if either token is + /// not present. + /// + /// The for the current request. + /// The . + Task GetRequestTokensAsync([NotNull] HttpContext httpContext); + + void SaveCookieToken([NotNull] HttpContext httpContext, [NotNull] AntiforgeryToken token); } } \ No newline at end of file diff --git a/src/Microsoft.AspNet.Antiforgery/Properties/Resources.Designer.cs b/src/Microsoft.AspNet.Antiforgery/Properties/Resources.Designer.cs index f012e4b91e..e4542a56f5 100644 --- a/src/Microsoft.AspNet.Antiforgery/Properties/Resources.Designer.cs +++ b/src/Microsoft.AspNet.Antiforgery/Properties/Resources.Designer.cs @@ -58,22 +58,6 @@ namespace Microsoft.AspNet.Antiforgery return GetString("AntiforgeryToken_ClaimUidMismatch"); } - /// - /// The required antiforgery cookie "{0}" is not present. - /// - internal static string AntiforgeryToken_CookieMissing - { - get { return GetString("AntiforgeryToken_CookieMissing"); } - } - - /// - /// The required antiforgery cookie "{0}" is not present. - /// - internal static string FormatAntiforgeryToken_CookieMissing(object p0) - { - return string.Format(CultureInfo.CurrentCulture, GetString("AntiforgeryToken_CookieMissing"), p0); - } - /// /// The antiforgery token could not be decrypted. /// @@ -90,22 +74,6 @@ namespace Microsoft.AspNet.Antiforgery return GetString("AntiforgeryToken_DeserializationFailed"); } - /// - /// The required antiforgery form field "{0}" is not present. - /// - internal static string AntiforgeryToken_FormFieldMissing - { - get { return GetString("AntiforgeryToken_FormFieldMissing"); } - } - - /// - /// The required antiforgery form field "{0}" is not present. - /// - internal static string FormatAntiforgeryToken_FormFieldMissing(object p0) - { - return string.Format(CultureInfo.CurrentCulture, GetString("AntiforgeryToken_FormFieldMissing"), p0); - } - /// /// The antiforgery cookie token and form field token do not match. /// @@ -123,7 +91,7 @@ namespace Microsoft.AspNet.Antiforgery } /// - /// Validation of the provided antiforgery token failed. The cookie "{0}" and the form field "{1}" were swapped. + /// Validation of the provided antiforgery token failed. The cookie token and the form token were swapped. /// internal static string AntiforgeryToken_TokensSwapped { @@ -131,11 +99,11 @@ namespace Microsoft.AspNet.Antiforgery } /// - /// Validation of the provided antiforgery token failed. The cookie "{0}" and the form field "{1}" were swapped. + /// Validation of the provided antiforgery token failed. The cookie token and the form token were swapped. /// - internal static string FormatAntiforgeryToken_TokensSwapped(object p0, object p1) + internal static string FormatAntiforgeryToken_TokensSwapped() { - return string.Format(CultureInfo.CurrentCulture, GetString("AntiforgeryToken_TokensSwapped"), p0, p1); + return GetString("AntiforgeryToken_TokensSwapped"); } /// @@ -170,6 +138,70 @@ namespace Microsoft.AspNet.Antiforgery return string.Format(CultureInfo.CurrentCulture, GetString("AntiforgeryWorker_RequireSSL"), p0, p1, p2); } + /// + /// The required antiforgery cookie "{0}" is not present. + /// + internal static string Antiforgery_CookieToken_MustBeProvided + { + get { return GetString("Antiforgery_CookieToken_MustBeProvided"); } + } + + /// + /// The required antiforgery cookie "{0}" is not present. + /// + internal static string FormatAntiforgery_CookieToken_MustBeProvided(object p0) + { + return string.Format(CultureInfo.CurrentCulture, GetString("Antiforgery_CookieToken_MustBeProvided"), p0); + } + + /// + /// The cookie token must be provided. + /// + internal static string Antiforgery_CookieToken_MustBeProvided_Generic + { + get { return GetString("Antiforgery_CookieToken_MustBeProvided_Generic"); } + } + + /// + /// The cookie token must be provided. + /// + internal static string FormatAntiforgery_CookieToken_MustBeProvided_Generic() + { + return GetString("Antiforgery_CookieToken_MustBeProvided_Generic"); + } + + /// + /// The required antiforgery form field "{0}" is not present. + /// + internal static string Antiforgery_FormToken_MustBeProvided + { + get { return GetString("Antiforgery_FormToken_MustBeProvided"); } + } + + /// + /// The required antiforgery form field "{0}" is not present. + /// + internal static string FormatAntiforgery_FormToken_MustBeProvided(object p0) + { + return string.Format(CultureInfo.CurrentCulture, GetString("Antiforgery_FormToken_MustBeProvided"), p0); + } + + /// + /// The form token must be provided. + /// + internal static string Antiforgery_FormToken_MustBeProvided_Generic + { + get { return GetString("Antiforgery_FormToken_MustBeProvided_Generic"); } + } + + /// + /// The form token must be provided. + /// + internal static string FormatAntiforgery_FormToken_MustBeProvided_Generic() + { + return GetString("Antiforgery_FormToken_MustBeProvided_Generic"); + } + /// /// Value cannot be null or empty. /// diff --git a/src/Microsoft.AspNet.Antiforgery/Resources.resx b/src/Microsoft.AspNet.Antiforgery/Resources.resx index 2cad9e6cf6..cb8f9c3db8 100644 --- a/src/Microsoft.AspNet.Antiforgery/Resources.resx +++ b/src/Microsoft.AspNet.Antiforgery/Resources.resx @@ -127,20 +127,14 @@ The provided antiforgery token was meant for a different claims-based user than the current user. - - The required antiforgery cookie "{0}" is not present. - The antiforgery token could not be decrypted. - - The required antiforgery form field "{0}" is not present. - The antiforgery cookie token and form field token do not match. - Validation of the provided antiforgery token failed. The cookie "{0}" and the form field "{1}" were swapped. + Validation of the provided antiforgery token failed. The cookie token and the form token were swapped. The provided antiforgery token was meant for user "{0}", but the current user is "{1}". @@ -149,6 +143,18 @@ The antiforgery system has the configuration value {0}.{1} = {2}, but the current request is not an SSL request. 0 = nameof(AntiforgeryOptions), 1 = nameof(RequireSsl), 2 = bool.TrueString + + The required antiforgery cookie "{0}" is not present. + + + The cookie token must be provided. + + + The required antiforgery form field "{0}" is not present. + + + The form token must be provided. + Value cannot be null or empty. diff --git a/test/Microsoft.AspNet.Antiforgery.Test/DefaultAntiforgeryTest.cs b/test/Microsoft.AspNet.Antiforgery.Test/DefaultAntiforgeryTest.cs index c775e5cd36..b283ee5aac 100644 --- a/test/Microsoft.AspNet.Antiforgery.Test/DefaultAntiforgeryTest.cs +++ b/test/Microsoft.AspNet.Antiforgery.Test/DefaultAntiforgeryTest.cs @@ -318,7 +318,7 @@ namespace Microsoft.AspNet.Antiforgery } [Fact] - public void Validate_FromInvalidStrings_Throws() + public void ValidateTokens_FromInvalidStrings_Throws() { // Arrange var context = CreateMockContext(new AntiforgeryOptions()); @@ -344,7 +344,7 @@ namespace Microsoft.AspNet.Antiforgery } [Fact] - public void Validate_FromValidStrings_TokensValidatedSuccessfully() + public void ValidateTokens_FromValidStrings_TokensValidatedSuccessfully() { // Arrange var context = CreateMockContext(new AntiforgeryOptions()); @@ -369,16 +369,37 @@ namespace Microsoft.AspNet.Antiforgery } [Fact] - public async Task Validate_FromStore_Failure() + public void ValidateTokens_MissingCookieInTokenSet_Throws() + { + // Arrange + var context = CreateMockContext(new AntiforgeryOptions()); + var antiforgery = GetAntiforgery(context); + + var tokenSet = new AntiforgeryTokenSet("hi", cookieToken: null); + + + // Act + var exception = Assert.Throws( + () => antiforgery.ValidateTokens(context.HttpContext, tokenSet)); + + // Assert + var trimmed = exception.Message.Substring(0, exception.Message.IndexOf(Environment.NewLine)); + Assert.Equal("The cookie token must be provided.", trimmed); + } + + [Fact] + public async Task ValidateRequestAsync_FromStore_Failure() { // Arrange var context = CreateMockContext(new AntiforgeryOptions()); - context.TokenGenerator.Setup(o => o.ValidateTokens( - context.HttpContext, - context.TestTokenSet.OldCookieToken, context.TestTokenSet.FormToken)) - .Throws(new InvalidOperationException("my-message")); - context.TokenSerializer = null; + context.TokenGenerator + .Setup(o => o.ValidateTokens( + context.HttpContext, + context.TestTokenSet.OldCookieToken, + context.TestTokenSet.FormToken)) + .Throws(new InvalidOperationException("my-message")); + var antiforgery = GetAntiforgery(context); // Act & assert @@ -388,16 +409,18 @@ namespace Microsoft.AspNet.Antiforgery } [Fact] - public async Task Validate_FromStore_Success() + public async Task ValidateRequestAsync_FromStore_Success() { // Arrange var context = CreateMockContext(new AntiforgeryOptions()); - context.TokenGenerator.Setup(o => o.ValidateTokens( - context.HttpContext, - context.TestTokenSet.OldCookieToken, context.TestTokenSet.FormToken)) - .Verifiable(); - context.TokenSerializer = null; + context.TokenGenerator + .Setup(o => o.ValidateTokens( + context.HttpContext, + context.TestTokenSet.OldCookieToken, + context.TestTokenSet.FormToken)) + .Verifiable(); + var antiforgery = GetAntiforgery(context); // Act @@ -482,8 +505,11 @@ namespace Microsoft.AspNet.Antiforgery var mockTokenStore = new Mock(MockBehavior.Strict); mockTokenStore.Setup(o => o.GetCookieToken(context)) .Returns(oldCookieToken); - mockTokenStore.Setup(o => o.GetFormTokenAsync(context)) - .Returns(Task.FromResult(formToken)); + + mockTokenStore.Setup(o => o.GetRequestTokensAsync(context)) + .Returns(() => Task.FromResult(new AntiforgeryTokenSet( + testTokenSet.FormTokenString, + testTokenSet.OldCookieTokenString))); if (saveNewCookie) { @@ -502,11 +528,13 @@ namespace Microsoft.AspNet.Antiforgery var formToken = testTokenSet.FormToken; var mockSerializer = new Mock(MockBehavior.Strict); mockSerializer.Setup(o => o.Serialize(formToken)) - .Returns("serialized-form-token"); - mockSerializer.Setup(o => o.Deserialize("serialized-old-cookie-token")) + .Returns(testTokenSet.FormTokenString); + mockSerializer.Setup(o => o.Deserialize(testTokenSet.FormTokenString)) + .Returns(formToken); + mockSerializer.Setup(o => o.Deserialize(testTokenSet.OldCookieTokenString)) .Returns(oldCookieToken); mockSerializer.Setup(o => o.Serialize(newCookieToken)) - .Returns("serialized-new-cookie-token"); + .Returns(testTokenSet.NewCookieTokenString); return mockSerializer; } @@ -558,8 +586,11 @@ namespace Microsoft.AspNet.Antiforgery return new TestTokenSet() { FormToken = new AntiforgeryToken() { IsSessionToken = false }, + FormTokenString = "serialized-form-token", OldCookieToken = new AntiforgeryToken() { IsSessionToken = isOldCookieTokenSessionToken }, + OldCookieTokenString = "serialized-old-cookie-token", NewCookieToken = new AntiforgeryToken() { IsSessionToken = isNewCookieSessionToken }, + NewCookieTokenString = "serialized-new-cookie-token", }; } diff --git a/test/Microsoft.AspNet.Antiforgery.Test/DefaultAntiforgeryTokenGeneratorTest.cs b/test/Microsoft.AspNet.Antiforgery.Test/DefaultAntiforgeryTokenGeneratorTest.cs index 8412e95208..9f8b9bd2b1 100644 --- a/test/Microsoft.AspNet.Antiforgery.Test/DefaultAntiforgeryTokenGeneratorTest.cs +++ b/test/Microsoft.AspNet.Antiforgery.Test/DefaultAntiforgeryTokenGeneratorTest.cs @@ -19,7 +19,6 @@ namespace Microsoft.AspNet.Antiforgery { // Arrange var tokenProvider = new DefaultAntiforgeryTokenGenerator( - optionsAccessor: new TestOptionsManager(), claimUidExtractor: null, additionalDataProvider: null); @@ -40,7 +39,6 @@ namespace Microsoft.AspNet.Antiforgery Assert.False(httpContext.User.Identity.IsAuthenticated); var tokenProvider = new DefaultAntiforgeryTokenGenerator( - optionsAccessor: new TestOptionsManager(), claimUidExtractor: null, additionalDataProvider: null); @@ -74,7 +72,6 @@ namespace Microsoft.AspNet.Antiforgery var claimUidExtractor = new Mock().Object; var tokenProvider = new DefaultAntiforgeryTokenGenerator( - optionsAccessor: new TestOptionsManager(), claimUidExtractor: claimUidExtractor, additionalDataProvider: null); @@ -109,7 +106,6 @@ namespace Microsoft.AspNet.Antiforgery var claimUidExtractor = new Mock().Object; var tokenProvider = new DefaultAntiforgeryTokenGenerator( - optionsAccessor: new TestOptionsManager(), claimUidExtractor: claimUidExtractor, additionalDataProvider: mockAdditionalDataProvider.Object); @@ -148,7 +144,6 @@ namespace Microsoft.AspNet.Antiforgery .Returns(base64ClaimUId); var tokenProvider = new DefaultAntiforgeryTokenGenerator( - optionsAccessor: new TestOptionsManager(), claimUidExtractor: mockClaimUidExtractor.Object, additionalDataProvider: null); @@ -182,7 +177,6 @@ namespace Microsoft.AspNet.Antiforgery var claimUidExtractor = new Mock().Object; var tokenProvider = new DefaultAntiforgeryTokenGenerator( - optionsAccessor: new TestOptionsManager(), claimUidExtractor: claimUidExtractor, additionalDataProvider: null); @@ -209,7 +203,6 @@ namespace Microsoft.AspNet.Antiforgery }; var tokenProvider = new DefaultAntiforgeryTokenGenerator( - optionsAccessor: new TestOptionsManager(), claimUidExtractor: null, additionalDataProvider: null); @@ -226,7 +219,6 @@ namespace Microsoft.AspNet.Antiforgery // Arrange AntiforgeryToken cookieToken = null; var tokenProvider = new DefaultAntiforgeryTokenGenerator( - optionsAccessor: new TestOptionsManager(), claimUidExtractor: null, additionalDataProvider: null); @@ -247,7 +239,6 @@ namespace Microsoft.AspNet.Antiforgery }; var tokenProvider = new DefaultAntiforgeryTokenGenerator( - optionsAccessor: new TestOptionsManager(), claimUidExtractor: null, additionalDataProvider: null); @@ -268,21 +259,16 @@ namespace Microsoft.AspNet.Antiforgery var fieldtoken = new AntiforgeryToken() { IsSessionToken = false }; - var options = new AntiforgeryOptions() - { - CookieName = "my-cookie-name" - }; - var tokenProvider = new DefaultAntiforgeryTokenGenerator( - optionsAccessor: new TestOptionsManager(options), claimUidExtractor: null, additionalDataProvider: null); // Act & assert - var ex = - Assert.Throws( - () => tokenProvider.ValidateTokens(httpContext, null, fieldtoken)); - Assert.Equal(@"The required antiforgery cookie ""my-cookie-name"" is not present.", ex.Message); + var ex = Assert.Throws( + () => tokenProvider.ValidateTokens(httpContext, null, fieldtoken)); + + var trimmed = ex.Message.Substring(0, ex.Message.IndexOf(Environment.NewLine)); + Assert.Equal(@"The cookie token must be provided.", trimmed); } [Fact] @@ -294,21 +280,16 @@ namespace Microsoft.AspNet.Antiforgery var sessionToken = new AntiforgeryToken() { IsSessionToken = true }; - var options = new AntiforgeryOptions() - { - FormFieldName = "my-form-field-name" - }; - var tokenProvider = new DefaultAntiforgeryTokenGenerator( - optionsAccessor: new TestOptionsManager(options), claimUidExtractor: null, additionalDataProvider: null); // Act & assert - var ex = - Assert.Throws( - () => tokenProvider.ValidateTokens(httpContext, sessionToken, null)); - Assert.Equal(@"The required antiforgery form field ""my-form-field-name"" is not present.", ex.Message); + var ex = Assert.Throws( + () => tokenProvider.ValidateTokens(httpContext, sessionToken, null)); + + var trimmed = ex.Message.Substring(0, ex.Message.IndexOf(Environment.NewLine)); + Assert.Equal("The form token must be provided.", trimmed); } [Fact] @@ -321,14 +302,7 @@ namespace Microsoft.AspNet.Antiforgery var sessionToken = new AntiforgeryToken() { IsSessionToken = true }; var fieldtoken = new AntiforgeryToken() { IsSessionToken = false }; - var options = new AntiforgeryOptions() - { - CookieName = "my-cookie-name", - FormFieldName = "my-form-field-name" - }; - var tokenProvider = new DefaultAntiforgeryTokenGenerator( - optionsAccessor: new TestOptionsManager(options), claimUidExtractor: null, additionalDataProvider: null); @@ -338,7 +312,7 @@ namespace Microsoft.AspNet.Antiforgery () => tokenProvider.ValidateTokens(httpContext, fieldtoken, fieldtoken)); Assert.Equal( "Validation of the provided antiforgery token failed. " + - @"The cookie ""my-cookie-name"" and the form field ""my-form-field-name"" were swapped.", + @"The cookie token and the form token were swapped.", ex1.Message); var ex2 = @@ -346,7 +320,7 @@ namespace Microsoft.AspNet.Antiforgery () => tokenProvider.ValidateTokens(httpContext, sessionToken, sessionToken)); Assert.Equal( "Validation of the provided antiforgery token failed. " + - @"The cookie ""my-cookie-name"" and the form field ""my-form-field-name"" were swapped.", + @"The cookie token and the form token were swapped.", ex2.Message); } @@ -361,7 +335,6 @@ namespace Microsoft.AspNet.Antiforgery var fieldtoken = new AntiforgeryToken() { IsSessionToken = false }; var tokenProvider = new DefaultAntiforgeryTokenGenerator( - optionsAccessor: new TestOptionsManager(), claimUidExtractor: null, additionalDataProvider: null); @@ -399,7 +372,6 @@ namespace Microsoft.AspNet.Antiforgery .Returns((string)null); var tokenProvider = new DefaultAntiforgeryTokenGenerator( - optionsAccessor: new TestOptionsManager(), claimUidExtractor: mockClaimUidExtractor.Object, additionalDataProvider: null); @@ -434,7 +406,6 @@ namespace Microsoft.AspNet.Antiforgery .Returns(Convert.ToBase64String(differentToken.GetData())); var tokenProvider = new DefaultAntiforgeryTokenGenerator( - optionsAccessor: new TestOptionsManager(), claimUidExtractor: mockClaimUidExtractor.Object, additionalDataProvider: null); @@ -468,7 +439,6 @@ namespace Microsoft.AspNet.Antiforgery .Returns(false); var tokenProvider = new DefaultAntiforgeryTokenGenerator( - optionsAccessor: new TestOptionsManager(), claimUidExtractor: null, additionalDataProvider: mockAdditionalDataProvider.Object); @@ -500,7 +470,6 @@ namespace Microsoft.AspNet.Antiforgery .Returns(true); var tokenProvider = new DefaultAntiforgeryTokenGenerator( - optionsAccessor: new TestOptionsManager(), claimUidExtractor: null, additionalDataProvider: mockAdditionalDataProvider.Object); @@ -533,7 +502,6 @@ namespace Microsoft.AspNet.Antiforgery .Returns(true); var tokenProvider = new DefaultAntiforgeryTokenGenerator( - optionsAccessor: new TestOptionsManager(), claimUidExtractor: new Mock().Object, additionalDataProvider: mockAdditionalDataProvider.Object); @@ -565,7 +533,6 @@ namespace Microsoft.AspNet.Antiforgery .Returns(Convert.ToBase64String(fieldtoken.ClaimUid.GetData())); var tokenProvider = new DefaultAntiforgeryTokenGenerator( - optionsAccessor: new TestOptionsManager(), claimUidExtractor: mockClaimUidExtractor.Object, additionalDataProvider: null); diff --git a/test/Microsoft.AspNet.Antiforgery.Test/DefaultAntiforgeryTokenStoreTest.cs b/test/Microsoft.AspNet.Antiforgery.Test/DefaultAntiforgeryTokenStoreTest.cs index d2bfc7b458..a3cf81ce87 100644 --- a/test/Microsoft.AspNet.Antiforgery.Test/DefaultAntiforgeryTokenStoreTest.cs +++ b/test/Microsoft.AspNet.Antiforgery.Test/DefaultAntiforgeryTokenStoreTest.cs @@ -7,6 +7,7 @@ using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Microsoft.AspNet.Http; +using Microsoft.AspNet.Http.Internal; using Microsoft.Framework.DependencyInjection; using Moq; using Xunit; @@ -160,20 +161,16 @@ namespace Microsoft.AspNet.Antiforgery } [Fact] - public async Task GetFormToken_FormFieldIsEmpty_ReturnsNull() + public async Task GetRequestTokens_CookieIsEmpty_Throws() { // Arrange - var mockHttpContext = new Mock(); - var requestContext = new Mock(); - var formCollection = new Mock(); - formCollection.Setup(f => f["form-field-name"]).Returns(string.Empty); - requestContext.Setup(o => o.ReadFormAsync(CancellationToken.None)) - .Returns(Task.FromResult(formCollection.Object)); - mockHttpContext.Setup(o => o.Request) - .Returns(requestContext.Object); + var httpContext = new DefaultHttpContext(); + httpContext.Request.Form = new FormCollection(new Dictionary()); + httpContext.Request.Cookies = new ReadableStringCollection(new Dictionary()); var options = new AntiforgeryOptions() { + CookieName = "cookie-name", FormFieldName = "form-field-name", }; @@ -182,81 +179,72 @@ namespace Microsoft.AspNet.Antiforgery tokenSerializer: null); // Act - var token = await tokenStore.GetFormTokenAsync(mockHttpContext.Object); + var exception = await Assert.ThrowsAsync( + async () => await tokenStore.GetRequestTokensAsync(httpContext)); - // Assert - Assert.Null(token); + // Assert + Assert.Equal("The required antiforgery cookie \"cookie-name\" is not present.", exception.Message); } [Fact] - public async Task GetFormToken_FormFieldIsInvalid_PropagatesException() + public async Task GetRequestTokens_FormFieldIsEmpty_Throws() { // Arrange - var formCollection = new Mock(); - formCollection.Setup(f => f["form-field-name"]).Returns("invalid-value"); - - var requestContext = new Mock(); - requestContext.Setup(o => o.ReadFormAsync(CancellationToken.None)) - .Returns(Task.FromResult(formCollection.Object)); - - var mockHttpContext = new Mock(); - mockHttpContext.Setup(o => o.Request) - .Returns(requestContext.Object); - - var expectedException = new InvalidOperationException("some exception"); - var mockSerializer = new Mock(); - mockSerializer.Setup(o => o.Deserialize("invalid-value")) - .Throws(expectedException); + var httpContext = new DefaultHttpContext(); + httpContext.Request.Form = new FormCollection(new Dictionary()); + httpContext.Request.Cookies = new ReadableStringCollection(new Dictionary() + { + { "cookie-name", new string[] { "cookie-value" } }, + }); var options = new AntiforgeryOptions() { + CookieName = "cookie-name", FormFieldName = "form-field-name", }; var tokenStore = new DefaultAntiforgeryTokenStore( optionsAccessor: new TestOptionsManager(options), - tokenSerializer: mockSerializer.Object); + tokenSerializer: null); - // Act & assert + // Act var exception = await Assert.ThrowsAsync( - async () => await tokenStore.GetFormTokenAsync(mockHttpContext.Object)); - Assert.Same(expectedException, exception); + async () => await tokenStore.GetRequestTokensAsync(httpContext)); + + // Assert + Assert.Equal("The required antiforgery form field \"form-field-name\" is not present.", exception.Message); } [Fact] public async Task GetFormToken_FormFieldIsValid_ReturnsToken() { // Arrange - var expectedToken = new AntiforgeryToken(); - - // Arrange - var mockHttpContext = new Mock(); - var requestContext = new Mock(); - var formCollection = new Mock(); - formCollection.Setup(f => f["form-field-name"]).Returns("valid-value"); - requestContext.Setup(o => o.ReadFormAsync(CancellationToken.None)) - .Returns(Task.FromResult(formCollection.Object)); - mockHttpContext.Setup(o => o.Request) - .Returns(requestContext.Object); - - var mockSerializer = new Mock(); - mockSerializer.Setup(o => o.Deserialize("valid-value")) - .Returns(expectedToken); + var httpContext = new DefaultHttpContext(); + httpContext.Request.Form = new FormCollection(new Dictionary() + { + { "form-field-name", new string[] { "form-value" } }, + }); + httpContext.Request.Cookies = new ReadableStringCollection(new Dictionary() + { + { "cookie-name", new string[] { "cookie-value" } }, + }); var options = new AntiforgeryOptions() { + CookieName = "cookie-name", FormFieldName = "form-field-name", }; var tokenStore = new DefaultAntiforgeryTokenStore( optionsAccessor: new TestOptionsManager(options), - tokenSerializer: mockSerializer.Object); + tokenSerializer: null); // Act - var retVal = await tokenStore.GetFormTokenAsync(mockHttpContext.Object); + var tokens = await tokenStore.GetRequestTokensAsync(httpContext); // Assert - Assert.Same(expectedToken, retVal); + Assert.Equal("cookie-value", tokens.CookieToken); + Assert.Equal("form-value", tokens.FormToken); } [Theory] From b922d816be89975a78ba87d1a696e595766464b1 Mon Sep 17 00:00:00 2001 From: unknown Date: Thu, 6 Aug 2015 10:29:16 -0700 Subject: [PATCH 017/296] Fix aspnet/Mvc#2749 - fail gracefully with non-form content This change will report a more specific error when antiforgery is used with non-form content than "invalid content type". --- .../DefaultAntiforgeryTokenStore.cs | 8 +++++ .../DefaultAntiforgeryTokenStoreTest.cs | 34 +++++++++++++++++++ 2 files changed, 42 insertions(+) diff --git a/src/Microsoft.AspNet.Antiforgery/DefaultAntiforgeryTokenStore.cs b/src/Microsoft.AspNet.Antiforgery/DefaultAntiforgeryTokenStore.cs index 7a566d4295..a0fb2085e1 100644 --- a/src/Microsoft.AspNet.Antiforgery/DefaultAntiforgeryTokenStore.cs +++ b/src/Microsoft.AspNet.Antiforgery/DefaultAntiforgeryTokenStore.cs @@ -53,6 +53,14 @@ namespace Microsoft.AspNet.Antiforgery Resources.FormatAntiforgery_CookieToken_MustBeProvided(_options.CookieName)); } + if (!httpContext.Request.HasFormContentType) + { + // Check the content-type before accessing the form collection to make sure + // we throw gracefully. + throw new InvalidOperationException( + Resources.FormatAntiforgery_FormToken_MustBeProvided(_options.FormFieldName)); + } + var form = await httpContext.Request.ReadFormAsync(); var formField = form[_options.FormFieldName]; if (string.IsNullOrEmpty(formField)) diff --git a/test/Microsoft.AspNet.Antiforgery.Test/DefaultAntiforgeryTokenStoreTest.cs b/test/Microsoft.AspNet.Antiforgery.Test/DefaultAntiforgeryTokenStoreTest.cs index a3cf81ce87..5c12c500d6 100644 --- a/test/Microsoft.AspNet.Antiforgery.Test/DefaultAntiforgeryTokenStoreTest.cs +++ b/test/Microsoft.AspNet.Antiforgery.Test/DefaultAntiforgeryTokenStoreTest.cs @@ -186,11 +186,44 @@ namespace Microsoft.AspNet.Antiforgery Assert.Equal("The required antiforgery cookie \"cookie-name\" is not present.", exception.Message); } + [Fact] + public async Task GetRequestTokens_NonFormContentType_Throws() + { + // Arrange + var httpContext = new DefaultHttpContext(); + httpContext.Request.ContentType = "application/json"; + + // Will not be accessed + httpContext.Request.Form = null; + httpContext.Request.Cookies = new ReadableStringCollection(new Dictionary() + { + { "cookie-name", new string[] { "cookie-value" } }, + }); + + var options = new AntiforgeryOptions() + { + CookieName = "cookie-name", + FormFieldName = "form-field-name", + }; + + var tokenStore = new DefaultAntiforgeryTokenStore( + optionsAccessor: new TestOptionsManager(options), + tokenSerializer: null); + + // Act + var exception = await Assert.ThrowsAsync( + async () => await tokenStore.GetRequestTokensAsync(httpContext)); + + // Assert + Assert.Equal("The required antiforgery form field \"form-field-name\" is not present.", exception.Message); + } + [Fact] public async Task GetRequestTokens_FormFieldIsEmpty_Throws() { // Arrange var httpContext = new DefaultHttpContext(); + httpContext.Request.ContentType = "application/x-www-form-urlencoded"; httpContext.Request.Form = new FormCollection(new Dictionary()); httpContext.Request.Cookies = new ReadableStringCollection(new Dictionary() { @@ -220,6 +253,7 @@ namespace Microsoft.AspNet.Antiforgery { // Arrange var httpContext = new DefaultHttpContext(); + httpContext.Request.ContentType = "application/x-www-form-urlencoded"; httpContext.Request.Form = new FormCollection(new Dictionary() { { "form-field-name", new string[] { "form-value" } }, From 3bed6fce9c0dc0d9a8264333d0c94561a6ae25be Mon Sep 17 00:00:00 2001 From: Pranav K Date: Tue, 11 Aug 2015 12:53:18 -0700 Subject: [PATCH 018/296] Reacting to DI changes --- src/Microsoft.AspNet.Antiforgery/ServiceCollectionExtensions.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/src/Microsoft.AspNet.Antiforgery/ServiceCollectionExtensions.cs b/src/Microsoft.AspNet.Antiforgery/ServiceCollectionExtensions.cs index 34db9b5026..297a76a36d 100644 --- a/src/Microsoft.AspNet.Antiforgery/ServiceCollectionExtensions.cs +++ b/src/Microsoft.AspNet.Antiforgery/ServiceCollectionExtensions.cs @@ -3,6 +3,7 @@ using System; using Microsoft.AspNet.Antiforgery; +using Microsoft.Framework.DependencyInjection.Extensions; using Microsoft.Framework.Internal; using Microsoft.Framework.OptionsModel; From 87d4033226b262f58b453a6e4b7144f99755e617 Mon Sep 17 00:00:00 2001 From: Chris R Date: Tue, 11 Aug 2015 14:29:37 -0700 Subject: [PATCH 019/296] #10 React to CoreCLR Cryptography pacakge changes, remove transitive dependencies. --- src/Microsoft.AspNet.Antiforgery/project.json | 11 +---------- 1 file changed, 1 insertion(+), 10 deletions(-) diff --git a/src/Microsoft.AspNet.Antiforgery/project.json b/src/Microsoft.AspNet.Antiforgery/project.json index 017b3d6d99..c5de78d2a6 100644 --- a/src/Microsoft.AspNet.Antiforgery/project.json +++ b/src/Microsoft.AspNet.Antiforgery/project.json @@ -17,15 +17,6 @@ "frameworks" : { "dnx451": { }, - "dnxcore50" : { - "dependencies": { - "System.Collections": "4.0.11-beta-*", - "System.Linq": "4.0.1-beta-*", - "System.Security.Cryptography.RandomNumberGenerator": "4.0.0-beta-*", - "System.Security.Cryptography.Hashing.Algorithms": "4.0.0-beta-*", - "System.Threading": "4.0.11-beta-*", - "Microsoft.CSharp": "4.0.1-beta-*" - } - } + "dnxcore50" : { } } } From 98c3f181dc7e59a4c0e8757e72a79df503cefd1c Mon Sep 17 00:00:00 2001 From: Kiran Challa Date: Tue, 11 Aug 2015 16:54:52 -0700 Subject: [PATCH 020/296] Enable pinning build script --- build.cmd | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) diff --git a/build.cmd b/build.cmd index 5a69c96e86..ccf195aee8 100644 --- a/build.cmd +++ b/build.cmd @@ -3,6 +3,8 @@ cd %~dp0 SETLOCAL SET CACHED_NUGET=%LocalAppData%\NuGet\NuGet.exe +SET BUILDCMD_KOREBUILD_VERSION="" +SET BUILDCMD_DNX_VERSION="" IF EXIST %CACHED_NUGET% goto copynuget echo Downloading latest version of NuGet.exe... @@ -16,21 +18,21 @@ copy %CACHED_NUGET% .nuget\nuget.exe > nul :restore IF EXIST packages\KoreBuild goto run -IF DEFINED BUILDCMD_RELEASE ( - .nuget\NuGet.exe install KoreBuild -version 0.2.1-%BUILDCMD_RELEASE% -ExcludeVersion -o packages -nocache -pre -) ELSE ( +IF %BUILDCMD_KOREBUILD_VERSION%=="" ( .nuget\NuGet.exe install KoreBuild -ExcludeVersion -o packages -nocache -pre +) ELSE ( + .nuget\NuGet.exe install KoreBuild -version %BUILDCMD_KOREBUILD_VERSION% -ExcludeVersion -o packages -nocache -pre ) .nuget\NuGet.exe install Sake -version 0.2 -o packages -ExcludeVersion IF "%SKIP_DNX_INSTALL%"=="1" goto run -IF DEFINED BUILDCMD_RELEASE ( - CALL packages\KoreBuild\build\dnvm install 1.0.0-%BUILDCMD_RELEASE% -runtime CLR -arch x86 -a default +IF %BUILDCMD_DNX_VERSION%=="" ( + CALL packages\KoreBuild\build\dnvm upgrade -runtime CLR -arch x86 ) ELSE ( - CALL packages\KoreBuild\build\dnvm upgrade -runtime CLR -arch x86 + CALL packages\KoreBuild\build\dnvm install %BUILDCMD_DNX_VERSION% -runtime CLR -arch x86 -a default ) CALL packages\KoreBuild\build\dnvm install default -runtime CoreCLR -arch x86 :run CALL packages\KoreBuild\build\dnvm use default -runtime CLR -arch x86 -packages\Sake\tools\Sake.exe -I packages\KoreBuild\build -f makefile.shade %* +packages\Sake\tools\Sake.exe -I packages\KoreBuild\build -f makefile.shade %* \ No newline at end of file From cadf2f8f71d4359694803ca65a2dc4007040d0b6 Mon Sep 17 00:00:00 2001 From: Pranav K Date: Mon, 17 Aug 2015 14:48:57 -0700 Subject: [PATCH 021/296] Updating to release NuGet.config. --- NuGet.Config | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/NuGet.Config b/NuGet.Config index 46c3b3e36c..222ebf7828 100644 --- a/NuGet.Config +++ b/NuGet.Config @@ -1,7 +1,7 @@ - + - + From a89c269a06d5c9a788dc69c6660fbd1fe32539d8 Mon Sep 17 00:00:00 2001 From: Pranav K Date: Tue, 18 Aug 2015 14:00:23 -0700 Subject: [PATCH 022/296] Updating to aspnetliterelease. --- NuGet.Config | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/NuGet.Config b/NuGet.Config index 222ebf7828..08a8a4b55c 100644 --- a/NuGet.Config +++ b/NuGet.Config @@ -1,7 +1,7 @@ - + From 8a19c4e805e37f2f3e93a9e4e1e51a88439bf4ce Mon Sep 17 00:00:00 2001 From: Pranav K Date: Tue, 18 Aug 2015 14:00:24 -0700 Subject: [PATCH 023/296] Updating to aspnetlitedev. --- NuGet.Config | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/NuGet.Config b/NuGet.Config index 46c3b3e36c..5f5695ac3d 100644 --- a/NuGet.Config +++ b/NuGet.Config @@ -1,7 +1,7 @@ - + - + From 7cbbbd9b608241f9cd52c17ccfb349861549c900 Mon Sep 17 00:00:00 2001 From: "N. Taylor Mullen" Date: Wed, 19 Aug 2015 14:54:37 -0700 Subject: [PATCH 024/296] Update NuGet feed from v2 => v3. --- NuGet.Config | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/NuGet.Config b/NuGet.Config index 5f5695ac3d..56d86acac0 100644 --- a/NuGet.Config +++ b/NuGet.Config @@ -2,6 +2,6 @@ - + From ed367df5bc627d430999b86ee1446da97fbdebea Mon Sep 17 00:00:00 2001 From: "N. Taylor Mullen" Date: Thu, 20 Aug 2015 15:38:10 -0700 Subject: [PATCH 025/296] Update 'build.cmd' to pull Sake from v2 NuGet feed. --- build.cmd | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/build.cmd b/build.cmd index ccf195aee8..b54d91cf74 100644 --- a/build.cmd +++ b/build.cmd @@ -23,7 +23,7 @@ IF %BUILDCMD_KOREBUILD_VERSION%=="" ( ) ELSE ( .nuget\NuGet.exe install KoreBuild -version %BUILDCMD_KOREBUILD_VERSION% -ExcludeVersion -o packages -nocache -pre ) -.nuget\NuGet.exe install Sake -version 0.2 -o packages -ExcludeVersion +.nuget\NuGet.exe install Sake -ExcludeVersion -Source https://www.nuget.org/api/v2/ -Out packages IF "%SKIP_DNX_INSTALL%"=="1" goto run IF %BUILDCMD_DNX_VERSION%=="" ( From 2a7dcea2661dca820eee6948fc1f3aada2ef79fa Mon Sep 17 00:00:00 2001 From: "N. Taylor Mullen" Date: Thu, 20 Aug 2015 20:46:58 -0700 Subject: [PATCH 026/296] Update 'build.sh' to pull Sake from v2 NuGet feed. --- build.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/build.sh b/build.sh index 203b034a33..fd756bc44b 100644 --- a/build.sh +++ b/build.sh @@ -24,7 +24,7 @@ fi if test ! -d packages/KoreBuild; then mono .nuget/nuget.exe install KoreBuild -ExcludeVersion -o packages -nocache -pre - mono .nuget/nuget.exe install Sake -version 0.2 -o packages -ExcludeVersion + mono .nuget/nuget.exe install Sake -ExcludeVersion -Source https://www.nuget.org/api/v2/ -Out packages fi if ! type dnvm > /dev/null 2>&1; then From 7bb59a287c3c89efeece1248efd1e77c5e45cca0 Mon Sep 17 00:00:00 2001 From: Chris R Date: Fri, 28 Aug 2015 14:23:17 -0700 Subject: [PATCH 027/296] React to string[] -> StringValues changes. --- .../DefaultAntiforgery.cs | 2 +- .../DefaultAntiforgeryTokenStoreTest.cs | 37 ++++++++----------- 2 files changed, 17 insertions(+), 22 deletions(-) diff --git a/src/Microsoft.AspNet.Antiforgery/DefaultAntiforgery.cs b/src/Microsoft.AspNet.Antiforgery/DefaultAntiforgery.cs index b4497ebfed..18a11c7d17 100644 --- a/src/Microsoft.AspNet.Antiforgery/DefaultAntiforgery.cs +++ b/src/Microsoft.AspNet.Antiforgery/DefaultAntiforgery.cs @@ -149,7 +149,7 @@ namespace Microsoft.AspNet.Antiforgery // Adding X-Frame-Options header to prevent ClickJacking. See // http://tools.ietf.org/html/draft-ietf-websec-x-frame-options-10 // for more information. - context.Response.Headers.Set("X-Frame-Options", "SAMEORIGIN"); + context.Response.Headers["X-Frame-Options"] = "SAMEORIGIN"; } } diff --git a/test/Microsoft.AspNet.Antiforgery.Test/DefaultAntiforgeryTokenStoreTest.cs b/test/Microsoft.AspNet.Antiforgery.Test/DefaultAntiforgeryTokenStoreTest.cs index 5c12c500d6..8e73c9d69e 100644 --- a/test/Microsoft.AspNet.Antiforgery.Test/DefaultAntiforgeryTokenStoreTest.cs +++ b/test/Microsoft.AspNet.Antiforgery.Test/DefaultAntiforgeryTokenStoreTest.cs @@ -4,11 +4,11 @@ #if DNX451 using System; using System.Collections.Generic; -using System.Threading; using System.Threading.Tasks; using Microsoft.AspNet.Http; using Microsoft.AspNet.Http.Internal; using Microsoft.Framework.DependencyInjection; +using Microsoft.Framework.Primitives; using Moq; using Xunit; @@ -24,7 +24,7 @@ namespace Microsoft.AspNet.Antiforgery // Arrange var requestCookies = new Mock(); requestCookies - .Setup(o => o.Get(It.IsAny())) + .Setup(o => o[It.IsAny()]) .Returns(string.Empty); var mockHttpContext = new Mock(); mockHttpContext @@ -55,7 +55,7 @@ namespace Microsoft.AspNet.Antiforgery // Arrange var requestCookies = new Mock(); requestCookies - .Setup(o => o.Get(It.IsAny())) + .Setup(o => o[It.IsAny()]) .Returns(string.Empty); var mockHttpContext = new Mock(); mockHttpContext @@ -165,8 +165,8 @@ namespace Microsoft.AspNet.Antiforgery { // Arrange var httpContext = new DefaultHttpContext(); - httpContext.Request.Form = new FormCollection(new Dictionary()); - httpContext.Request.Cookies = new ReadableStringCollection(new Dictionary()); + httpContext.Request.Form = new FormCollection(new Dictionary()); + httpContext.Request.Cookies = new ReadableStringCollection(new Dictionary()); var options = new AntiforgeryOptions() { @@ -195,9 +195,9 @@ namespace Microsoft.AspNet.Antiforgery // Will not be accessed httpContext.Request.Form = null; - httpContext.Request.Cookies = new ReadableStringCollection(new Dictionary() + httpContext.Request.Cookies = new ReadableStringCollection(new Dictionary() { - { "cookie-name", new string[] { "cookie-value" } }, + { "cookie-name", "cookie-value" }, }); var options = new AntiforgeryOptions() @@ -224,10 +224,10 @@ namespace Microsoft.AspNet.Antiforgery // Arrange var httpContext = new DefaultHttpContext(); httpContext.Request.ContentType = "application/x-www-form-urlencoded"; - httpContext.Request.Form = new FormCollection(new Dictionary()); - httpContext.Request.Cookies = new ReadableStringCollection(new Dictionary() + httpContext.Request.Form = new FormCollection(new Dictionary()); + httpContext.Request.Cookies = new ReadableStringCollection(new Dictionary() { - { "cookie-name", new string[] { "cookie-value" } }, + { "cookie-name", "cookie-value" }, }); var options = new AntiforgeryOptions() @@ -254,13 +254,13 @@ namespace Microsoft.AspNet.Antiforgery // Arrange var httpContext = new DefaultHttpContext(); httpContext.Request.ContentType = "application/x-www-form-urlencoded"; - httpContext.Request.Form = new FormCollection(new Dictionary() + httpContext.Request.Form = new FormCollection(new Dictionary() { - { "form-field-name", new string[] { "form-value" } }, + { "form-field-name", "form-value" }, }); - httpContext.Request.Cookies = new ReadableStringCollection(new Dictionary() + httpContext.Request.Cookies = new ReadableStringCollection(new Dictionary() { - { "cookie-name", new string[] { "cookie-value" } }, + { "cookie-name", "cookie-value" }, }); var options = new AntiforgeryOptions() @@ -419,22 +419,17 @@ namespace Microsoft.AspNet.Antiforgery return this[key]; } - public IList GetValues(string key) - { - throw new NotImplementedException(); - } - public bool ContainsKey(string key) { return _dictionary.ContainsKey(key); } - public string this[string key] + public StringValues this[string key] { get { return _dictionary[key]; } } - public IEnumerator> GetEnumerator() + public IEnumerator> GetEnumerator() { throw new NotImplementedException(); } From f5c8bf09e2c7ec04443fa8fce6a1453c251fc7e4 Mon Sep 17 00:00:00 2001 From: Hao Kung Date: Wed, 2 Sep 2015 15:28:52 -0700 Subject: [PATCH 028/296] React to options --- NuGet.Config | 2 +- .../AntiforgeryOptionsSetup.cs | 4 +--- src/Microsoft.AspNet.Antiforgery/DefaultAntiforgery.cs | 2 +- .../DefaultAntiforgeryTokenStore.cs | 2 +- .../AntiforgeryOptionsSetupTest.cs | 4 ++-- .../DefaultAntiforgeryTest.cs | 9 ++------- .../TestOptionsManager.cs | 7 +------ 7 files changed, 9 insertions(+), 21 deletions(-) diff --git a/NuGet.Config b/NuGet.Config index 56d86acac0..b20b7336fc 100644 --- a/NuGet.Config +++ b/NuGet.Config @@ -1,4 +1,4 @@ - + diff --git a/src/Microsoft.AspNet.Antiforgery/AntiforgeryOptionsSetup.cs b/src/Microsoft.AspNet.Antiforgery/AntiforgeryOptionsSetup.cs index 76030662ad..f37c3e9b2d 100644 --- a/src/Microsoft.AspNet.Antiforgery/AntiforgeryOptionsSetup.cs +++ b/src/Microsoft.AspNet.Antiforgery/AntiforgeryOptionsSetup.cs @@ -13,10 +13,8 @@ namespace Microsoft.AspNet.Antiforgery public class AntiforgeryOptionsSetup : ConfigureOptions { public AntiforgeryOptionsSetup(IOptions dataProtectionOptionsAccessor) - : base((options) => ConfigureOptions(options, dataProtectionOptionsAccessor.Options)) + : base((options) => ConfigureOptions(options, dataProtectionOptionsAccessor.Value)) { - // We want this to run after any user setups to compute a default name if needed. - Order = 10000; } public static void ConfigureOptions(AntiforgeryOptions options, DataProtectionOptions dataProtectionOptions) diff --git a/src/Microsoft.AspNet.Antiforgery/DefaultAntiforgery.cs b/src/Microsoft.AspNet.Antiforgery/DefaultAntiforgery.cs index 18a11c7d17..b68ae093b3 100644 --- a/src/Microsoft.AspNet.Antiforgery/DefaultAntiforgery.cs +++ b/src/Microsoft.AspNet.Antiforgery/DefaultAntiforgery.cs @@ -30,7 +30,7 @@ namespace Microsoft.AspNet.Antiforgery IAntiforgeryTokenStore tokenStore, IHtmlEncoder htmlEncoder) { - _options = antiforgeryOptionsAccessor.Options; + _options = antiforgeryOptionsAccessor.Value; _tokenGenerator = tokenGenerator; _tokenSerializer = tokenSerializer; _tokenStore = tokenStore; diff --git a/src/Microsoft.AspNet.Antiforgery/DefaultAntiforgeryTokenStore.cs b/src/Microsoft.AspNet.Antiforgery/DefaultAntiforgeryTokenStore.cs index a0fb2085e1..cd0667f0fb 100644 --- a/src/Microsoft.AspNet.Antiforgery/DefaultAntiforgeryTokenStore.cs +++ b/src/Microsoft.AspNet.Antiforgery/DefaultAntiforgeryTokenStore.cs @@ -21,7 +21,7 @@ namespace Microsoft.AspNet.Antiforgery [NotNull] IOptions optionsAccessor, [NotNull] IAntiforgeryTokenSerializer tokenSerializer) { - _options = optionsAccessor.Options; + _options = optionsAccessor.Value; _tokenSerializer = tokenSerializer; } diff --git a/test/Microsoft.AspNet.Antiforgery.Test/AntiforgeryOptionsSetupTest.cs b/test/Microsoft.AspNet.Antiforgery.Test/AntiforgeryOptionsSetupTest.cs index 68bd517548..b3b9bc72e5 100644 --- a/test/Microsoft.AspNet.Antiforgery.Test/AntiforgeryOptionsSetupTest.cs +++ b/test/Microsoft.AspNet.Antiforgery.Test/AntiforgeryOptionsSetupTest.cs @@ -25,7 +25,7 @@ namespace Microsoft.AspNet.Antiforgery var options = services.GetRequiredService>(); // Act - var cookieName = options.Options.CookieName; + var cookieName = options.Value.CookieName; // Assert Assert.Equal(expectedCookieName, cookieName); @@ -49,7 +49,7 @@ namespace Microsoft.AspNet.Antiforgery var options = services.GetRequiredService>(); // Act - var cookieName = options.Options.CookieName; + var cookieName = options.Value.CookieName; // Assert Assert.Equal("antiforgery", cookieName); diff --git a/test/Microsoft.AspNet.Antiforgery.Test/DefaultAntiforgeryTest.cs b/test/Microsoft.AspNet.Antiforgery.Test/DefaultAntiforgeryTest.cs index b283ee5aac..912bc015cc 100644 --- a/test/Microsoft.AspNet.Antiforgery.Test/DefaultAntiforgeryTest.cs +++ b/test/Microsoft.AspNet.Antiforgery.Test/DefaultAntiforgeryTest.cs @@ -466,7 +466,7 @@ namespace Microsoft.AspNet.Antiforgery var optionsManager = new TestOptionsManager(); if (options != null) { - optionsManager.Options = options; + optionsManager.Value = options; } return new DefaultAntiforgery( @@ -628,12 +628,7 @@ namespace Microsoft.AspNet.Antiforgery private class TestOptionsManager : IOptions { - public AntiforgeryOptions Options { get; set; } = new AntiforgeryOptions(); - - public AntiforgeryOptions GetNamedOptions(string name) - { - throw new NotImplementedException(); - } + public AntiforgeryOptions Value { get; set; } = new AntiforgeryOptions(); } } } \ No newline at end of file diff --git a/test/Microsoft.AspNet.Antiforgery.Test/TestOptionsManager.cs b/test/Microsoft.AspNet.Antiforgery.Test/TestOptionsManager.cs index 2a74d9764e..9df6d86e2d 100644 --- a/test/Microsoft.AspNet.Antiforgery.Test/TestOptionsManager.cs +++ b/test/Microsoft.AspNet.Antiforgery.Test/TestOptionsManager.cs @@ -17,11 +17,6 @@ namespace Microsoft.AspNet.Antiforgery Options = options; } - public AntiforgeryOptions Options { get; set; } = new AntiforgeryOptions(); - - public AntiforgeryOptions GetNamedOptions(string name) - { - throw new NotImplementedException(); - } + public AntiforgeryOptions Value { get; set; } = new AntiforgeryOptions(); } } From 83ea8051c8cae8e82a8b0d126fda85e18dade435 Mon Sep 17 00:00:00 2001 From: Hao Kung Date: Wed, 2 Sep 2015 15:44:39 -0700 Subject: [PATCH 029/296] Update test --- samples/AntiforgerySample/FormPostSampleMiddleware.cs | 2 +- .../AntiforgeryOptionsSetupTest.cs | 7 +++---- .../TestOptionsManager.cs | 2 +- 3 files changed, 5 insertions(+), 6 deletions(-) diff --git a/samples/AntiforgerySample/FormPostSampleMiddleware.cs b/samples/AntiforgerySample/FormPostSampleMiddleware.cs index dc27fb7abe..494e84a0b5 100644 --- a/samples/AntiforgerySample/FormPostSampleMiddleware.cs +++ b/samples/AntiforgerySample/FormPostSampleMiddleware.cs @@ -22,7 +22,7 @@ namespace AntiforgerySample { _next = next; _antiforgery = antiforgery; - _options = options.Options; + _options = options.Value; } public async Task Invoke(HttpContext context) diff --git a/test/Microsoft.AspNet.Antiforgery.Test/AntiforgeryOptionsSetupTest.cs b/test/Microsoft.AspNet.Antiforgery.Test/AntiforgeryOptionsSetupTest.cs index b3b9bc72e5..946a0812e6 100644 --- a/test/Microsoft.AspNet.Antiforgery.Test/AntiforgeryOptionsSetupTest.cs +++ b/test/Microsoft.AspNet.Antiforgery.Test/AntiforgeryOptionsSetupTest.cs @@ -36,14 +36,13 @@ namespace Microsoft.AspNet.Antiforgery { // Arrange var serviceCollection = new ServiceCollection(); - serviceCollection.AddAntiforgery(); - serviceCollection.ConfigureDataProtection(o => o.SetApplicationName("HelloWorldApp")); - serviceCollection.Configure(o => { Assert.Null(o.CookieName); o.CookieName = "antiforgery"; - }, order: 9999); + }); + serviceCollection.AddAntiforgery(); + serviceCollection.ConfigureDataProtection(o => o.SetApplicationName("HelloWorldApp")); var services = serviceCollection.BuildServiceProvider(); var options = services.GetRequiredService>(); diff --git a/test/Microsoft.AspNet.Antiforgery.Test/TestOptionsManager.cs b/test/Microsoft.AspNet.Antiforgery.Test/TestOptionsManager.cs index 9df6d86e2d..e1c1c5cbcc 100644 --- a/test/Microsoft.AspNet.Antiforgery.Test/TestOptionsManager.cs +++ b/test/Microsoft.AspNet.Antiforgery.Test/TestOptionsManager.cs @@ -14,7 +14,7 @@ namespace Microsoft.AspNet.Antiforgery public TestOptionsManager(AntiforgeryOptions options) { - Options = options; + Value = options; } public AntiforgeryOptions Value { get; set; } = new AntiforgeryOptions(); From 6bc4a409265859ee7df6185199edf0e9a9493084 Mon Sep 17 00:00:00 2001 From: David Fowler Date: Fri, 4 Sep 2015 01:33:47 -0700 Subject: [PATCH 030/296] Setup ci stuff --- .travis.yml | 4 ++++ appveyor.yml | 7 +++++++ build.sh | 0 3 files changed, 11 insertions(+) create mode 100644 .travis.yml create mode 100644 appveyor.yml mode change 100644 => 100755 build.sh diff --git a/.travis.yml b/.travis.yml new file mode 100644 index 0000000000..238174a4e4 --- /dev/null +++ b/.travis.yml @@ -0,0 +1,4 @@ +language: csharp +sudo: false +script: + - ./build.sh --quiet verify diff --git a/appveyor.yml b/appveyor.yml new file mode 100644 index 0000000000..58a3e1bc22 --- /dev/null +++ b/appveyor.yml @@ -0,0 +1,7 @@ +init: + - git config --global core.autocrlf true +build_script: + - build.cmd --quiet --parallel verify +clone_depth: 1 +test: off +deploy: off \ No newline at end of file diff --git a/build.sh b/build.sh old mode 100644 new mode 100755 From 3240ef37e1aabb8a0ab422a5eb0a6d8ba5ff6e89 Mon Sep 17 00:00:00 2001 From: Pranav K Date: Thu, 10 Sep 2015 16:25:41 -0700 Subject: [PATCH 031/296] Adding NeutralResourcesLanguageAttribute --- src/Microsoft.AspNet.Antiforgery/Properties/AssemblyInfo.cs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/Microsoft.AspNet.Antiforgery/Properties/AssemblyInfo.cs b/src/Microsoft.AspNet.Antiforgery/Properties/AssemblyInfo.cs index a91599ff84..6a761b69c9 100644 --- a/src/Microsoft.AspNet.Antiforgery/Properties/AssemblyInfo.cs +++ b/src/Microsoft.AspNet.Antiforgery/Properties/AssemblyInfo.cs @@ -2,8 +2,10 @@ // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Reflection; +using System.Resources; using System.Runtime.CompilerServices; [assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")] [assembly: InternalsVisibleTo("Microsoft.AspNet.Antiforgery.Test")] [assembly: AssemblyMetadata("Serviceable", "True")] +[assembly: NeutralResourcesLanguage("en-us")] From e0ec2da711aa97f70e4dac25aa4a99a1230ca4f3 Mon Sep 17 00:00:00 2001 From: Pranav K Date: Fri, 11 Sep 2015 16:26:06 -0700 Subject: [PATCH 032/296] Replacing NotNull with thrown exceptions --- .../AntiforgeryOptions.cs | 38 +++++++++++-- .../DefaultAntiforgery.cs | 54 +++++++++++++++---- .../DefaultAntiforgeryTokenGenerator.cs | 10 ++++ .../DefaultAntiforgeryTokenSerializer.cs | 15 ++++-- .../DefaultAntiforgeryTokenStore.cs | 37 +++++++++++-- .../IAntiforgery.cs | 15 +++--- .../IAntiforgeryTokenGenerator.cs | 9 ++-- .../IAntiforgeryTokenStore.cs | 7 ++- .../ServiceCollectionExtensions.cs | 24 +++++++-- src/Microsoft.AspNet.Antiforgery/project.json | 1 - .../DefaultAntiforgeryTokenStoreTest.cs | 15 +++--- 11 files changed, 175 insertions(+), 50 deletions(-) diff --git a/src/Microsoft.AspNet.Antiforgery/AntiforgeryOptions.cs b/src/Microsoft.AspNet.Antiforgery/AntiforgeryOptions.cs index 6955481157..db66421a15 100644 --- a/src/Microsoft.AspNet.Antiforgery/AntiforgeryOptions.cs +++ b/src/Microsoft.AspNet.Antiforgery/AntiforgeryOptions.cs @@ -1,7 +1,7 @@ // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. -using Microsoft.Framework.Internal; +using System; namespace Microsoft.AspNet.Antiforgery { @@ -11,6 +11,8 @@ namespace Microsoft.AspNet.Antiforgery public class AntiforgeryOptions { private const string AntiforgeryTokenFieldName = "__RequestVerificationToken"; + private string _cookieName; + private string _formFieldName = AntiforgeryTokenFieldName; /// /// Specifies the name of the cookie that is used by the antiforgery @@ -20,12 +22,42 @@ namespace Microsoft.AspNet.Antiforgery /// If an explicit name is not provided, the system will automatically /// generate a name. /// - public string CookieName { get; [param: NotNull] set; } + public string CookieName + { + get + { + return _cookieName; + } + set + { + if (value == null) + { + throw new ArgumentNullException(nameof(value)); + } + + _cookieName = value; + } + } /// /// Specifies the name of the antiforgery token field that is used by the antiforgery system. /// - public string FormFieldName { get; [param: NotNull] set; } = AntiforgeryTokenFieldName; + public string FormFieldName + { + get + { + return _formFieldName; + } + set + { + if (value == null) + { + throw new ArgumentNullException(nameof(value)); + } + + _formFieldName = value; + } + } /// /// Specifies whether SSL is required for the antiforgery system diff --git a/src/Microsoft.AspNet.Antiforgery/DefaultAntiforgery.cs b/src/Microsoft.AspNet.Antiforgery/DefaultAntiforgery.cs index b68ae093b3..c2c66444ce 100644 --- a/src/Microsoft.AspNet.Antiforgery/DefaultAntiforgery.cs +++ b/src/Microsoft.AspNet.Antiforgery/DefaultAntiforgery.cs @@ -5,7 +5,6 @@ using System; using System.Diagnostics; using System.Threading.Tasks; using Microsoft.AspNet.Http; -using Microsoft.Framework.Internal; using Microsoft.Framework.OptionsModel; using Microsoft.Framework.WebEncoders; @@ -38,8 +37,13 @@ namespace Microsoft.AspNet.Antiforgery } /// - public string GetHtml([NotNull] HttpContext context) + public string GetHtml(HttpContext context) { + if (context == null) + { + throw new ArgumentNullException(nameof(context)); + } + CheckSSLConfig(context); var tokenSet = GetAndStoreTokens(context); @@ -53,27 +57,42 @@ namespace Microsoft.AspNet.Antiforgery } /// - public AntiforgeryTokenSet GetAndStoreTokens([NotNull] HttpContext context) + public AntiforgeryTokenSet GetAndStoreTokens(HttpContext context) { + if (context == null) + { + throw new ArgumentNullException(nameof(context)); + } + CheckSSLConfig(context); - + var tokenSet = GetTokensInternal(context); SaveCookieTokenAndHeader(context, tokenSet.CookieToken); return Serialize(tokenSet); } /// - public AntiforgeryTokenSet GetTokens([NotNull] HttpContext context) + public AntiforgeryTokenSet GetTokens(HttpContext context) { + if (context == null) + { + throw new ArgumentNullException(nameof(context)); + } + CheckSSLConfig(context); - + var tokenSet = GetTokensInternal(context); return Serialize(tokenSet); } /// - public async Task ValidateRequestAsync([NotNull] HttpContext context) + public async Task ValidateRequestAsync(HttpContext context) { + if (context == null) + { + throw new ArgumentNullException(nameof(context)); + } + CheckSSLConfig(context); var tokens = await _tokenStore.GetRequestTokensAsync(context); @@ -81,8 +100,13 @@ namespace Microsoft.AspNet.Antiforgery } /// - public void ValidateTokens([NotNull] HttpContext context, AntiforgeryTokenSet antiforgeryTokenSet) + public void ValidateTokens(HttpContext context, AntiforgeryTokenSet antiforgeryTokenSet) { + if (context == null) + { + throw new ArgumentNullException(nameof(context)); + } + CheckSSLConfig(context); if (string.IsNullOrEmpty(antiforgeryTokenSet.CookieToken)) @@ -111,8 +135,13 @@ namespace Microsoft.AspNet.Antiforgery } /// - public void SetCookieTokenAndHeader([NotNull] HttpContext context) + public void SetCookieTokenAndHeader(HttpContext context) { + if (context == null) + { + throw new ArgumentNullException(nameof(context)); + } + CheckSSLConfig(context); var cookieToken = GetCookieTokenDoesNotThrow(context); @@ -135,9 +164,14 @@ namespace Microsoft.AspNet.Antiforgery } private void SaveCookieTokenAndHeader( - [NotNull] HttpContext context, + HttpContext context, AntiforgeryToken cookieToken) { + if (context == null) + { + throw new ArgumentNullException(nameof(context)); + } + if (cookieToken != null) { // Persist the new cookie if it is not null. diff --git a/src/Microsoft.AspNet.Antiforgery/DefaultAntiforgeryTokenGenerator.cs b/src/Microsoft.AspNet.Antiforgery/DefaultAntiforgeryTokenGenerator.cs index 700ecaaa6e..c23661ccc4 100644 --- a/src/Microsoft.AspNet.Antiforgery/DefaultAntiforgeryTokenGenerator.cs +++ b/src/Microsoft.AspNet.Antiforgery/DefaultAntiforgeryTokenGenerator.cs @@ -35,6 +35,11 @@ namespace Microsoft.AspNet.Antiforgery HttpContext httpContext, AntiforgeryToken cookieToken) { + if (httpContext == null) + { + throw new ArgumentNullException(nameof(httpContext)); + } + Debug.Assert(IsCookieTokenValid(cookieToken)); var formToken = new AntiforgeryToken() @@ -92,6 +97,11 @@ namespace Microsoft.AspNet.Antiforgery AntiforgeryToken sessionToken, AntiforgeryToken fieldToken) { + if (httpContext == null) + { + throw new ArgumentNullException(nameof(httpContext)); + } + if (sessionToken == null) { throw new ArgumentNullException( diff --git a/src/Microsoft.AspNet.Antiforgery/DefaultAntiforgeryTokenSerializer.cs b/src/Microsoft.AspNet.Antiforgery/DefaultAntiforgeryTokenSerializer.cs index 971af9c3a0..c5eb46a413 100644 --- a/src/Microsoft.AspNet.Antiforgery/DefaultAntiforgeryTokenSerializer.cs +++ b/src/Microsoft.AspNet.Antiforgery/DefaultAntiforgeryTokenSerializer.cs @@ -5,7 +5,6 @@ using System; using System.IO; using Microsoft.AspNet.DataProtection; using Microsoft.AspNet.WebUtilities; -using Microsoft.Framework.Internal; namespace Microsoft.AspNet.Antiforgery { @@ -16,8 +15,13 @@ namespace Microsoft.AspNet.Antiforgery private readonly IDataProtector _cryptoSystem; private const byte TokenVersion = 0x01; - public DefaultAntiforgeryTokenSerializer([NotNull] IDataProtectionProvider provider) + public DefaultAntiforgeryTokenSerializer(IDataProtectionProvider provider) { + if (provider == null) + { + throw new ArgumentNullException(nameof(provider)); + } + _cryptoSystem = provider.CreateProtector(Purpose); } @@ -102,8 +106,13 @@ namespace Microsoft.AspNet.Antiforgery return deserializedToken; } - public string Serialize([NotNull] AntiforgeryToken token) + public string Serialize(AntiforgeryToken token) { + if (token == null) + { + throw new ArgumentNullException(nameof(token)); + } + using (var stream = new MemoryStream()) { using (var writer = new BinaryWriter(stream)) diff --git a/src/Microsoft.AspNet.Antiforgery/DefaultAntiforgeryTokenStore.cs b/src/Microsoft.AspNet.Antiforgery/DefaultAntiforgeryTokenStore.cs index cd0667f0fb..0e67c14827 100644 --- a/src/Microsoft.AspNet.Antiforgery/DefaultAntiforgeryTokenStore.cs +++ b/src/Microsoft.AspNet.Antiforgery/DefaultAntiforgeryTokenStore.cs @@ -6,7 +6,6 @@ using System.Diagnostics; using System.Threading.Tasks; using Microsoft.AspNet.Http; using Microsoft.Framework.DependencyInjection; -using Microsoft.Framework.Internal; using Microsoft.Framework.OptionsModel; namespace Microsoft.AspNet.Antiforgery @@ -18,15 +17,30 @@ namespace Microsoft.AspNet.Antiforgery private readonly IAntiforgeryTokenSerializer _tokenSerializer; public DefaultAntiforgeryTokenStore( - [NotNull] IOptions optionsAccessor, - [NotNull] IAntiforgeryTokenSerializer tokenSerializer) + IOptions optionsAccessor, + IAntiforgeryTokenSerializer tokenSerializer) { + if (optionsAccessor == null) + { + throw new ArgumentNullException(nameof(optionsAccessor)); + } + + if (tokenSerializer == null) + { + throw new ArgumentNullException(nameof(tokenSerializer)); + } + _options = optionsAccessor.Value; _tokenSerializer = tokenSerializer; } public AntiforgeryToken GetCookieToken(HttpContext httpContext) { + if (httpContext == null) + { + throw new ArgumentNullException(nameof(httpContext)); + } + var services = httpContext.RequestServices; var contextAccessor = services.GetRequiredService(); if (contextAccessor.Value != null) @@ -44,8 +58,13 @@ namespace Microsoft.AspNet.Antiforgery return _tokenSerializer.Deserialize(requestCookie); } - public async Task GetRequestTokensAsync([NotNull] HttpContext httpContext) + public async Task GetRequestTokensAsync(HttpContext httpContext) { + if (httpContext == null) + { + throw new ArgumentNullException(nameof(httpContext)); + } + var requestCookie = httpContext.Request.Cookies[_options.CookieName]; if (string.IsNullOrEmpty(requestCookie)) { @@ -74,6 +93,16 @@ namespace Microsoft.AspNet.Antiforgery public void SaveCookieToken(HttpContext httpContext, AntiforgeryToken token) { + if (httpContext == null) + { + throw new ArgumentNullException(nameof(httpContext)); + } + + if (token == null) + { + throw new ArgumentNullException(nameof(token)); + } + // Add the cookie to the request based context. // This is useful if the cookie needs to be reloaded in the context of the same request. diff --git a/src/Microsoft.AspNet.Antiforgery/IAntiforgery.cs b/src/Microsoft.AspNet.Antiforgery/IAntiforgery.cs index 564dbd2b83..f57c5689ae 100644 --- a/src/Microsoft.AspNet.Antiforgery/IAntiforgery.cs +++ b/src/Microsoft.AspNet.Antiforgery/IAntiforgery.cs @@ -1,9 +1,8 @@ -// Copyright (c) .NET Foundation. All rights reserved. +// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Threading.Tasks; using Microsoft.AspNet.Http; -using Microsoft.Framework.Internal; namespace Microsoft.AspNet.Antiforgery { @@ -25,7 +24,7 @@ namespace Microsoft.AspNet.Antiforgery /// This method has a side effect: /// A response cookie is set if there is no valid cookie associated with the request. /// - string GetHtml([NotNull] HttpContext context); + string GetHtml(HttpContext context); /// /// Generates an for this request and stores the cookie token @@ -37,7 +36,7 @@ namespace Microsoft.AspNet.Antiforgery /// This method has a side effect: /// A response cookie is set if there is no valid cookie associated with the request. /// - AntiforgeryTokenSet GetAndStoreTokens([NotNull] HttpContext context); + AntiforgeryTokenSet GetAndStoreTokens(HttpContext context); /// /// Generates an for this request. @@ -48,13 +47,13 @@ namespace Microsoft.AspNet.Antiforgery /// is responsible for setting the response cookie and injecting the returned /// form token as appropriate. /// - AntiforgeryTokenSet GetTokens([NotNull] HttpContext context); + AntiforgeryTokenSet GetTokens(HttpContext context); /// /// Validates an antiforgery token that was supplied as part of the request. /// /// The associated with the current request. - Task ValidateRequestAsync([NotNull] HttpContext context); + Task ValidateRequestAsync(HttpContext context); /// /// Validates an for the current request. @@ -63,12 +62,12 @@ namespace Microsoft.AspNet.Antiforgery /// /// The (cookie and form token) for this request. /// - void ValidateTokens([NotNull] HttpContext context, AntiforgeryTokenSet antiforgeryTokenSet); + void ValidateTokens(HttpContext context, AntiforgeryTokenSet antiforgeryTokenSet); /// /// Generates and stores an antiforgery cookie token if one is not available or not valid. /// /// The associated with the current request. - void SetCookieTokenAndHeader([NotNull] HttpContext context); + void SetCookieTokenAndHeader(HttpContext context); } } diff --git a/src/Microsoft.AspNet.Antiforgery/IAntiforgeryTokenGenerator.cs b/src/Microsoft.AspNet.Antiforgery/IAntiforgeryTokenGenerator.cs index bdf01af11e..0918d26917 100644 --- a/src/Microsoft.AspNet.Antiforgery/IAntiforgeryTokenGenerator.cs +++ b/src/Microsoft.AspNet.Antiforgery/IAntiforgeryTokenGenerator.cs @@ -2,7 +2,6 @@ // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using Microsoft.AspNet.Http; -using Microsoft.Framework.Internal; namespace Microsoft.AspNet.Antiforgery { @@ -17,7 +16,7 @@ namespace Microsoft.AspNet.Antiforgery // Given a cookie token, generates a corresponding form token. // The incoming cookie token must be valid. AntiforgeryToken GenerateFormToken( - [NotNull] HttpContext httpContext, + HttpContext httpContext, AntiforgeryToken cookieToken); // Determines whether an existing cookie token is valid (well-formed). @@ -26,8 +25,8 @@ namespace Microsoft.AspNet.Antiforgery // Validates a (cookie, form) token pair. void ValidateTokens( - [NotNull] HttpContext httpContext, - [NotNull] AntiforgeryToken cookieToken, - [NotNull] AntiforgeryToken formToken); + HttpContext httpContext, + AntiforgeryToken cookieToken, + AntiforgeryToken formToken); } } \ No newline at end of file diff --git a/src/Microsoft.AspNet.Antiforgery/IAntiforgeryTokenStore.cs b/src/Microsoft.AspNet.Antiforgery/IAntiforgeryTokenStore.cs index afa43014d6..c600d68e53 100644 --- a/src/Microsoft.AspNet.Antiforgery/IAntiforgeryTokenStore.cs +++ b/src/Microsoft.AspNet.Antiforgery/IAntiforgeryTokenStore.cs @@ -3,14 +3,13 @@ using System.Threading.Tasks; using Microsoft.AspNet.Http; -using Microsoft.Framework.Internal; namespace Microsoft.AspNet.Antiforgery { // Provides an abstraction around how tokens are persisted and retrieved for a request public interface IAntiforgeryTokenStore { - AntiforgeryToken GetCookieToken([NotNull] HttpContext httpContext); + AntiforgeryToken GetCookieToken(HttpContext httpContext); /// /// Gets the cookie and form tokens from the request. Will throw an exception if either token is @@ -18,8 +17,8 @@ namespace Microsoft.AspNet.Antiforgery /// /// The for the current request. /// The . - Task GetRequestTokensAsync([NotNull] HttpContext httpContext); + Task GetRequestTokensAsync(HttpContext httpContext); - void SaveCookieToken([NotNull] HttpContext httpContext, [NotNull] AntiforgeryToken token); + void SaveCookieToken(HttpContext httpContext, AntiforgeryToken token); } } \ No newline at end of file diff --git a/src/Microsoft.AspNet.Antiforgery/ServiceCollectionExtensions.cs b/src/Microsoft.AspNet.Antiforgery/ServiceCollectionExtensions.cs index 297a76a36d..e33c314b6c 100644 --- a/src/Microsoft.AspNet.Antiforgery/ServiceCollectionExtensions.cs +++ b/src/Microsoft.AspNet.Antiforgery/ServiceCollectionExtensions.cs @@ -1,18 +1,22 @@ -// Copyright (c) .NET Foundation. All rights reserved. +// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using Microsoft.AspNet.Antiforgery; using Microsoft.Framework.DependencyInjection.Extensions; -using Microsoft.Framework.Internal; using Microsoft.Framework.OptionsModel; namespace Microsoft.Framework.DependencyInjection { public static class ServiceCollectionExtensions { - public static IServiceCollection AddAntiforgery([NotNull] this IServiceCollection services) + public static IServiceCollection AddAntiforgery(this IServiceCollection services) { + if (services == null) + { + throw new ArgumentNullException(nameof(services)); + } + services.AddDataProtection(); services.AddWebEncoders(); @@ -31,9 +35,19 @@ namespace Microsoft.Framework.DependencyInjection } public static IServiceCollection ConfigureAntiforgery( - [NotNull] this IServiceCollection services, - [NotNull] Action setupAction) + this IServiceCollection services, + Action setupAction) { + if (services == null) + { + throw new ArgumentNullException(nameof(services)); + } + + if (setupAction == null) + { + throw new ArgumentNullException(nameof(setupAction)); + } + services.Configure(setupAction); return services; } diff --git a/src/Microsoft.AspNet.Antiforgery/project.json b/src/Microsoft.AspNet.Antiforgery/project.json index c5de78d2a6..4bc77d47bd 100644 --- a/src/Microsoft.AspNet.Antiforgery/project.json +++ b/src/Microsoft.AspNet.Antiforgery/project.json @@ -10,7 +10,6 @@ "Microsoft.AspNet.Http.Abstractions": "1.0.0-*", "Microsoft.AspNet.WebUtilities": "1.0.0-*", "Microsoft.Framework.DependencyInjection.Abstractions": "1.0.0-*", - "Microsoft.Framework.NotNullAttribute.Sources": { "type": "build", "version": "1.0.0-*" }, "Microsoft.Framework.OptionsModel": "1.0.0-*", "Microsoft.Framework.WebEncoders": "1.0.0-*" }, diff --git a/test/Microsoft.AspNet.Antiforgery.Test/DefaultAntiforgeryTokenStoreTest.cs b/test/Microsoft.AspNet.Antiforgery.Test/DefaultAntiforgeryTokenStoreTest.cs index 8e73c9d69e..98f56039e2 100644 --- a/test/Microsoft.AspNet.Antiforgery.Test/DefaultAntiforgeryTokenStoreTest.cs +++ b/test/Microsoft.AspNet.Antiforgery.Test/DefaultAntiforgeryTokenStoreTest.cs @@ -5,6 +5,7 @@ using System; using System.Collections.Generic; using System.Threading.Tasks; +using Microsoft.AspNet.DataProtection; using Microsoft.AspNet.Http; using Microsoft.AspNet.Http.Internal; using Microsoft.Framework.DependencyInjection; @@ -40,7 +41,7 @@ namespace Microsoft.AspNet.Antiforgery var tokenStore = new DefaultAntiforgeryTokenStore( optionsAccessor: new TestOptionsManager(options), - tokenSerializer: null); + tokenSerializer: Mock.Of()); // Act var token = tokenStore.GetCookieToken(mockHttpContext.Object); @@ -75,7 +76,7 @@ namespace Microsoft.AspNet.Antiforgery var tokenStore = new DefaultAntiforgeryTokenStore( optionsAccessor: new TestOptionsManager(options), - tokenSerializer: null); + tokenSerializer: Mock.Of()); // Act var token = tokenStore.GetCookieToken(mockHttpContext.Object); @@ -97,7 +98,7 @@ namespace Microsoft.AspNet.Antiforgery var tokenStore = new DefaultAntiforgeryTokenStore( optionsAccessor: new TestOptionsManager(options), - tokenSerializer: null); + tokenSerializer: Mock.Of()); // Act var token = tokenStore.GetCookieToken(mockHttpContext); @@ -176,7 +177,7 @@ namespace Microsoft.AspNet.Antiforgery var tokenStore = new DefaultAntiforgeryTokenStore( optionsAccessor: new TestOptionsManager(options), - tokenSerializer: null); + tokenSerializer: Mock.Of()); // Act var exception = await Assert.ThrowsAsync( @@ -208,7 +209,7 @@ namespace Microsoft.AspNet.Antiforgery var tokenStore = new DefaultAntiforgeryTokenStore( optionsAccessor: new TestOptionsManager(options), - tokenSerializer: null); + tokenSerializer: new DefaultAntiforgeryTokenSerializer(new EphemeralDataProtectionProvider())); // Act var exception = await Assert.ThrowsAsync( @@ -238,7 +239,7 @@ namespace Microsoft.AspNet.Antiforgery var tokenStore = new DefaultAntiforgeryTokenStore( optionsAccessor: new TestOptionsManager(options), - tokenSerializer: null); + tokenSerializer: Mock.Of()); // Act var exception = await Assert.ThrowsAsync( @@ -271,7 +272,7 @@ namespace Microsoft.AspNet.Antiforgery var tokenStore = new DefaultAntiforgeryTokenStore( optionsAccessor: new TestOptionsManager(options), - tokenSerializer: null); + tokenSerializer: Mock.Of()); // Act var tokens = await tokenStore.GetRequestTokensAsync(httpContext); From 5392f41746f0af6ffec8ef6940ea887503c7ab87 Mon Sep 17 00:00:00 2001 From: "N. Taylor Mullen" Date: Thu, 17 Sep 2015 18:33:14 -0700 Subject: [PATCH 033/296] Update nuget.exe and corresponding feeds to v3. --- NuGet.Config => NuGet.config | 4 ++-- build.cmd | 11 ++++++----- build.sh | 13 ++++++++----- 3 files changed, 16 insertions(+), 12 deletions(-) rename NuGet.Config => NuGet.config (75%) diff --git a/NuGet.Config b/NuGet.config similarity index 75% rename from NuGet.Config rename to NuGet.config index b20b7336fc..52bf414192 100644 --- a/NuGet.Config +++ b/NuGet.config @@ -1,7 +1,7 @@ - + - + diff --git a/build.cmd b/build.cmd index b54d91cf74..177997c42e 100644 --- a/build.cmd +++ b/build.cmd @@ -2,14 +2,15 @@ cd %~dp0 SETLOCAL -SET CACHED_NUGET=%LocalAppData%\NuGet\NuGet.exe +SET NUGET_VERSION=latest +SET CACHED_NUGET=%LocalAppData%\NuGet\nuget.%NUGET_VERSION%.exe SET BUILDCMD_KOREBUILD_VERSION="" SET BUILDCMD_DNX_VERSION="" IF EXIST %CACHED_NUGET% goto copynuget echo Downloading latest version of NuGet.exe... IF NOT EXIST %LocalAppData%\NuGet md %LocalAppData%\NuGet -@powershell -NoProfile -ExecutionPolicy unrestricted -Command "$ProgressPreference = 'SilentlyContinue'; Invoke-WebRequest 'https://www.nuget.org/nuget.exe' -OutFile '%CACHED_NUGET%'" +@powershell -NoProfile -ExecutionPolicy unrestricted -Command "$ProgressPreference = 'SilentlyContinue'; Invoke-WebRequest 'https://dist.nuget.org/win-x86-commandline/%NUGET_VERSION%/nuget.exe' -OutFile '%CACHED_NUGET%'" :copynuget IF EXIST .nuget\nuget.exe goto restore @@ -19,11 +20,11 @@ copy %CACHED_NUGET% .nuget\nuget.exe > nul :restore IF EXIST packages\KoreBuild goto run IF %BUILDCMD_KOREBUILD_VERSION%=="" ( - .nuget\NuGet.exe install KoreBuild -ExcludeVersion -o packages -nocache -pre + .nuget\nuget.exe install KoreBuild -ExcludeVersion -o packages -nocache -pre ) ELSE ( - .nuget\NuGet.exe install KoreBuild -version %BUILDCMD_KOREBUILD_VERSION% -ExcludeVersion -o packages -nocache -pre + .nuget\nuget.exe install KoreBuild -version %BUILDCMD_KOREBUILD_VERSION% -ExcludeVersion -o packages -nocache -pre ) -.nuget\NuGet.exe install Sake -ExcludeVersion -Source https://www.nuget.org/api/v2/ -Out packages +.nuget\nuget.exe install Sake -ExcludeVersion -Out packages IF "%SKIP_DNX_INSTALL%"=="1" goto run IF %BUILDCMD_DNX_VERSION%=="" ( diff --git a/build.sh b/build.sh index fd756bc44b..0c66139817 100755 --- a/build.sh +++ b/build.sh @@ -10,21 +10,23 @@ else fi fi mkdir -p $cachedir +nugetVersion=latest +cachePath=$cachedir/nuget.$nugetVersion.exe -url=https://www.nuget.org/nuget.exe +url=https://dist.nuget.org/win-x86-commandline/$nugetVersion/nuget.exe -if test ! -f $cachedir/nuget.exe; then - wget -O $cachedir/nuget.exe $url 2>/dev/null || curl -o $cachedir/nuget.exe --location $url /dev/null +if test ! -f $cachePath; then + wget -O $cachePath $url 2>/dev/null || curl -o $cachePath --location $url /dev/null fi if test ! -e .nuget; then mkdir .nuget - cp $cachedir/nuget.exe .nuget/nuget.exe + cp $cachePath .nuget/nuget.exe fi if test ! -d packages/KoreBuild; then mono .nuget/nuget.exe install KoreBuild -ExcludeVersion -o packages -nocache -pre - mono .nuget/nuget.exe install Sake -ExcludeVersion -Source https://www.nuget.org/api/v2/ -Out packages + mono .nuget/nuget.exe install Sake -ExcludeVersion -Out packages fi if ! type dnvm > /dev/null 2>&1; then @@ -36,3 +38,4 @@ if ! type dnx > /dev/null 2>&1; then fi mono packages/Sake/tools/Sake.exe -I packages/KoreBuild/build -f makefile.shade "$@" + From 90539dc489aa837bbca33d218db8a26be50fe55f Mon Sep 17 00:00:00 2001 From: Ajay Bhargav Baaskaran Date: Tue, 22 Sep 2015 15:33:36 -0700 Subject: [PATCH 034/296] Enabling NuGetPackageVerifier --- NuGetPackageVerifier.json | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 NuGetPackageVerifier.json diff --git a/NuGetPackageVerifier.json b/NuGetPackageVerifier.json new file mode 100644 index 0000000000..5627d30493 --- /dev/null +++ b/NuGetPackageVerifier.json @@ -0,0 +1,25 @@ +{ + "adx": { // Packages written by the ADX team and that ship on NuGet.org + "rules": [ + "AssemblyHasDocumentFileRule", + "AssemblyHasVersionAttributesRule", + "AssemblyHasServicingAttributeRule", + "AssemblyHasNeutralResourcesLanguageAttributeRule", + "SatellitePackageRule", + "StrictSemanticVersionValidationRule" + ], + "packages": { + "Microsoft.AspNet.Antiforgery": { } + } + }, + "Default": { // Rules to run for packages not listed in any other set. + "rules": [ + "AssemblyHasDocumentFileRule", + "AssemblyHasVersionAttributesRule", + "AssemblyHasServicingAttributeRule", + "AssemblyHasNeutralResourcesLanguageAttributeRule", + "SatellitePackageRule", + "StrictSemanticVersionValidationRule" + ] + } +} \ No newline at end of file From c5a16b3a5110e2811e836e85005547a49bc07d42 Mon Sep 17 00:00:00 2001 From: Pranav K Date: Mon, 28 Sep 2015 23:15:43 -0700 Subject: [PATCH 035/296] Updating to release NuGet.config. --- NuGet.config | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/NuGet.config b/NuGet.config index 52bf414192..71b9724a09 100644 --- a/NuGet.config +++ b/NuGet.config @@ -1,7 +1,7 @@ - + From c555131eaa703cddc9f3efc0f5400ce84c3d6746 Mon Sep 17 00:00:00 2001 From: "N. Taylor Mullen" Date: Thu, 1 Oct 2015 11:58:29 -0700 Subject: [PATCH 036/296] Update 'build.cmd' alias parameter to use full name. --- build.cmd | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/build.cmd b/build.cmd index 177997c42e..70d974a61f 100644 --- a/build.cmd +++ b/build.cmd @@ -30,7 +30,7 @@ IF "%SKIP_DNX_INSTALL%"=="1" goto run IF %BUILDCMD_DNX_VERSION%=="" ( CALL packages\KoreBuild\build\dnvm upgrade -runtime CLR -arch x86 ) ELSE ( - CALL packages\KoreBuild\build\dnvm install %BUILDCMD_DNX_VERSION% -runtime CLR -arch x86 -a default + CALL packages\KoreBuild\build\dnvm install %BUILDCMD_DNX_VERSION% -runtime CLR -arch x86 -alias default ) CALL packages\KoreBuild\build\dnvm install default -runtime CoreCLR -arch x86 From 7a0068ede29d07960af8f808f733467d91cd45ac Mon Sep 17 00:00:00 2001 From: Pranav K Date: Sat, 3 Oct 2015 15:44:46 -0700 Subject: [PATCH 037/296] Renaming Microsoft.Framework.* -> Microsoft.Extensions.* --- samples/AntiforgerySample/FormPostSampleMiddleware.cs | 4 ++-- samples/AntiforgerySample/Startup.cs | 4 ++-- src/Microsoft.AspNet.Antiforgery/AntiforgeryOptionsSetup.cs | 4 ++-- src/Microsoft.AspNet.Antiforgery/DefaultAntiforgery.cs | 4 ++-- .../DefaultAntiforgeryTokenStore.cs | 4 ++-- .../ServiceCollectionExtensions.cs | 6 +++--- src/Microsoft.AspNet.Antiforgery/project.json | 6 +++--- .../AntiforgeryOptionsSetupTest.cs | 6 +++--- .../DefaultAntiforgeryTest.cs | 4 ++-- .../DefaultAntiforgeryTokenStoreTest.cs | 4 ++-- .../Microsoft.AspNet.Antiforgery.Test/TestOptionsManager.cs | 4 ++-- test/Microsoft.AspNet.Antiforgery.Test/project.json | 6 +++--- 12 files changed, 28 insertions(+), 28 deletions(-) diff --git a/samples/AntiforgerySample/FormPostSampleMiddleware.cs b/samples/AntiforgerySample/FormPostSampleMiddleware.cs index 494e84a0b5..aa9b41a872 100644 --- a/samples/AntiforgerySample/FormPostSampleMiddleware.cs +++ b/samples/AntiforgerySample/FormPostSampleMiddleware.cs @@ -1,11 +1,11 @@ -// Copyright (c) .NET Foundation. All rights reserved. +// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Threading.Tasks; using Microsoft.AspNet.Antiforgery; using Microsoft.AspNet.Builder; using Microsoft.AspNet.Http; -using Microsoft.Framework.OptionsModel; +using Microsoft.Extensions.OptionsModel; namespace AntiforgerySample { diff --git a/samples/AntiforgerySample/Startup.cs b/samples/AntiforgerySample/Startup.cs index dadb75b86f..6fef43186c 100644 --- a/samples/AntiforgerySample/Startup.cs +++ b/samples/AntiforgerySample/Startup.cs @@ -1,8 +1,8 @@ -// Copyright (c) .NET Foundation. All rights reserved. +// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using Microsoft.AspNet.Builder; -using Microsoft.Framework.DependencyInjection; +using Microsoft.Extensions.DependencyInjection; namespace AntiforgerySample { diff --git a/src/Microsoft.AspNet.Antiforgery/AntiforgeryOptionsSetup.cs b/src/Microsoft.AspNet.Antiforgery/AntiforgeryOptionsSetup.cs index f37c3e9b2d..58b38be7a6 100644 --- a/src/Microsoft.AspNet.Antiforgery/AntiforgeryOptionsSetup.cs +++ b/src/Microsoft.AspNet.Antiforgery/AntiforgeryOptionsSetup.cs @@ -1,4 +1,4 @@ -// Copyright (c) .NET Foundation. All rights reserved. +// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Linq; @@ -6,7 +6,7 @@ using System.Security.Cryptography; using System.Text; using Microsoft.AspNet.DataProtection; using Microsoft.AspNet.WebUtilities; -using Microsoft.Framework.OptionsModel; +using Microsoft.Extensions.OptionsModel; namespace Microsoft.AspNet.Antiforgery { diff --git a/src/Microsoft.AspNet.Antiforgery/DefaultAntiforgery.cs b/src/Microsoft.AspNet.Antiforgery/DefaultAntiforgery.cs index c2c66444ce..e1eb7a10eb 100644 --- a/src/Microsoft.AspNet.Antiforgery/DefaultAntiforgery.cs +++ b/src/Microsoft.AspNet.Antiforgery/DefaultAntiforgery.cs @@ -5,8 +5,8 @@ using System; using System.Diagnostics; using System.Threading.Tasks; using Microsoft.AspNet.Http; -using Microsoft.Framework.OptionsModel; -using Microsoft.Framework.WebEncoders; +using Microsoft.Extensions.OptionsModel; +using Microsoft.Extensions.WebEncoders; namespace Microsoft.AspNet.Antiforgery { diff --git a/src/Microsoft.AspNet.Antiforgery/DefaultAntiforgeryTokenStore.cs b/src/Microsoft.AspNet.Antiforgery/DefaultAntiforgeryTokenStore.cs index 0e67c14827..29a50483ce 100644 --- a/src/Microsoft.AspNet.Antiforgery/DefaultAntiforgeryTokenStore.cs +++ b/src/Microsoft.AspNet.Antiforgery/DefaultAntiforgeryTokenStore.cs @@ -5,8 +5,8 @@ using System; using System.Diagnostics; using System.Threading.Tasks; using Microsoft.AspNet.Http; -using Microsoft.Framework.DependencyInjection; -using Microsoft.Framework.OptionsModel; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.OptionsModel; namespace Microsoft.AspNet.Antiforgery { diff --git a/src/Microsoft.AspNet.Antiforgery/ServiceCollectionExtensions.cs b/src/Microsoft.AspNet.Antiforgery/ServiceCollectionExtensions.cs index e33c314b6c..e78899c7ba 100644 --- a/src/Microsoft.AspNet.Antiforgery/ServiceCollectionExtensions.cs +++ b/src/Microsoft.AspNet.Antiforgery/ServiceCollectionExtensions.cs @@ -3,10 +3,10 @@ using System; using Microsoft.AspNet.Antiforgery; -using Microsoft.Framework.DependencyInjection.Extensions; -using Microsoft.Framework.OptionsModel; +using Microsoft.Extensions.DependencyInjection.Extensions; +using Microsoft.Extensions.OptionsModel; -namespace Microsoft.Framework.DependencyInjection +namespace Microsoft.Extensions.DependencyInjection { public static class ServiceCollectionExtensions { diff --git a/src/Microsoft.AspNet.Antiforgery/project.json b/src/Microsoft.AspNet.Antiforgery/project.json index 4bc77d47bd..51c2e51048 100644 --- a/src/Microsoft.AspNet.Antiforgery/project.json +++ b/src/Microsoft.AspNet.Antiforgery/project.json @@ -9,9 +9,9 @@ "Microsoft.AspNet.DataProtection": "1.0.0-*", "Microsoft.AspNet.Http.Abstractions": "1.0.0-*", "Microsoft.AspNet.WebUtilities": "1.0.0-*", - "Microsoft.Framework.DependencyInjection.Abstractions": "1.0.0-*", - "Microsoft.Framework.OptionsModel": "1.0.0-*", - "Microsoft.Framework.WebEncoders": "1.0.0-*" + "Microsoft.Extensions.DependencyInjection.Abstractions": "1.0.0-*", + "Microsoft.Extensions.OptionsModel": "1.0.0-*", + "Microsoft.Extensions.WebEncoders": "1.0.0-*" }, "frameworks" : { diff --git a/test/Microsoft.AspNet.Antiforgery.Test/AntiforgeryOptionsSetupTest.cs b/test/Microsoft.AspNet.Antiforgery.Test/AntiforgeryOptionsSetupTest.cs index 946a0812e6..3966090c1e 100644 --- a/test/Microsoft.AspNet.Antiforgery.Test/AntiforgeryOptionsSetupTest.cs +++ b/test/Microsoft.AspNet.Antiforgery.Test/AntiforgeryOptionsSetupTest.cs @@ -1,8 +1,8 @@ -// Copyright (c) .NET Foundation. All rights reserved. +// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. -using Microsoft.Framework.DependencyInjection; -using Microsoft.Framework.OptionsModel; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.OptionsModel; using Xunit; namespace Microsoft.AspNet.Antiforgery diff --git a/test/Microsoft.AspNet.Antiforgery.Test/DefaultAntiforgeryTest.cs b/test/Microsoft.AspNet.Antiforgery.Test/DefaultAntiforgeryTest.cs index 912bc015cc..112b1fc629 100644 --- a/test/Microsoft.AspNet.Antiforgery.Test/DefaultAntiforgeryTest.cs +++ b/test/Microsoft.AspNet.Antiforgery.Test/DefaultAntiforgeryTest.cs @@ -6,8 +6,8 @@ using System.Security.Claims; using System.Threading.Tasks; using Microsoft.AspNet.Http; using Microsoft.AspNet.Http.Internal; -using Microsoft.Framework.OptionsModel; -using Microsoft.Framework.WebEncoders.Testing; +using Microsoft.Extensions.OptionsModel; +using Microsoft.Extensions.WebEncoders.Testing; #if DNX451 using Moq; #endif diff --git a/test/Microsoft.AspNet.Antiforgery.Test/DefaultAntiforgeryTokenStoreTest.cs b/test/Microsoft.AspNet.Antiforgery.Test/DefaultAntiforgeryTokenStoreTest.cs index 98f56039e2..3b546e99d9 100644 --- a/test/Microsoft.AspNet.Antiforgery.Test/DefaultAntiforgeryTokenStoreTest.cs +++ b/test/Microsoft.AspNet.Antiforgery.Test/DefaultAntiforgeryTokenStoreTest.cs @@ -8,8 +8,8 @@ using System.Threading.Tasks; using Microsoft.AspNet.DataProtection; using Microsoft.AspNet.Http; using Microsoft.AspNet.Http.Internal; -using Microsoft.Framework.DependencyInjection; -using Microsoft.Framework.Primitives; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Primitives; using Moq; using Xunit; diff --git a/test/Microsoft.AspNet.Antiforgery.Test/TestOptionsManager.cs b/test/Microsoft.AspNet.Antiforgery.Test/TestOptionsManager.cs index e1c1c5cbcc..830d3a7913 100644 --- a/test/Microsoft.AspNet.Antiforgery.Test/TestOptionsManager.cs +++ b/test/Microsoft.AspNet.Antiforgery.Test/TestOptionsManager.cs @@ -1,8 +1,8 @@ -// Copyright (c) .NET Foundation. All rights reserved. +// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; -using Microsoft.Framework.OptionsModel; +using Microsoft.Extensions.OptionsModel; namespace Microsoft.AspNet.Antiforgery { diff --git a/test/Microsoft.AspNet.Antiforgery.Test/project.json b/test/Microsoft.AspNet.Antiforgery.Test/project.json index ce82ef7f25..e3a04e2114 100644 --- a/test/Microsoft.AspNet.Antiforgery.Test/project.json +++ b/test/Microsoft.AspNet.Antiforgery.Test/project.json @@ -1,9 +1,9 @@ -{ +{ "dependencies": { "Microsoft.AspNet.Antiforgery": "1.0.0-*", "Microsoft.AspNet.Http": "1.0.0-*", - "Microsoft.Framework.DependencyInjection": "1.0.0-*", - "Microsoft.Framework.WebEncoders.Testing": "1.0.0-*", + "Microsoft.Extensions.DependencyInjection": "1.0.0-*", + "Microsoft.Extensions.WebEncoders.Testing": "1.0.0-*", "xunit.runner.aspnet": "2.0.0-aspnet-*" }, "commands": { From c0517a2815cca72d9474f1d755d1bebd12351429 Mon Sep 17 00:00:00 2001 From: Doug Bunting Date: Thu, 8 Oct 2015 19:00:27 -0700 Subject: [PATCH 038/296] React to aspnet/Universe#290 fix --- build.cmd | 25 +++++++++++++------------ build.sh | 12 +++++++----- 2 files changed, 20 insertions(+), 17 deletions(-) diff --git a/build.cmd b/build.cmd index 70d974a61f..84dc87e480 100644 --- a/build.cmd +++ b/build.cmd @@ -18,22 +18,23 @@ md .nuget copy %CACHED_NUGET% .nuget\nuget.exe > nul :restore -IF EXIST packages\KoreBuild goto run +IF EXIST packages\Sake goto getdnx IF %BUILDCMD_KOREBUILD_VERSION%=="" ( - .nuget\nuget.exe install KoreBuild -ExcludeVersion -o packages -nocache -pre + .nuget\nuget.exe install KoreBuild -ExcludeVersion -o packages -nocache -pre ) ELSE ( - .nuget\nuget.exe install KoreBuild -version %BUILDCMD_KOREBUILD_VERSION% -ExcludeVersion -o packages -nocache -pre + .nuget\nuget.exe install KoreBuild -version %BUILDCMD_KOREBUILD_VERSION% -ExcludeVersion -o packages -nocache -pre ) -.nuget\nuget.exe install Sake -ExcludeVersion -Out packages +.nuget\NuGet.exe install Sake -ExcludeVersion -Source https://www.nuget.org/api/v2/ -Out packages -IF "%SKIP_DNX_INSTALL%"=="1" goto run -IF %BUILDCMD_DNX_VERSION%=="" ( - CALL packages\KoreBuild\build\dnvm upgrade -runtime CLR -arch x86 +:getdnx +IF "%SKIP_DNX_INSTALL%"=="" ( + IF "%BUILDCMD_DNX_VERSION%"=="" ( + BUILDCMD_DNX_VERSION=latest + ) + CALL packages\KoreBuild\build\dnvm install %BUILDCMD_DNX_VERSION% -runtime CoreCLR -arch x86 -alias default + CALL packages\KoreBuild\build\dnvm install default -runtime CLR -arch x86 -alias default ) ELSE ( - CALL packages\KoreBuild\build\dnvm install %BUILDCMD_DNX_VERSION% -runtime CLR -arch x86 -alias default + CALL packages\KoreBuild\build\dnvm use default -runtime CLR -arch x86 ) -CALL packages\KoreBuild\build\dnvm install default -runtime CoreCLR -arch x86 -:run -CALL packages\KoreBuild\build\dnvm use default -runtime CLR -arch x86 -packages\Sake\tools\Sake.exe -I packages\KoreBuild\build -f makefile.shade %* \ No newline at end of file +packages\Sake\tools\Sake.exe -I packages\KoreBuild\build -f makefile.shade %* diff --git a/build.sh b/build.sh index 0c66139817..da4e3fcd1c 100755 --- a/build.sh +++ b/build.sh @@ -24,18 +24,20 @@ if test ! -e .nuget; then cp $cachePath .nuget/nuget.exe fi -if test ! -d packages/KoreBuild; then +if test ! -d packages/Sake; then mono .nuget/nuget.exe install KoreBuild -ExcludeVersion -o packages -nocache -pre - mono .nuget/nuget.exe install Sake -ExcludeVersion -Out packages + mono .nuget/nuget.exe install Sake -ExcludeVersion -Source https://www.nuget.org/api/v2/ -Out packages fi if ! type dnvm > /dev/null 2>&1; then source packages/KoreBuild/build/dnvm.sh fi -if ! type dnx > /dev/null 2>&1; then - dnvm upgrade +if ! type dnx > /dev/null 2>&1 || [ -z "$SKIP_DNX_INSTALL" ]; then + dnvm install latest -runtime coreclr -alias default + dnvm install default -runtime mono -alias default +else + dnvm use default -runtime mono fi mono packages/Sake/tools/Sake.exe -I packages/KoreBuild/build -f makefile.shade "$@" - From e925bb1b3abc2dccae05ca2a57da1f5b782b0e21 Mon Sep 17 00:00:00 2001 From: Doug Bunting Date: Mon, 12 Oct 2015 12:47:15 -0700 Subject: [PATCH 039/296] Fix local build break --- build.cmd | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/build.cmd b/build.cmd index 84dc87e480..553e3929a0 100644 --- a/build.cmd +++ b/build.cmd @@ -4,8 +4,8 @@ cd %~dp0 SETLOCAL SET NUGET_VERSION=latest SET CACHED_NUGET=%LocalAppData%\NuGet\nuget.%NUGET_VERSION%.exe -SET BUILDCMD_KOREBUILD_VERSION="" -SET BUILDCMD_DNX_VERSION="" +SET BUILDCMD_KOREBUILD_VERSION= +SET BUILDCMD_DNX_VERSION= IF EXIST %CACHED_NUGET% goto copynuget echo Downloading latest version of NuGet.exe... @@ -19,7 +19,7 @@ copy %CACHED_NUGET% .nuget\nuget.exe > nul :restore IF EXIST packages\Sake goto getdnx -IF %BUILDCMD_KOREBUILD_VERSION%=="" ( +IF "%BUILDCMD_KOREBUILD_VERSION%"=="" ( .nuget\nuget.exe install KoreBuild -ExcludeVersion -o packages -nocache -pre ) ELSE ( .nuget\nuget.exe install KoreBuild -version %BUILDCMD_KOREBUILD_VERSION% -ExcludeVersion -o packages -nocache -pre @@ -27,10 +27,10 @@ IF %BUILDCMD_KOREBUILD_VERSION%=="" ( .nuget\NuGet.exe install Sake -ExcludeVersion -Source https://www.nuget.org/api/v2/ -Out packages :getdnx +IF "%BUILDCMD_DNX_VERSION%"=="" ( + SET BUILDCMD_DNX_VERSION=latest +) IF "%SKIP_DNX_INSTALL%"=="" ( - IF "%BUILDCMD_DNX_VERSION%"=="" ( - BUILDCMD_DNX_VERSION=latest - ) CALL packages\KoreBuild\build\dnvm install %BUILDCMD_DNX_VERSION% -runtime CoreCLR -arch x86 -alias default CALL packages\KoreBuild\build\dnvm install default -runtime CLR -arch x86 -alias default ) ELSE ( From c7dc5ab7f024f9197f3457dac553433901e74716 Mon Sep 17 00:00:00 2001 From: Pranav K Date: Thu, 22 Oct 2015 00:23:06 -0700 Subject: [PATCH 040/296] Switching to generations TFMs --- src/Microsoft.AspNet.Antiforgery/project.json | 37 +++++++++---------- 1 file changed, 18 insertions(+), 19 deletions(-) diff --git a/src/Microsoft.AspNet.Antiforgery/project.json b/src/Microsoft.AspNet.Antiforgery/project.json index 51c2e51048..593788b3f5 100644 --- a/src/Microsoft.AspNet.Antiforgery/project.json +++ b/src/Microsoft.AspNet.Antiforgery/project.json @@ -1,21 +1,20 @@ { - "description": "An antiforgery system for ASP.NET designed to generate and validate tokens to prevent Cross-Site Request Forgery attacks.", - "version": "1.0.0-*", - "repository": { - "type": "git", - "url": "git://github.com/aspnet/antiforgery" - }, - "dependencies": { - "Microsoft.AspNet.DataProtection": "1.0.0-*", - "Microsoft.AspNet.Http.Abstractions": "1.0.0-*", - "Microsoft.AspNet.WebUtilities": "1.0.0-*", - "Microsoft.Extensions.DependencyInjection.Abstractions": "1.0.0-*", - "Microsoft.Extensions.OptionsModel": "1.0.0-*", - "Microsoft.Extensions.WebEncoders": "1.0.0-*" - }, - - "frameworks" : { - "dnx451": { }, - "dnxcore50" : { } + "description": "An antiforgery system for ASP.NET designed to generate and validate tokens to prevent Cross-Site Request Forgery attacks.", + "version": "1.0.0-*", + "repository": { + "type": "git", + "url": "git://github.com/aspnet/antiforgery" + }, + "dependencies": { + "Microsoft.AspNet.DataProtection": "1.0.0-*", + "Microsoft.AspNet.Http.Abstractions": "1.0.0-*", + "Microsoft.AspNet.WebUtilities": "1.0.0-*", + "Microsoft.Extensions.DependencyInjection.Abstractions": "1.0.0-*", + "Microsoft.Extensions.OptionsModel": "1.0.0-*", + "Microsoft.Extensions.WebEncoders": "1.0.0-*" + }, + "frameworks": { + "net451": {}, + "dotnet5.4": {} } -} +} \ No newline at end of file From e49daaa980eacd795a7edb973ded5d24c49dd7ed Mon Sep 17 00:00:00 2001 From: Pranav K Date: Wed, 28 Oct 2015 12:43:08 -0700 Subject: [PATCH 041/296] Updating to release NuGet.config. --- NuGet.config | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/NuGet.config b/NuGet.config index 52bf414192..71b9724a09 100644 --- a/NuGet.config +++ b/NuGet.config @@ -1,7 +1,7 @@ - + From 84cfe5640d5b554bf390c54e1f6369d623ef8895 Mon Sep 17 00:00:00 2001 From: Chris R Date: Fri, 30 Oct 2015 11:45:48 -0700 Subject: [PATCH 042/296] React to WebEncoders changes. --- .../DefaultAntiforgery.cs | 12 ++++++------ src/Microsoft.AspNet.Antiforgery/project.json | 2 -- .../DefaultAntiforgeryTest.cs | 2 +- test/Microsoft.AspNet.Antiforgery.Test/project.json | 1 - 4 files changed, 7 insertions(+), 10 deletions(-) diff --git a/src/Microsoft.AspNet.Antiforgery/DefaultAntiforgery.cs b/src/Microsoft.AspNet.Antiforgery/DefaultAntiforgery.cs index e1eb7a10eb..98f6e49f84 100644 --- a/src/Microsoft.AspNet.Antiforgery/DefaultAntiforgery.cs +++ b/src/Microsoft.AspNet.Antiforgery/DefaultAntiforgery.cs @@ -3,10 +3,10 @@ using System; using System.Diagnostics; +using System.Text.Encodings.Web; using System.Threading.Tasks; using Microsoft.AspNet.Http; using Microsoft.Extensions.OptionsModel; -using Microsoft.Extensions.WebEncoders; namespace Microsoft.AspNet.Antiforgery { @@ -16,7 +16,7 @@ namespace Microsoft.AspNet.Antiforgery /// public class DefaultAntiforgery : IAntiforgery { - private readonly IHtmlEncoder _htmlEncoder; + private readonly HtmlEncoder _htmlEncoder; private readonly AntiforgeryOptions _options; private readonly IAntiforgeryTokenGenerator _tokenGenerator; private readonly IAntiforgeryTokenSerializer _tokenSerializer; @@ -27,7 +27,7 @@ namespace Microsoft.AspNet.Antiforgery IAntiforgeryTokenGenerator tokenGenerator, IAntiforgeryTokenSerializer tokenSerializer, IAntiforgeryTokenStore tokenStore, - IHtmlEncoder htmlEncoder) + HtmlEncoder htmlEncoder) { _options = antiforgeryOptionsAccessor.Value; _tokenGenerator = tokenGenerator; @@ -50,9 +50,9 @@ namespace Microsoft.AspNet.Antiforgery var inputTag = string.Format( "", - _htmlEncoder.HtmlEncode(_options.FormFieldName), - _htmlEncoder.HtmlEncode("hidden"), - _htmlEncoder.HtmlEncode(tokenSet.FormToken)); + _htmlEncoder.Encode(_options.FormFieldName), + _htmlEncoder.Encode("hidden"), + _htmlEncoder.Encode(tokenSet.FormToken)); return inputTag; } diff --git a/src/Microsoft.AspNet.Antiforgery/project.json b/src/Microsoft.AspNet.Antiforgery/project.json index 593788b3f5..882a5e760e 100644 --- a/src/Microsoft.AspNet.Antiforgery/project.json +++ b/src/Microsoft.AspNet.Antiforgery/project.json @@ -9,8 +9,6 @@ "Microsoft.AspNet.DataProtection": "1.0.0-*", "Microsoft.AspNet.Http.Abstractions": "1.0.0-*", "Microsoft.AspNet.WebUtilities": "1.0.0-*", - "Microsoft.Extensions.DependencyInjection.Abstractions": "1.0.0-*", - "Microsoft.Extensions.OptionsModel": "1.0.0-*", "Microsoft.Extensions.WebEncoders": "1.0.0-*" }, "frameworks": { diff --git a/test/Microsoft.AspNet.Antiforgery.Test/DefaultAntiforgeryTest.cs b/test/Microsoft.AspNet.Antiforgery.Test/DefaultAntiforgeryTest.cs index 112b1fc629..fe3c5387e1 100644 --- a/test/Microsoft.AspNet.Antiforgery.Test/DefaultAntiforgeryTest.cs +++ b/test/Microsoft.AspNet.Antiforgery.Test/DefaultAntiforgeryTest.cs @@ -474,7 +474,7 @@ namespace Microsoft.AspNet.Antiforgery tokenGenerator: tokenGenerator, tokenSerializer: tokenSerializer, tokenStore: tokenStore, - htmlEncoder: new CommonTestEncoder()); + htmlEncoder: new HtmlTestEncoder()); } private HttpContext GetHttpContext() diff --git a/test/Microsoft.AspNet.Antiforgery.Test/project.json b/test/Microsoft.AspNet.Antiforgery.Test/project.json index e3a04e2114..f4fed3ec60 100644 --- a/test/Microsoft.AspNet.Antiforgery.Test/project.json +++ b/test/Microsoft.AspNet.Antiforgery.Test/project.json @@ -3,7 +3,6 @@ "Microsoft.AspNet.Antiforgery": "1.0.0-*", "Microsoft.AspNet.Http": "1.0.0-*", "Microsoft.Extensions.DependencyInjection": "1.0.0-*", - "Microsoft.Extensions.WebEncoders.Testing": "1.0.0-*", "xunit.runner.aspnet": "2.0.0-aspnet-*" }, "commands": { From 7edbabd49816f6a2dc8bb6c7911b68d47375d8df Mon Sep 17 00:00:00 2001 From: Chris R Date: Tue, 3 Nov 2015 10:15:23 -0800 Subject: [PATCH 043/296] React to Http.Abstractions changes. --- .../DefaultAntiforgeryTokenStoreTest.cs | 34 +++++++++++-------- 1 file changed, 19 insertions(+), 15 deletions(-) diff --git a/test/Microsoft.AspNet.Antiforgery.Test/DefaultAntiforgeryTokenStoreTest.cs b/test/Microsoft.AspNet.Antiforgery.Test/DefaultAntiforgeryTokenStoreTest.cs index 3b546e99d9..27d36cd2b6 100644 --- a/test/Microsoft.AspNet.Antiforgery.Test/DefaultAntiforgeryTokenStoreTest.cs +++ b/test/Microsoft.AspNet.Antiforgery.Test/DefaultAntiforgeryTokenStoreTest.cs @@ -23,7 +23,7 @@ namespace Microsoft.AspNet.Antiforgery public void GetCookieToken_CookieDoesNotExist_ReturnsNull() { // Arrange - var requestCookies = new Mock(); + var requestCookies = new Mock(); requestCookies .Setup(o => o[It.IsAny()]) .Returns(string.Empty); @@ -54,7 +54,7 @@ namespace Microsoft.AspNet.Antiforgery public void GetCookieToken_CookieIsMissingInRequest_LooksUpCookieInAntiforgeryContext() { // Arrange - var requestCookies = new Mock(); + var requestCookies = new Mock(); requestCookies .Setup(o => o[It.IsAny()]) .Returns(string.Empty); @@ -167,7 +167,7 @@ namespace Microsoft.AspNet.Antiforgery // Arrange var httpContext = new DefaultHttpContext(); httpContext.Request.Form = new FormCollection(new Dictionary()); - httpContext.Request.Cookies = new ReadableStringCollection(new Dictionary()); + httpContext.Request.Cookies = new RequestCookieCollection(new Dictionary()); var options = new AntiforgeryOptions() { @@ -196,7 +196,7 @@ namespace Microsoft.AspNet.Antiforgery // Will not be accessed httpContext.Request.Form = null; - httpContext.Request.Cookies = new ReadableStringCollection(new Dictionary() + httpContext.Request.Cookies = new RequestCookieCollection(new Dictionary() { { "cookie-name", "cookie-value" }, }); @@ -226,7 +226,7 @@ namespace Microsoft.AspNet.Antiforgery var httpContext = new DefaultHttpContext(); httpContext.Request.ContentType = "application/x-www-form-urlencoded"; httpContext.Request.Form = new FormCollection(new Dictionary()); - httpContext.Request.Cookies = new ReadableStringCollection(new Dictionary() + httpContext.Request.Cookies = new RequestCookieCollection(new Dictionary() { { "cookie-name", "cookie-value" }, }); @@ -259,7 +259,7 @@ namespace Microsoft.AspNet.Antiforgery { { "form-field-name", "form-value" }, }); - httpContext.Request.Cookies = new ReadableStringCollection(new Dictionary() + httpContext.Request.Cookies = new RequestCookieCollection(new Dictionary() { { "cookie-name", "cookie-value" }, }); @@ -385,7 +385,7 @@ namespace Microsoft.AspNet.Antiforgery } } - private class MockCookieCollection : IReadableStringCollection + private class MockCookieCollection : IRequestCookieCollection { private Dictionary _dictionary; @@ -415,22 +415,26 @@ namespace Microsoft.AspNet.Antiforgery return new MockCookieCollection(new Dictionary() { { key, value } }); } - public string Get(string key) - { - return this[key]; - } - public bool ContainsKey(string key) { return _dictionary.ContainsKey(key); } - public StringValues this[string key] + public string this[string key] { - get { return _dictionary[key]; } + get + { + string value; + return _dictionary.TryGetValue(key, out value) ? value : null; + } } - public IEnumerator> GetEnumerator() + public bool TryGetValue(string key, out string value) + { + return _dictionary.TryGetValue(key, out value); + } + + public IEnumerator> GetEnumerator() { throw new NotImplementedException(); } From 391086e3cedab22db68df7c68546ae1b3986530b Mon Sep 17 00:00:00 2001 From: Cesar Blum Silveira Date: Tue, 3 Nov 2015 12:51:41 -0800 Subject: [PATCH 044/296] Strong name Microsoft.AspNet.Antiforgery. --- .../Properties/AssemblyInfo.cs | 4 ++-- src/Microsoft.AspNet.Antiforgery/project.json | 4 ++++ .../project.json | 4 ++++ tools/Key.snk | Bin 0 -> 596 bytes 4 files changed, 10 insertions(+), 2 deletions(-) create mode 100644 tools/Key.snk diff --git a/src/Microsoft.AspNet.Antiforgery/Properties/AssemblyInfo.cs b/src/Microsoft.AspNet.Antiforgery/Properties/AssemblyInfo.cs index 6a761b69c9..20d72d904c 100644 --- a/src/Microsoft.AspNet.Antiforgery/Properties/AssemblyInfo.cs +++ b/src/Microsoft.AspNet.Antiforgery/Properties/AssemblyInfo.cs @@ -5,7 +5,7 @@ using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; -[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")] -[assembly: InternalsVisibleTo("Microsoft.AspNet.Antiforgery.Test")] +[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2, PublicKey=0024000004800000940000000602000000240000525341310004000001000100c547cac37abd99c8db225ef2f6c8a3602f3b3606cc9891605d02baa56104f4cfc0734aa39b93bf7852f7d9266654753cc297e7d2edfe0bac1cdcf9f717241550e0a7b191195b7667bb4f64bcb8e2121380fd1d9d46ad2d92d2d15605093924cceaf74c4861eff62abf69b9291ed0a340e113be11e6a7d3113e92484cf7045cc7")] +[assembly: InternalsVisibleTo("Microsoft.AspNet.Antiforgery.Test, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f33a29044fa9d740c9b3213a93e57c84b472c84e0b8a0e1ae48e67a9f8f6de9d5f7f3d52ac23e48ac51801f1dc950abe901da34d2a9e3baadb141a17c77ef3c565dd5ee5054b91cf63bb3c6ab83f72ab3aafe93d0fc3c2348b764fafb0b1c0733de51459aeab46580384bf9d74c4e28164b7cde247f891ba07891c9d872ad2bb")] [assembly: AssemblyMetadata("Serviceable", "True")] [assembly: NeutralResourcesLanguage("en-us")] diff --git a/src/Microsoft.AspNet.Antiforgery/project.json b/src/Microsoft.AspNet.Antiforgery/project.json index 593788b3f5..1c93addfb0 100644 --- a/src/Microsoft.AspNet.Antiforgery/project.json +++ b/src/Microsoft.AspNet.Antiforgery/project.json @@ -1,6 +1,10 @@ { "description": "An antiforgery system for ASP.NET designed to generate and validate tokens to prevent Cross-Site Request Forgery attacks.", "version": "1.0.0-*", + "compilationOptions": { + "warningsAsErrors": true, + "keyFile": "../../tools/Key.snk" + }, "repository": { "type": "git", "url": "git://github.com/aspnet/antiforgery" diff --git a/test/Microsoft.AspNet.Antiforgery.Test/project.json b/test/Microsoft.AspNet.Antiforgery.Test/project.json index e3a04e2114..9da84be89a 100644 --- a/test/Microsoft.AspNet.Antiforgery.Test/project.json +++ b/test/Microsoft.AspNet.Antiforgery.Test/project.json @@ -1,4 +1,8 @@ { + "compilationOptions": { + "warningsAsErrors": true, + "keyFile": "../../tools/Key.snk" + }, "dependencies": { "Microsoft.AspNet.Antiforgery": "1.0.0-*", "Microsoft.AspNet.Http": "1.0.0-*", diff --git a/tools/Key.snk b/tools/Key.snk new file mode 100644 index 0000000000000000000000000000000000000000..e10e4889c125d3120cd9e81582243d70f7cbb806 GIT binary patch literal 596 zcmV-a0;~N80ssI2Bme+XQ$aES1ONa50098=Iw=HCsnz~#iVhm& zj%TU(_THUee?3yHBjk$37ysB?i5#7WD$={H zV4B!OxRPrb|8)HPg~A}8P>^=#y<)56#=E&NzcjOtPK~<4n6GHt=K$ro*T(lhby_@U zEk(hLzk1H)0yXj{A_5>fk-TgNoP|q6(tP2xo8zt8i%212CWM#AeCd?`hS|4~L({h~Moo(~vy&3Z z1uI}`fd^*>o=rwbAGymj6RM^pZm(*Kfhs+Y1#`-2JPWZMK8@;ZWCk2+9bX4YP);~fj-BU*R zQPvWv$89!{Rl9wM+zR>_TSkn^voYxA?2G iKnV#iZ6Ah`K>b=@=IjYJXrxL124zR(38)nxe+&q_$QXwJ literal 0 HcmV?d00001 From c82ac5e61f893090734c80e36c65562a175a20ef Mon Sep 17 00:00:00 2001 From: ryanbrandenburg Date: Wed, 4 Nov 2015 17:04:11 -0800 Subject: [PATCH 045/296] * Return old cookie token --- .../DefaultAntiforgery.cs | 12 +++-- .../DefaultAntiforgeryTest.cs | 47 ++++++++++++++++++- 2 files changed, 54 insertions(+), 5 deletions(-) diff --git a/src/Microsoft.AspNet.Antiforgery/DefaultAntiforgery.cs b/src/Microsoft.AspNet.Antiforgery/DefaultAntiforgery.cs index 98f6e49f84..a10370c334 100644 --- a/src/Microsoft.AspNet.Antiforgery/DefaultAntiforgery.cs +++ b/src/Microsoft.AspNet.Antiforgery/DefaultAntiforgery.cs @@ -67,7 +67,10 @@ namespace Microsoft.AspNet.Antiforgery CheckSSLConfig(context); var tokenSet = GetTokensInternal(context); - SaveCookieTokenAndHeader(context, tokenSet.CookieToken); + if (tokenSet.IsNewCookieToken) + { + SaveCookieTokenAndHeader(context, tokenSet.CookieToken); + } return Serialize(tokenSet); } @@ -226,8 +229,9 @@ namespace Microsoft.AspNet.Antiforgery return new AntiforgeryTokenSetInternal() { // Note : The new cookie would be null if the old cookie is valid. - CookieToken = newCookieToken, - FormToken = formToken + CookieToken = cookieToken, + FormToken = formToken, + IsNewCookieToken = newCookieToken != null }; } @@ -243,6 +247,8 @@ namespace Microsoft.AspNet.Antiforgery public AntiforgeryToken FormToken { get; set; } public AntiforgeryToken CookieToken { get; set; } + + public bool IsNewCookieToken { get; set; } } } } \ No newline at end of file diff --git a/test/Microsoft.AspNet.Antiforgery.Test/DefaultAntiforgeryTest.cs b/test/Microsoft.AspNet.Antiforgery.Test/DefaultAntiforgeryTest.cs index fe3c5387e1..59c45b919c 100644 --- a/test/Microsoft.AspNet.Antiforgery.Test/DefaultAntiforgeryTest.cs +++ b/test/Microsoft.AspNet.Antiforgery.Test/DefaultAntiforgeryTest.cs @@ -313,10 +313,51 @@ namespace Microsoft.AspNet.Antiforgery var tokenset = antiforgery.GetTokens(context.HttpContext); // Assert - Assert.Null(tokenset.CookieToken); + Assert.Equal("serialized-old-cookie-token", tokenset.CookieToken); Assert.Equal("serialized-form-token", tokenset.FormToken); } + [Fact] + public void GetAndStoreTokens_ExistingValidCookieToken_NotOverriden() + { + // Arrange + var context = CreateMockContext( + new AntiforgeryOptions(), + useOldCookie: true, + isOldCookieValid: true); + var antiforgery = GetAntiforgery(context); + + // Act + var tokenSet = antiforgery.GetAndStoreTokens(context.HttpContext); + + // Assert + // We shouldn't have saved the cookie because it already existed. + context.TokenStore.Verify(t => t.SaveCookieToken(It.IsAny(), It.IsAny()), Times.Never); + + Assert.Equal("serialized-old-cookie-token", tokenSet.CookieToken); + Assert.Equal("serialized-form-token", tokenSet.FormToken); + } + + [Fact] + public void GetAndStoreTokens_NoExistingCookieToken_Saved() + { + // Arrange + var context = CreateMockContext( + new AntiforgeryOptions(), + useOldCookie: false, + isOldCookieValid: false); + var antiforgery = GetAntiforgery(context); + + // Act + var tokenSet = antiforgery.GetAndStoreTokens(context.HttpContext); + + // Assert + context.TokenStore.Verify(t => t.SaveCookieToken(It.IsAny(), It.IsAny()), Times.Once); + + Assert.Equal("serialized-new-cookie-token", tokenSet.CookieToken); + Assert.Equal("serialized-form-token", tokenSet.FormToken); + } + [Fact] public void ValidateTokens_FromInvalidStrings_Throws() { @@ -533,6 +574,8 @@ namespace Microsoft.AspNet.Antiforgery .Returns(formToken); mockSerializer.Setup(o => o.Deserialize(testTokenSet.OldCookieTokenString)) .Returns(oldCookieToken); + mockSerializer.Setup(o => o.Serialize(oldCookieToken)) + .Returns(testTokenSet.OldCookieTokenString); mockSerializer.Setup(o => o.Serialize(newCookieToken)) .Returns(testTokenSet.NewCookieTokenString); return mockSerializer; @@ -549,7 +592,7 @@ namespace Microsoft.AspNet.Antiforgery var mockSerializer = GetTokenSerializer(testTokenSet); - var mockTokenStore = GetTokenStore(httpContext, testTokenSet); + var mockTokenStore = GetTokenStore(httpContext, testTokenSet, !useOldCookie); var mockGenerator = new Mock(MockBehavior.Strict); mockGenerator From 1c39930b164de5547d1f03544fff1afc290cd443 Mon Sep 17 00:00:00 2001 From: Pranav K Date: Fri, 13 Nov 2015 10:33:23 -0800 Subject: [PATCH 046/296] Reacting to DependencyInjection changes --- .../DefaultAntiforgeryTokenStoreTest.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/Microsoft.AspNet.Antiforgery.Test/DefaultAntiforgeryTokenStoreTest.cs b/test/Microsoft.AspNet.Antiforgery.Test/DefaultAntiforgeryTokenStoreTest.cs index 27d36cd2b6..e76f400d87 100644 --- a/test/Microsoft.AspNet.Antiforgery.Test/DefaultAntiforgeryTokenStoreTest.cs +++ b/test/Microsoft.AspNet.Antiforgery.Test/DefaultAntiforgeryTokenStoreTest.cs @@ -350,7 +350,7 @@ namespace Microsoft.AspNet.Antiforgery private static IServiceProvider GetServiceProvider(IAntiforgeryContextAccessor contextAccessor) { var serviceCollection = new ServiceCollection(); - serviceCollection.AddInstance(contextAccessor); + serviceCollection.AddSingleton(contextAccessor); return serviceCollection.BuildServiceProvider(); } From 42d6166b610db8e6fdbea5009c1fa1ead072a796 Mon Sep 17 00:00:00 2001 From: Doug Bunting Date: Tue, 17 Nov 2015 10:49:09 -0800 Subject: [PATCH 047/296] Explicitly choose Mono 4.0.5 - avoids future problems related to aspnet/External#48 - e.g. when Travis updates default Mono version in `csharp` bundle --- .travis.yml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.travis.yml b/.travis.yml index 238174a4e4..fa50e30ef7 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,4 +1,6 @@ language: csharp sudo: false +mono: + - 4.0.5 script: - ./build.sh --quiet verify From 4c74e08bf12982a683e72983c8395100bb14044c Mon Sep 17 00:00:00 2001 From: Doug Bunting Date: Tue, 17 Nov 2015 12:26:08 -0800 Subject: [PATCH 048/296] Move Travis to supported Linux distribution - use Ubuntu 14.04 (Trusty) - Travis support for Trusty is in Beta and currently requires `sudo` - run `dnu restore` with DNX Core since aspnet/External#49 is not fixed in Mono versions we can use - add required dependencies for DNX Core to `.travis.yml` - addresses part of aspnet/Universe#290 --- .travis.yml | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index fa50e30ef7..2fc624899f 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,5 +1,17 @@ language: csharp -sudo: false +sudo: required +dist: trusty +addons: + apt: + packages: + - gettext + - libcurl4-openssl-dev + - libicu-dev + - libssl-dev + - libunwind8 + - zlib1g +env: + - KOREBUILD_DNU_RESTORE_CORECLR=true mono: - 4.0.5 script: From e2632d47f0c8928393e71ff8f17395cb91cf7cff Mon Sep 17 00:00:00 2001 From: Hao Kung Date: Tue, 17 Nov 2015 14:08:22 -0800 Subject: [PATCH 049/296] React to DataProtection changes --- .../AntiforgeryOptionsSetupTest.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/test/Microsoft.AspNet.Antiforgery.Test/AntiforgeryOptionsSetupTest.cs b/test/Microsoft.AspNet.Antiforgery.Test/AntiforgeryOptionsSetupTest.cs index 3966090c1e..91b9482081 100644 --- a/test/Microsoft.AspNet.Antiforgery.Test/AntiforgeryOptionsSetupTest.cs +++ b/test/Microsoft.AspNet.Antiforgery.Test/AntiforgeryOptionsSetupTest.cs @@ -19,7 +19,7 @@ namespace Microsoft.AspNet.Antiforgery // Arrange var serviceCollection = new ServiceCollection(); serviceCollection.AddAntiforgery(); - serviceCollection.ConfigureDataProtection(o => o.SetApplicationName(applicationId)); + serviceCollection.AddDataProtection(o => o.SetApplicationName(applicationId)); var services = serviceCollection.BuildServiceProvider(); var options = services.GetRequiredService>(); @@ -42,7 +42,7 @@ namespace Microsoft.AspNet.Antiforgery o.CookieName = "antiforgery"; }); serviceCollection.AddAntiforgery(); - serviceCollection.ConfigureDataProtection(o => o.SetApplicationName("HelloWorldApp")); + serviceCollection.AddDataProtection(o => o.SetApplicationName("HelloWorldApp")); var services = serviceCollection.BuildServiceProvider(); var options = services.GetRequiredService>(); From 130e8f03986d935b245a900309e6ff39f872acfb Mon Sep 17 00:00:00 2001 From: Pranav K Date: Tue, 10 Nov 2015 14:40:10 -0800 Subject: [PATCH 050/296] Updating tests to use moq.netcore --- .../DefaultAntiforgeryTest.cs | 10 ----- .../DefaultAntiforgeryTokenGeneratorTest.cs | 8 ---- .../DefaultAntiforgeryTokenSerializerTest.cs | 3 -- .../DefaultAntiforgeryTokenStoreTest.cs | 3 -- .../DefaultClaimUidExtractorTest.cs | 4 -- .../TestOptionsManager.cs | 1 - .../project.json | 44 ++++++++++--------- 7 files changed, 24 insertions(+), 49 deletions(-) diff --git a/test/Microsoft.AspNet.Antiforgery.Test/DefaultAntiforgeryTest.cs b/test/Microsoft.AspNet.Antiforgery.Test/DefaultAntiforgeryTest.cs index 59c45b919c..1a709dccad 100644 --- a/test/Microsoft.AspNet.Antiforgery.Test/DefaultAntiforgeryTest.cs +++ b/test/Microsoft.AspNet.Antiforgery.Test/DefaultAntiforgeryTest.cs @@ -8,9 +8,7 @@ using Microsoft.AspNet.Http; using Microsoft.AspNet.Http.Internal; using Microsoft.Extensions.OptionsModel; using Microsoft.Extensions.WebEncoders.Testing; -#if DNX451 using Moq; -#endif using Xunit; namespace Microsoft.AspNet.Antiforgery @@ -149,8 +147,6 @@ namespace Microsoft.AspNet.Antiforgery exception.Message); } -#if DNX451 - [Fact] public void GetHtml_ExistingInvalidCookieToken_GeneratesANewCookieAndAnAntiforgeryToken() { @@ -496,8 +492,6 @@ namespace Microsoft.AspNet.Antiforgery Assert.Equal(expectedHeaderValue, xFrameOptions); } -#endif - private DefaultAntiforgery GetAntiforgery( AntiforgeryOptions options = null, IAntiforgeryTokenGenerator tokenGenerator = null, @@ -525,8 +519,6 @@ namespace Microsoft.AspNet.Antiforgery return httpContext; } -#if DNX451 - private DefaultAntiforgery GetAntiforgery(AntiforgeryMockContext context) { return GetAntiforgery( @@ -667,8 +659,6 @@ namespace Microsoft.AspNet.Antiforgery public Mock TokenSerializer { get; set; } } -#endif - private class TestOptionsManager : IOptions { public AntiforgeryOptions Value { get; set; } = new AntiforgeryOptions(); diff --git a/test/Microsoft.AspNet.Antiforgery.Test/DefaultAntiforgeryTokenGeneratorTest.cs b/test/Microsoft.AspNet.Antiforgery.Test/DefaultAntiforgeryTokenGeneratorTest.cs index 9f8b9bd2b1..10fd048d19 100644 --- a/test/Microsoft.AspNet.Antiforgery.Test/DefaultAntiforgeryTokenGeneratorTest.cs +++ b/test/Microsoft.AspNet.Antiforgery.Test/DefaultAntiforgeryTokenGeneratorTest.cs @@ -5,9 +5,7 @@ using System; using System.Security.Claims; using System.Security.Cryptography; using Microsoft.AspNet.Http.Internal; -#if DNX451 using Moq; -#endif using Xunit; namespace Microsoft.AspNet.Antiforgery @@ -54,8 +52,6 @@ namespace Microsoft.AspNet.Antiforgery Assert.Empty(fieldToken.AdditionalData); } -#if DNX451 - [Fact] public void GenerateFormToken_AuthenticatedWithoutUsernameAndNoAdditionalData_NoAdditionalData() { @@ -191,7 +187,6 @@ namespace Microsoft.AspNet.Antiforgery Assert.Null(fieldToken.ClaimUid); Assert.Empty(fieldToken.AdditionalData); } -#endif [Fact] public void IsCookieTokenValid_FieldToken_ReturnsFalse() @@ -346,8 +341,6 @@ namespace Microsoft.AspNet.Antiforgery exception.Message); } -#if DNX451 - [Theory] [InlineData("the-user", "the-other-user")] [InlineData("http://example.com/uri-casing", "http://example.com/URI-casing")] @@ -542,7 +535,6 @@ namespace Microsoft.AspNet.Antiforgery // Assert // Nothing to assert - if we got this far, success! } -#endif private static ClaimsIdentity GetAuthenticatedIdentity(string identityUsername) { diff --git a/test/Microsoft.AspNet.Antiforgery.Test/DefaultAntiforgeryTokenSerializerTest.cs b/test/Microsoft.AspNet.Antiforgery.Test/DefaultAntiforgeryTokenSerializerTest.cs index 54fadd4399..0c074a2b13 100644 --- a/test/Microsoft.AspNet.Antiforgery.Test/DefaultAntiforgeryTokenSerializerTest.cs +++ b/test/Microsoft.AspNet.Antiforgery.Test/DefaultAntiforgeryTokenSerializerTest.cs @@ -1,7 +1,6 @@ // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. -#if DNX451 using System; using System.Collections.Generic; using System.Linq; @@ -185,5 +184,3 @@ namespace Microsoft.AspNet.Antiforgery } } } - -#endif \ No newline at end of file diff --git a/test/Microsoft.AspNet.Antiforgery.Test/DefaultAntiforgeryTokenStoreTest.cs b/test/Microsoft.AspNet.Antiforgery.Test/DefaultAntiforgeryTokenStoreTest.cs index e76f400d87..275632ab4f 100644 --- a/test/Microsoft.AspNet.Antiforgery.Test/DefaultAntiforgeryTokenStoreTest.cs +++ b/test/Microsoft.AspNet.Antiforgery.Test/DefaultAntiforgeryTokenStoreTest.cs @@ -1,7 +1,6 @@ // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. -#if DNX451 using System; using System.Collections.Generic; using System.Threading.Tasks; @@ -446,5 +445,3 @@ namespace Microsoft.AspNet.Antiforgery } } } - -#endif \ No newline at end of file diff --git a/test/Microsoft.AspNet.Antiforgery.Test/DefaultClaimUidExtractorTest.cs b/test/Microsoft.AspNet.Antiforgery.Test/DefaultClaimUidExtractorTest.cs index fe5511db95..25704e4b96 100644 --- a/test/Microsoft.AspNet.Antiforgery.Test/DefaultClaimUidExtractorTest.cs +++ b/test/Microsoft.AspNet.Antiforgery.Test/DefaultClaimUidExtractorTest.cs @@ -4,9 +4,7 @@ using System; using System.Linq; using System.Security.Claims; -#if DNX451 using Moq; -#endif using Xunit; namespace Microsoft.AspNet.Antiforgery @@ -26,7 +24,6 @@ namespace Microsoft.AspNet.Antiforgery Assert.Null(claimUid); } -#if DNX451 [Fact] public void ExtractClaimUid_Unauthenticated() { @@ -61,7 +58,6 @@ namespace Microsoft.AspNet.Antiforgery Assert.NotNull(claimUid); Assert.Equal("47DEQpj8HBSa+/TImW+5JCeuQeRkm5NMpJWZG3hSuFU=", claimUid); } -#endif [Fact] public void DefaultUniqueClaimTypes_NotPresent_SerializesAllClaimTypes() diff --git a/test/Microsoft.AspNet.Antiforgery.Test/TestOptionsManager.cs b/test/Microsoft.AspNet.Antiforgery.Test/TestOptionsManager.cs index 830d3a7913..c0a47a3537 100644 --- a/test/Microsoft.AspNet.Antiforgery.Test/TestOptionsManager.cs +++ b/test/Microsoft.AspNet.Antiforgery.Test/TestOptionsManager.cs @@ -1,7 +1,6 @@ // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. -using System; using Microsoft.Extensions.OptionsModel; namespace Microsoft.AspNet.Antiforgery diff --git a/test/Microsoft.AspNet.Antiforgery.Test/project.json b/test/Microsoft.AspNet.Antiforgery.Test/project.json index 3cb8d5fe9d..46fd83f562 100644 --- a/test/Microsoft.AspNet.Antiforgery.Test/project.json +++ b/test/Microsoft.AspNet.Antiforgery.Test/project.json @@ -1,24 +1,28 @@ { - "compilationOptions": { - "warningsAsErrors": true, - "keyFile": "../../tools/Key.snk" + "compilationOptions": { + "warningsAsErrors": true, + "keyFile": "../../tools/Key.snk" + }, + "dependencies": { + "Microsoft.AspNet.Antiforgery": "1.0.0-*", + "Microsoft.AspNet.Http": "1.0.0-*", + "Microsoft.Extensions.DependencyInjection": "1.0.0-*", + "xunit.runner.aspnet": "2.0.0-aspnet-*" + }, + "commands": { + "run": "xunit.runner.aspnet", + "test": "xunit.runner.aspnet" + }, + "frameworks": { + "dnx451": { + "dependencies": { + "Moq": "4.2.1312.1622" + } }, - "dependencies": { - "Microsoft.AspNet.Antiforgery": "1.0.0-*", - "Microsoft.AspNet.Http": "1.0.0-*", - "Microsoft.Extensions.DependencyInjection": "1.0.0-*", - "xunit.runner.aspnet": "2.0.0-aspnet-*" - }, - "commands": { - "run": "xunit.runner.aspnet", - "test": "xunit.runner.aspnet" - }, - "frameworks": { - "dnx451": { - "dependencies": { - "Moq": "4.2.1312.1622" - } - }, - "dnxcore50": { } + "dnxcore50": { + "dependencies": { + "moq.netcore": "4.4.0-beta8" + } } + } } From 78face48d069ae53bc762f66790acf05fbfbb2f2 Mon Sep 17 00:00:00 2001 From: Doug Bunting Date: Mon, 23 Nov 2015 16:10:23 -0800 Subject: [PATCH 051/296] Ignore `launchSettings.json` files --- .gitignore | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.gitignore b/.gitignore index 304382499d..321d03f03c 100644 --- a/.gitignore +++ b/.gitignore @@ -25,4 +25,5 @@ project.lock.json *DS_Store *.ncrunchsolution *.*sdf -*.ipch \ No newline at end of file +*.ipch +launchSettings.json \ No newline at end of file From 6a9b38db77f7c54bed7c5e4e4f9a2331d17f6b1d Mon Sep 17 00:00:00 2001 From: Doug Bunting Date: Wed, 25 Nov 2015 09:44:54 -0800 Subject: [PATCH 052/296] Return an `IHtmlContent` from `IAntiforgery.GetHtml()` - part of aspnet/Mvc#3123 - no longer forces caller to wrap the return value in an `HtmlString` nit: don't HTML encode the word "hidden" --- .../DefaultAntiforgery.cs | 27 ++-- .../IAntiforgery.cs | 9 +- .../ServiceCollectionExtensions.cs | 1 - src/Microsoft.AspNet.Antiforgery/project.json | 8 +- .../DefaultAntiforgeryTest.cs | 129 +++++++++++------- .../project.json | 1 + 6 files changed, 106 insertions(+), 69 deletions(-) diff --git a/src/Microsoft.AspNet.Antiforgery/DefaultAntiforgery.cs b/src/Microsoft.AspNet.Antiforgery/DefaultAntiforgery.cs index a10370c334..d46e2153cf 100644 --- a/src/Microsoft.AspNet.Antiforgery/DefaultAntiforgery.cs +++ b/src/Microsoft.AspNet.Antiforgery/DefaultAntiforgery.cs @@ -3,8 +3,8 @@ using System; using System.Diagnostics; -using System.Text.Encodings.Web; using System.Threading.Tasks; +using Microsoft.AspNet.Html.Abstractions; using Microsoft.AspNet.Http; using Microsoft.Extensions.OptionsModel; @@ -16,7 +16,6 @@ namespace Microsoft.AspNet.Antiforgery /// public class DefaultAntiforgery : IAntiforgery { - private readonly HtmlEncoder _htmlEncoder; private readonly AntiforgeryOptions _options; private readonly IAntiforgeryTokenGenerator _tokenGenerator; private readonly IAntiforgeryTokenSerializer _tokenSerializer; @@ -26,18 +25,16 @@ namespace Microsoft.AspNet.Antiforgery IOptions antiforgeryOptionsAccessor, IAntiforgeryTokenGenerator tokenGenerator, IAntiforgeryTokenSerializer tokenSerializer, - IAntiforgeryTokenStore tokenStore, - HtmlEncoder htmlEncoder) + IAntiforgeryTokenStore tokenStore) { _options = antiforgeryOptionsAccessor.Value; _tokenGenerator = tokenGenerator; _tokenSerializer = tokenSerializer; _tokenStore = tokenStore; - _htmlEncoder = htmlEncoder; } /// - public string GetHtml(HttpContext context) + public IHtmlContent GetHtml(HttpContext context) { if (context == null) { @@ -48,12 +45,17 @@ namespace Microsoft.AspNet.Antiforgery var tokenSet = GetAndStoreTokens(context); - var inputTag = string.Format( - "", - _htmlEncoder.Encode(_options.FormFieldName), - _htmlEncoder.Encode("hidden"), - _htmlEncoder.Encode(tokenSet.FormToken)); - return inputTag; + // Though FormToken normally contains only US-ASCII letters, numbers, '-', and '_', must assume the + // IAntiforgeryTokenSerializer implementation has been overridden. Similarly, users may choose a + // FormFieldName containing almost any character. + var content = new HtmlContentBuilder() + .AppendHtml(""); + + return content; } /// @@ -71,6 +73,7 @@ namespace Microsoft.AspNet.Antiforgery { SaveCookieTokenAndHeader(context, tokenSet.CookieToken); } + return Serialize(tokenSet); } diff --git a/src/Microsoft.AspNet.Antiforgery/IAntiforgery.cs b/src/Microsoft.AspNet.Antiforgery/IAntiforgery.cs index f57c5689ae..51aecc0826 100644 --- a/src/Microsoft.AspNet.Antiforgery/IAntiforgery.cs +++ b/src/Microsoft.AspNet.Antiforgery/IAntiforgery.cs @@ -2,6 +2,7 @@ // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Threading.Tasks; +using Microsoft.AspNet.Html.Abstractions; using Microsoft.AspNet.Http; namespace Microsoft.AspNet.Antiforgery @@ -13,18 +14,18 @@ namespace Microsoft.AspNet.Antiforgery public interface IAntiforgery { /// - /// Generates an input field for an antiforgery token. + /// Generates an <input type="hidden"> element for an antiforgery token. /// /// The associated with the current request. /// - /// A string containing an <input type="hidden"> element. This element should be put inside - /// a <form>. + /// A containing an <input type="hidden"> element. This element should be put + /// inside a <form>. /// /// /// This method has a side effect: /// A response cookie is set if there is no valid cookie associated with the request. /// - string GetHtml(HttpContext context); + IHtmlContent GetHtml(HttpContext context); /// /// Generates an for this request and stores the cookie token diff --git a/src/Microsoft.AspNet.Antiforgery/ServiceCollectionExtensions.cs b/src/Microsoft.AspNet.Antiforgery/ServiceCollectionExtensions.cs index e78899c7ba..f728cdb40f 100644 --- a/src/Microsoft.AspNet.Antiforgery/ServiceCollectionExtensions.cs +++ b/src/Microsoft.AspNet.Antiforgery/ServiceCollectionExtensions.cs @@ -18,7 +18,6 @@ namespace Microsoft.Extensions.DependencyInjection } services.AddDataProtection(); - services.AddWebEncoders(); // Don't overwrite any options setups that a user may have added. services.TryAddEnumerable( diff --git a/src/Microsoft.AspNet.Antiforgery/project.json b/src/Microsoft.AspNet.Antiforgery/project.json index bd7c4464a8..9222a0c515 100644 --- a/src/Microsoft.AspNet.Antiforgery/project.json +++ b/src/Microsoft.AspNet.Antiforgery/project.json @@ -11,12 +11,12 @@ }, "dependencies": { "Microsoft.AspNet.DataProtection": "1.0.0-*", + "Microsoft.AspNet.Html.Abstractions": "1.0.0-*", "Microsoft.AspNet.Http.Abstractions": "1.0.0-*", - "Microsoft.AspNet.WebUtilities": "1.0.0-*", - "Microsoft.Extensions.WebEncoders": "1.0.0-*" + "Microsoft.AspNet.WebUtilities": "1.0.0-*" }, "frameworks": { - "net451": {}, - "dotnet5.4": {} + "dotnet5.4": { }, + "net451": { } } } \ No newline at end of file diff --git a/test/Microsoft.AspNet.Antiforgery.Test/DefaultAntiforgeryTest.cs b/test/Microsoft.AspNet.Antiforgery.Test/DefaultAntiforgeryTest.cs index 1a709dccad..cd06a911b8 100644 --- a/test/Microsoft.AspNet.Antiforgery.Test/DefaultAntiforgeryTest.cs +++ b/test/Microsoft.AspNet.Antiforgery.Test/DefaultAntiforgeryTest.cs @@ -2,8 +2,10 @@ // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; +using System.IO; using System.Security.Claims; using System.Threading.Tasks; +using Microsoft.AspNet.Html.Abstractions; using Microsoft.AspNet.Http; using Microsoft.AspNet.Http.Internal; using Microsoft.Extensions.OptionsModel; @@ -73,8 +75,7 @@ namespace Microsoft.AspNet.Antiforgery var antiforgery = GetAntiforgery(options); // Act & Assert - var exception = Assert.Throws( - () => antiforgery.GetHtml(httpContext)); + var exception = Assert.Throws(() => antiforgery.GetHtml(httpContext)); Assert.Equal( @"The antiforgery system has the configuration value AntiforgeryOptions.RequireSsl = true, " + "but the current request is not an SSL request.", @@ -159,15 +160,22 @@ namespace Microsoft.AspNet.Antiforgery // Make sure the existing cookie is invalid. var context = CreateMockContext(options, isOldCookieValid: false); var antiforgery = GetAntiforgery(context); + var encoder = new HtmlTestEncoder(); // Act var inputElement = antiforgery.GetHtml(context.HttpContext); // Assert - Assert.Equal( - @"", - inputElement); + using (var writer = new StringWriter()) + { + inputElement.WriteTo(writer, encoder); + + Assert.Equal( + @"", + writer.ToString()); + } + context.TokenStore.Verify(); } @@ -185,21 +193,31 @@ namespace Microsoft.AspNet.Antiforgery var antiforgery = GetAntiforgery(context); // This will cause the cookieToken to be null. - context.TokenStore.Setup(o => o.GetCookieToken(context.HttpContext)) - .Throws(new Exception("should be swallowed")); + context.TokenStore + .Setup(o => o.GetCookieToken(context.HttpContext)) + .Throws(new Exception("should be swallowed")); // Setup so that the null cookie token returned is treated as invalid. - context.TokenGenerator.Setup(o => o.IsCookieTokenValid(null)) - .Returns(false); + context.TokenGenerator + .Setup(o => o.IsCookieTokenValid(null)) + .Returns(false); + + var encoder = new HtmlTestEncoder(); // Act var inputElement = antiforgery.GetHtml(context.HttpContext); // Assert - Assert.Equal( - @"", - inputElement); + using (var writer = new StringWriter()) + { + inputElement.WriteTo(writer, encoder); + + Assert.Equal( + @"", + writer.ToString()); + } + context.TokenStore.Verify(); } @@ -215,15 +233,21 @@ namespace Microsoft.AspNet.Antiforgery // Make sure the existing cookie is valid and use the same cookie for the mock Token Provider. var context = CreateMockContext(options, useOldCookie: true, isOldCookieValid: true); var antiforgery = GetAntiforgery(context); + var encoder = new HtmlTestEncoder(); // Act var inputElement = antiforgery.GetHtml(context.HttpContext); // Assert - Assert.Equal( - @"", - inputElement); + using (var writer = new StringWriter()) + { + inputElement.WriteTo(writer, encoder); + + Assert.Equal( + @"", + writer.ToString()); + } } [Theory] @@ -237,12 +261,12 @@ namespace Microsoft.AspNet.Antiforgery SuppressXFrameOptionsHeader = suppressXFrameOptions }; - // Genreate a new cookie. + // Generate a new cookie. var context = CreateMockContext(options, useOldCookie: false, isOldCookieValid: false); var antiforgery = GetAntiforgery(context); // Act - var inputElement = antiforgery.GetHtml(context.HttpContext); + antiforgery.GetHtml(context.HttpContext); // Assert string xFrameOptions = context.HttpContext.Response.Headers["X-Frame-Options"]; @@ -253,7 +277,7 @@ namespace Microsoft.AspNet.Antiforgery public void GetTokens_ExistingInvalidCookieToken_GeneratesANewCookieTokenAndANewFormToken() { // Arrange - // Genreate a new cookie. + // Generate a new cookie. var context = CreateMockContext( new AntiforgeryOptions(), useOldCookie: false, @@ -328,8 +352,9 @@ namespace Microsoft.AspNet.Antiforgery // Assert // We shouldn't have saved the cookie because it already existed. - context.TokenStore.Verify(t => t.SaveCookieToken(It.IsAny(), It.IsAny()), Times.Never); - + context.TokenStore.Verify( + t => t.SaveCookieToken(It.IsAny(), It.IsAny()), Times.Never); + Assert.Equal("serialized-old-cookie-token", tokenSet.CookieToken); Assert.Equal("serialized-form-token", tokenSet.FormToken); } @@ -348,7 +373,8 @@ namespace Microsoft.AspNet.Antiforgery var tokenSet = antiforgery.GetAndStoreTokens(context.HttpContext); // Assert - context.TokenStore.Verify(t => t.SaveCookieToken(It.IsAny(), It.IsAny()), Times.Once); + context.TokenStore.Verify( + t => t.SaveCookieToken(It.IsAny(), It.IsAny()), Times.Once); Assert.Equal("serialized-new-cookie-token", tokenSet.CookieToken); Assert.Equal("serialized-form-token", tokenSet.FormToken); @@ -360,22 +386,26 @@ namespace Microsoft.AspNet.Antiforgery // Arrange var context = CreateMockContext(new AntiforgeryOptions()); - context.TokenSerializer.Setup(o => o.Deserialize("cookie-token")) - .Returns(context.TestTokenSet.OldCookieToken); - context.TokenSerializer.Setup(o => o.Deserialize("form-token")) - .Returns(context.TestTokenSet.FormToken); + context.TokenSerializer + .Setup(o => o.Deserialize("cookie-token")) + .Returns(context.TestTokenSet.OldCookieToken); + context.TokenSerializer + .Setup(o => o.Deserialize("form-token")) + .Returns(context.TestTokenSet.FormToken); - context.TokenGenerator.Setup(o => o.ValidateTokens( - context.HttpContext, - context.TestTokenSet.OldCookieToken, context.TestTokenSet.FormToken)) - .Throws(new InvalidOperationException("my-message")); + context.TokenGenerator + .Setup(o => o.ValidateTokens( + context.HttpContext, + context.TestTokenSet.OldCookieToken, + context.TestTokenSet.FormToken)) + .Throws(new InvalidOperationException("my-message")); context.TokenStore = null; var antiforgery = GetAntiforgery(context); // Act & assert var exception = Assert.Throws( () => antiforgery.ValidateTokens( - context.HttpContext, + context.HttpContext, new AntiforgeryTokenSet("form-token", "cookie-token"))); Assert.Equal("my-message", exception.Message); } @@ -386,15 +416,19 @@ namespace Microsoft.AspNet.Antiforgery // Arrange var context = CreateMockContext(new AntiforgeryOptions()); - context.TokenSerializer.Setup(o => o.Deserialize("cookie-token")) - .Returns(context.TestTokenSet.OldCookieToken); - context.TokenSerializer.Setup(o => o.Deserialize("form-token")) - .Returns(context.TestTokenSet.FormToken); + context.TokenSerializer + .Setup(o => o.Deserialize("cookie-token")) + .Returns(context.TestTokenSet.OldCookieToken); + context.TokenSerializer + .Setup(o => o.Deserialize("form-token")) + .Returns(context.TestTokenSet.FormToken); - context.TokenGenerator.Setup(o => o.ValidateTokens( - context.HttpContext, - context.TestTokenSet.OldCookieToken, context.TestTokenSet.FormToken)) - .Verifiable(); + context.TokenGenerator + .Setup(o => o.ValidateTokens( + context.HttpContext, + context.TestTokenSet.OldCookieToken, + context.TestTokenSet.FormToken)) + .Verifiable(); context.TokenStore = null; var antiforgery = GetAntiforgery(context); @@ -480,7 +514,7 @@ namespace Microsoft.AspNet.Antiforgery SuppressXFrameOptionsHeader = suppressXFrameOptions }; - // Genreate a new cookie. + // Generate a new cookie. var context = CreateMockContext(options, useOldCookie: false, isOldCookieValid: false); var antiforgery = GetAntiforgery(context); @@ -508,8 +542,7 @@ namespace Microsoft.AspNet.Antiforgery antiforgeryOptionsAccessor: optionsManager, tokenGenerator: tokenGenerator, tokenSerializer: tokenSerializer, - tokenStore: tokenStore, - htmlEncoder: new HtmlTestEncoder()); + tokenStore: tokenStore); } private HttpContext GetHttpContext() @@ -522,9 +555,9 @@ namespace Microsoft.AspNet.Antiforgery private DefaultAntiforgery GetAntiforgery(AntiforgeryMockContext context) { return GetAntiforgery( - context.Options, - context.TokenGenerator?.Object, - context.TokenSerializer?.Object, + context.Options, + context.TokenGenerator?.Object, + context.TokenSerializer?.Object, context.TokenStore?.Object); } @@ -538,7 +571,7 @@ namespace Microsoft.AspNet.Antiforgery var mockTokenStore = new Mock(MockBehavior.Strict); mockTokenStore.Setup(o => o.GetCookieToken(context)) .Returns(oldCookieToken); - + mockTokenStore.Setup(o => o.GetRequestTokensAsync(context)) .Returns(() => Task.FromResult(new AntiforgeryTokenSet( testTokenSet.FormTokenString, diff --git a/test/Microsoft.AspNet.Antiforgery.Test/project.json b/test/Microsoft.AspNet.Antiforgery.Test/project.json index 46fd83f562..a9bab13140 100644 --- a/test/Microsoft.AspNet.Antiforgery.Test/project.json +++ b/test/Microsoft.AspNet.Antiforgery.Test/project.json @@ -7,6 +7,7 @@ "Microsoft.AspNet.Antiforgery": "1.0.0-*", "Microsoft.AspNet.Http": "1.0.0-*", "Microsoft.Extensions.DependencyInjection": "1.0.0-*", + "Microsoft.Extensions.WebEncoders": "1.0.0-*", "xunit.runner.aspnet": "2.0.0-aspnet-*" }, "commands": { From daf16ad184172629ecdfe5e3542cd8fc7c9802fb Mon Sep 17 00:00:00 2001 From: Pranav K Date: Tue, 1 Dec 2015 11:02:49 -0800 Subject: [PATCH 053/296] Enabling CoreCLR tests on Travis --- .travis.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index 2fc624899f..c0befaffcf 100644 --- a/.travis.yml +++ b/.travis.yml @@ -11,7 +11,7 @@ addons: - libunwind8 - zlib1g env: - - KOREBUILD_DNU_RESTORE_CORECLR=true + - KOREBUILD_DNU_RESTORE_CORECLR=true KOREBUILD_TEST_DNXCORE=true mono: - 4.0.5 script: From 463e8f94733f8e842adc330f85af3ac3cc17ebba Mon Sep 17 00:00:00 2001 From: Pranav K Date: Wed, 2 Dec 2015 10:30:01 -0800 Subject: [PATCH 054/296] React to HtmlAbstractions namespace rename --- src/Microsoft.AspNet.Antiforgery/DefaultAntiforgery.cs | 2 +- src/Microsoft.AspNet.Antiforgery/IAntiforgery.cs | 2 +- .../Microsoft.AspNet.Antiforgery.Test/DefaultAntiforgeryTest.cs | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/Microsoft.AspNet.Antiforgery/DefaultAntiforgery.cs b/src/Microsoft.AspNet.Antiforgery/DefaultAntiforgery.cs index d46e2153cf..cd67239b0d 100644 --- a/src/Microsoft.AspNet.Antiforgery/DefaultAntiforgery.cs +++ b/src/Microsoft.AspNet.Antiforgery/DefaultAntiforgery.cs @@ -4,7 +4,7 @@ using System; using System.Diagnostics; using System.Threading.Tasks; -using Microsoft.AspNet.Html.Abstractions; +using Microsoft.AspNet.Html; using Microsoft.AspNet.Http; using Microsoft.Extensions.OptionsModel; diff --git a/src/Microsoft.AspNet.Antiforgery/IAntiforgery.cs b/src/Microsoft.AspNet.Antiforgery/IAntiforgery.cs index 51aecc0826..9d11d4dad6 100644 --- a/src/Microsoft.AspNet.Antiforgery/IAntiforgery.cs +++ b/src/Microsoft.AspNet.Antiforgery/IAntiforgery.cs @@ -2,7 +2,7 @@ // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Threading.Tasks; -using Microsoft.AspNet.Html.Abstractions; +using Microsoft.AspNet.Html; using Microsoft.AspNet.Http; namespace Microsoft.AspNet.Antiforgery diff --git a/test/Microsoft.AspNet.Antiforgery.Test/DefaultAntiforgeryTest.cs b/test/Microsoft.AspNet.Antiforgery.Test/DefaultAntiforgeryTest.cs index cd06a911b8..5f6b2ea59f 100644 --- a/test/Microsoft.AspNet.Antiforgery.Test/DefaultAntiforgeryTest.cs +++ b/test/Microsoft.AspNet.Antiforgery.Test/DefaultAntiforgeryTest.cs @@ -5,7 +5,7 @@ using System; using System.IO; using System.Security.Claims; using System.Threading.Tasks; -using Microsoft.AspNet.Html.Abstractions; +using Microsoft.AspNet.Html; using Microsoft.AspNet.Http; using Microsoft.AspNet.Http.Internal; using Microsoft.Extensions.OptionsModel; From 86795ab1b6b1926b94f0bcb8fb5b2fe4a0464a93 Mon Sep 17 00:00:00 2001 From: Pranav K Date: Fri, 11 Dec 2015 12:23:45 -0800 Subject: [PATCH 055/296] Updating to release NuGet.config. --- NuGet.config | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/NuGet.config b/NuGet.config index 52bf414192..71b9724a09 100644 --- a/NuGet.config +++ b/NuGet.config @@ -1,7 +1,7 @@ - + From 3280ff6ac55aee20953fbcb7284dcdcb93aa07dd Mon Sep 17 00:00:00 2001 From: Ryan Nowak Date: Tue, 15 Dec 2015 10:45:05 -0800 Subject: [PATCH 056/296] Add Header support This change adds support for retrieving an antiforgery CSRF token via a configurable header in addition to the form field. This helps with doing ajax requests in a 1st-party SPA when using cookie auth, and is similar to functionality provided by a bunch of different frameworks. In this change there's also a bunch of churn due to avoiding the term 'form' in favor of 'request' and 'session' in favor of 'cookie'. Where code and error message now mention 'form' they specifically mean form-encoded content. --- .../FormPostSampleMiddleware.cs | 2 +- .../AntiforgeryOptions.cs | 19 ++- .../AntiforgeryToken.cs | 2 +- .../AntiforgeryTokenSet.cs | 18 +-- .../DefaultAntiforgery.cs | 22 ++-- .../DefaultAntiforgeryTokenGenerator.cs | 52 ++++---- .../DefaultAntiforgeryTokenSerializer.cs | 12 +- .../DefaultAntiforgeryTokenStore.cs | 40 ++++-- .../IAntiforgery.cs | 2 +- .../IAntiforgeryTokenGenerator.cs | 8 +- .../IAntiforgeryTokenStore.cs | 2 +- .../Properties/Resources.Designer.cs | 56 +++++++-- .../Resources.resx | 16 ++- .../AntiforgeryTokenTest.cs | 12 +- .../DefaultAntiforgeryTest.cs | 44 +++---- .../DefaultAntiforgeryTokenGeneratorTest.cs | 114 ++++++++--------- .../DefaultAntiforgeryTokenSerializerTest.cs | 22 ++-- .../DefaultAntiforgeryTokenStoreTest.cs | 118 +++++++++++++++++- 18 files changed, 370 insertions(+), 191 deletions(-) diff --git a/samples/AntiforgerySample/FormPostSampleMiddleware.cs b/samples/AntiforgerySample/FormPostSampleMiddleware.cs index aa9b41a872..ef0a8a5421 100644 --- a/samples/AntiforgerySample/FormPostSampleMiddleware.cs +++ b/samples/AntiforgerySample/FormPostSampleMiddleware.cs @@ -40,7 +40,7 @@ namespace AntiforgerySample "; var tokenSet = _antiforgery.GetAndStoreTokens(context); - await context.Response.WriteAsync(string.Format(page, _options.FormFieldName, tokenSet.FormToken)); + await context.Response.WriteAsync(string.Format(page, _options.FormFieldName, tokenSet.RequestToken)); } else if (context.Request.Method == "POST") { diff --git a/src/Microsoft.AspNet.Antiforgery/AntiforgeryOptions.cs b/src/Microsoft.AspNet.Antiforgery/AntiforgeryOptions.cs index db66421a15..2308e36699 100644 --- a/src/Microsoft.AspNet.Antiforgery/AntiforgeryOptions.cs +++ b/src/Microsoft.AspNet.Antiforgery/AntiforgeryOptions.cs @@ -11,16 +11,17 @@ namespace Microsoft.AspNet.Antiforgery public class AntiforgeryOptions { private const string AntiforgeryTokenFieldName = "__RequestVerificationToken"; + private const string AntiforgertyTokenHeaderName = "RequestVerificationToken"; + private string _cookieName; + private string _headerName = AntiforgertyTokenHeaderName; private string _formFieldName = AntiforgeryTokenFieldName; /// - /// Specifies the name of the cookie that is used by the antiforgery - /// system. + /// Specifies the name of the cookie that is used by the antiforgery system. /// /// - /// If an explicit name is not provided, the system will automatically - /// generate a name. + /// If an explicit name is not provided, the system will automatically generate a name. /// public string CookieName { @@ -59,6 +60,16 @@ namespace Microsoft.AspNet.Antiforgery } } + /// + /// Specifies the name of the header value that is used by the antiforgery system. If null then + /// antiforgery validation will only consider form data. + /// + public string HeaderName + { + get { return _headerName; } + set { _headerName = value; } + } + /// /// Specifies whether SSL is required for the antiforgery system /// to operate. If this setting is 'true' and a non-SSL request diff --git a/src/Microsoft.AspNet.Antiforgery/AntiforgeryToken.cs b/src/Microsoft.AspNet.Antiforgery/AntiforgeryToken.cs index 61f9665c26..233c5c51cd 100644 --- a/src/Microsoft.AspNet.Antiforgery/AntiforgeryToken.cs +++ b/src/Microsoft.AspNet.Antiforgery/AntiforgeryToken.cs @@ -23,7 +23,7 @@ namespace Microsoft.AspNet.Antiforgery public BinaryBlob ClaimUid { get; set; } - public bool IsSessionToken { get; set; } + public bool IsCookieToken { get; set; } public BinaryBlob SecurityToken { diff --git a/src/Microsoft.AspNet.Antiforgery/AntiforgeryTokenSet.cs b/src/Microsoft.AspNet.Antiforgery/AntiforgeryTokenSet.cs index 973e6883e9..8fabd782ee 100644 --- a/src/Microsoft.AspNet.Antiforgery/AntiforgeryTokenSet.cs +++ b/src/Microsoft.AspNet.Antiforgery/AntiforgeryTokenSet.cs @@ -6,23 +6,23 @@ using System; namespace Microsoft.AspNet.Antiforgery { /// - /// The antiforgery token pair (cookie and form token) for a request. + /// The antiforgery token pair (cookie and request token) for a request. /// public class AntiforgeryTokenSet { /// - /// Creates the antiforgery token pair (cookie and form token) for a request. + /// Creates the antiforgery token pair (cookie and request token) for a request. /// - /// The token that is supplied in the request form body. + /// The token that is supplied in the request. /// The token that is supplied in the request cookie. - public AntiforgeryTokenSet(string formToken, string cookieToken) + public AntiforgeryTokenSet(string requestToken, string cookieToken) { - if (string.IsNullOrEmpty(formToken)) + if (string.IsNullOrEmpty(requestToken)) { - throw new ArgumentException(Resources.ArgumentCannotBeNullOrEmpty, nameof(formToken)); + throw new ArgumentException(Resources.ArgumentCannotBeNullOrEmpty, nameof(requestToken)); } - FormToken = formToken; + RequestToken = requestToken; // Cookie Token is allowed to be null in the case when the old cookie is valid // and there is no new cookieToken generated. @@ -30,9 +30,9 @@ namespace Microsoft.AspNet.Antiforgery } /// - /// The token that is supplied in the request form body. + /// The token that is supplied in the request. /// - public string FormToken { get; private set; } + public string RequestToken { get; private set; } /// The cookie token is allowed to be null. /// This would be the case when the old cookie token is still valid. diff --git a/src/Microsoft.AspNet.Antiforgery/DefaultAntiforgery.cs b/src/Microsoft.AspNet.Antiforgery/DefaultAntiforgery.cs index cd67239b0d..7aa43f581d 100644 --- a/src/Microsoft.AspNet.Antiforgery/DefaultAntiforgery.cs +++ b/src/Microsoft.AspNet.Antiforgery/DefaultAntiforgery.cs @@ -45,14 +45,14 @@ namespace Microsoft.AspNet.Antiforgery var tokenSet = GetAndStoreTokens(context); - // Though FormToken normally contains only US-ASCII letters, numbers, '-', and '_', must assume the + // Though RequestToken normally contains only US-ASCII letters, numbers, '-', and '_', must assume the // IAntiforgeryTokenSerializer implementation has been overridden. Similarly, users may choose a // FormFieldName containing almost any character. var content = new HtmlContentBuilder() .AppendHtml(""); return content; @@ -122,22 +122,22 @@ namespace Microsoft.AspNet.Antiforgery nameof(antiforgeryTokenSet)); } - if (string.IsNullOrEmpty(antiforgeryTokenSet.FormToken)) + if (string.IsNullOrEmpty(antiforgeryTokenSet.RequestToken)) { throw new ArgumentException( - Resources.Antiforgery_FormToken_MustBeProvided_Generic, + Resources.Antiforgery_RequestToken_MustBeProvided_Generic, nameof(antiforgeryTokenSet)); } - // Extract cookie & form tokens + // Extract cookie & request tokens var deserializedCookieToken = _tokenSerializer.Deserialize(antiforgeryTokenSet.CookieToken); - var deserializedFormToken = _tokenSerializer.Deserialize(antiforgeryTokenSet.FormToken); + var deserializedRequestToken = _tokenSerializer.Deserialize(antiforgeryTokenSet.RequestToken); // Validate _tokenGenerator.ValidateTokens( context, deserializedCookieToken, - deserializedFormToken); + deserializedRequestToken); } /// @@ -225,7 +225,7 @@ namespace Microsoft.AspNet.Antiforgery { cookieToken = newCookieToken; } - var formToken = _tokenGenerator.GenerateFormToken( + var requestToken = _tokenGenerator.GenerateRequestToken( context, cookieToken); @@ -233,7 +233,7 @@ namespace Microsoft.AspNet.Antiforgery { // Note : The new cookie would be null if the old cookie is valid. CookieToken = cookieToken, - FormToken = formToken, + RequestToken = requestToken, IsNewCookieToken = newCookieToken != null }; } @@ -241,13 +241,13 @@ namespace Microsoft.AspNet.Antiforgery private AntiforgeryTokenSet Serialize(AntiforgeryTokenSetInternal tokenSet) { return new AntiforgeryTokenSet( - tokenSet.FormToken != null ? _tokenSerializer.Serialize(tokenSet.FormToken) : null, + tokenSet.RequestToken != null ? _tokenSerializer.Serialize(tokenSet.RequestToken) : null, tokenSet.CookieToken != null ? _tokenSerializer.Serialize(tokenSet.CookieToken) : null); } private class AntiforgeryTokenSetInternal { - public AntiforgeryToken FormToken { get; set; } + public AntiforgeryToken RequestToken { get; set; } public AntiforgeryToken CookieToken { get; set; } diff --git a/src/Microsoft.AspNet.Antiforgery/DefaultAntiforgeryTokenGenerator.cs b/src/Microsoft.AspNet.Antiforgery/DefaultAntiforgeryTokenGenerator.cs index c23661ccc4..32a2581f71 100644 --- a/src/Microsoft.AspNet.Antiforgery/DefaultAntiforgeryTokenGenerator.cs +++ b/src/Microsoft.AspNet.Antiforgery/DefaultAntiforgeryTokenGenerator.cs @@ -27,11 +27,11 @@ namespace Microsoft.AspNet.Antiforgery return new AntiforgeryToken() { // SecurityToken will be populated automatically. - IsSessionToken = true + IsCookieToken = true }; } - public AntiforgeryToken GenerateFormToken( + public AntiforgeryToken GenerateRequestToken( HttpContext httpContext, AntiforgeryToken cookieToken) { @@ -42,10 +42,10 @@ namespace Microsoft.AspNet.Antiforgery Debug.Assert(IsCookieTokenValid(cookieToken)); - var formToken = new AntiforgeryToken() + var requestToken = new AntiforgeryToken() { SecurityToken = cookieToken.SecurityToken, - IsSessionToken = false + IsCookieToken = false }; var isIdentityAuthenticated = false; @@ -55,23 +55,23 @@ namespace Microsoft.AspNet.Antiforgery if (identity != null && identity.IsAuthenticated) { isIdentityAuthenticated = true; - formToken.ClaimUid = GetClaimUidBlob(_claimUidExtractor.ExtractClaimUid(identity)); - if (formToken.ClaimUid == null) + requestToken.ClaimUid = GetClaimUidBlob(_claimUidExtractor.ExtractClaimUid(identity)); + if (requestToken.ClaimUid == null) { - formToken.Username = identity.Name; + requestToken.Username = identity.Name; } } // populate AdditionalData if (_additionalDataProvider != null) { - formToken.AdditionalData = _additionalDataProvider.GetAdditionalData(httpContext); + requestToken.AdditionalData = _additionalDataProvider.GetAdditionalData(httpContext); } if (isIdentityAuthenticated - && string.IsNullOrEmpty(formToken.Username) - && formToken.ClaimUid == null - && string.IsNullOrEmpty(formToken.AdditionalData)) + && string.IsNullOrEmpty(requestToken.Username) + && requestToken.ClaimUid == null + && string.IsNullOrEmpty(requestToken.AdditionalData)) { // Application says user is authenticated, but we have no identifier for the user. throw new InvalidOperationException( @@ -84,46 +84,46 @@ namespace Microsoft.AspNet.Antiforgery nameof(DefaultAntiforgeryAdditionalDataProvider))); } - return formToken; + return requestToken; } public bool IsCookieTokenValid(AntiforgeryToken cookieToken) { - return (cookieToken != null && cookieToken.IsSessionToken); + return (cookieToken != null && cookieToken.IsCookieToken); } public void ValidateTokens( HttpContext httpContext, - AntiforgeryToken sessionToken, - AntiforgeryToken fieldToken) + AntiforgeryToken cookieToken, + AntiforgeryToken requestToken) { if (httpContext == null) { throw new ArgumentNullException(nameof(httpContext)); } - if (sessionToken == null) + if (cookieToken == null) { throw new ArgumentNullException( - nameof(sessionToken), + nameof(cookieToken), Resources.Antiforgery_CookieToken_MustBeProvided_Generic); } - if (fieldToken == null) + if (requestToken == null) { throw new ArgumentNullException( - nameof(fieldToken), - Resources.Antiforgery_FormToken_MustBeProvided_Generic); + nameof(requestToken), + Resources.Antiforgery_RequestToken_MustBeProvided_Generic); } // Do the tokens have the correct format? - if (!sessionToken.IsSessionToken || fieldToken.IsSessionToken) + if (!cookieToken.IsCookieToken || requestToken.IsCookieToken) { throw new InvalidOperationException(Resources.AntiforgeryToken_TokensSwapped); } // Are the security tokens embedded in each incoming token identical? - if (!Equals(sessionToken.SecurityToken, fieldToken.SecurityToken)) + if (!Equals(cookieToken.SecurityToken, requestToken.SecurityToken)) { throw new InvalidOperationException(Resources.AntiforgeryToken_SecurityTokenMismatch); } @@ -148,24 +148,24 @@ namespace Microsoft.AspNet.Antiforgery currentUsername.StartsWith("http://", StringComparison.OrdinalIgnoreCase) || currentUsername.StartsWith("https://", StringComparison.OrdinalIgnoreCase); - if (!string.Equals(fieldToken.Username, + if (!string.Equals(requestToken.Username, currentUsername, (useCaseSensitiveUsernameComparison) ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase)) { throw new InvalidOperationException( - Resources.FormatAntiforgeryToken_UsernameMismatch(fieldToken.Username, currentUsername)); + Resources.FormatAntiforgeryToken_UsernameMismatch(requestToken.Username, currentUsername)); } - if (!Equals(fieldToken.ClaimUid, currentClaimUid)) + if (!Equals(requestToken.ClaimUid, currentClaimUid)) { throw new InvalidOperationException(Resources.AntiforgeryToken_ClaimUidMismatch); } // Is the AdditionalData valid? if (_additionalDataProvider != null && - !_additionalDataProvider.ValidateAdditionalData(httpContext, fieldToken.AdditionalData)) + !_additionalDataProvider.ValidateAdditionalData(httpContext, requestToken.AdditionalData)) { throw new InvalidOperationException(Resources.AntiforgeryToken_AdditionalDataCheckFailed); } diff --git a/src/Microsoft.AspNet.Antiforgery/DefaultAntiforgeryTokenSerializer.cs b/src/Microsoft.AspNet.Antiforgery/DefaultAntiforgeryTokenSerializer.cs index c5eb46a413..e1ecd406e8 100644 --- a/src/Microsoft.AspNet.Antiforgery/DefaultAntiforgeryTokenSerializer.cs +++ b/src/Microsoft.AspNet.Antiforgery/DefaultAntiforgeryTokenSerializer.cs @@ -56,8 +56,8 @@ namespace Microsoft.AspNet.Antiforgery /* The serialized format of the anti-XSRF token is as follows: * Version: 1 byte integer * SecurityToken: 16 byte binary blob - * IsSessionToken: 1 byte Boolean - * [if IsSessionToken != true] + * IsCookieToken: 1 byte Boolean + * [if IsCookieToken != true] * +- IsClaimsBased: 1 byte Boolean * | [if IsClaimsBased = true] * | `- ClaimUid: 32 byte binary blob @@ -78,9 +78,9 @@ namespace Microsoft.AspNet.Antiforgery var securityTokenBytes = reader.ReadBytes(AntiforgeryToken.SecurityTokenBitLength / 8); deserializedToken.SecurityToken = new BinaryBlob(AntiforgeryToken.SecurityTokenBitLength, securityTokenBytes); - deserializedToken.IsSessionToken = reader.ReadBoolean(); + deserializedToken.IsCookieToken = reader.ReadBoolean(); - if (!deserializedToken.IsSessionToken) + if (!deserializedToken.IsCookieToken) { var isClaimsBased = reader.ReadBoolean(); if (isClaimsBased) @@ -119,9 +119,9 @@ namespace Microsoft.AspNet.Antiforgery { writer.Write(TokenVersion); writer.Write(token.SecurityToken.GetData()); - writer.Write(token.IsSessionToken); + writer.Write(token.IsCookieToken); - if (!token.IsSessionToken) + if (!token.IsCookieToken) { if (token.ClaimUid != null) { diff --git a/src/Microsoft.AspNet.Antiforgery/DefaultAntiforgeryTokenStore.cs b/src/Microsoft.AspNet.Antiforgery/DefaultAntiforgeryTokenStore.cs index 29a50483ce..8adbd024ea 100644 --- a/src/Microsoft.AspNet.Antiforgery/DefaultAntiforgeryTokenStore.cs +++ b/src/Microsoft.AspNet.Antiforgery/DefaultAntiforgeryTokenStore.cs @@ -7,10 +7,10 @@ using System.Threading.Tasks; using Microsoft.AspNet.Http; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.OptionsModel; +using Microsoft.Extensions.Primitives; namespace Microsoft.AspNet.Antiforgery { - // Saves anti-XSRF tokens split between HttpRequest.Cookies and HttpRequest.Form public class DefaultAntiforgeryTokenStore : IAntiforgeryTokenStore { private readonly AntiforgeryOptions _options; @@ -72,23 +72,43 @@ namespace Microsoft.AspNet.Antiforgery Resources.FormatAntiforgery_CookieToken_MustBeProvided(_options.CookieName)); } - if (!httpContext.Request.HasFormContentType) + StringValues requestToken; + if (httpContext.Request.HasFormContentType) { // Check the content-type before accessing the form collection to make sure // we throw gracefully. - throw new InvalidOperationException( - Resources.FormatAntiforgery_FormToken_MustBeProvided(_options.FormFieldName)); + var form = await httpContext.Request.ReadFormAsync(); + requestToken = form[_options.FormFieldName]; } - var form = await httpContext.Request.ReadFormAsync(); - var formField = form[_options.FormFieldName]; - if (string.IsNullOrEmpty(formField)) + // Fall back to header if the form value was not provided. + if (requestToken.Count == 0 && _options.HeaderName != null) { - throw new InvalidOperationException( - Resources.FormatAntiforgery_FormToken_MustBeProvided(_options.FormFieldName)); + requestToken = httpContext.Request.Headers[_options.HeaderName]; } - return new AntiforgeryTokenSet(formField, requestCookie); + if (requestToken.Count == 0) + { + if (_options.HeaderName == null) + { + var message = Resources.FormatAntiforgery_FormToken_MustBeProvided(_options.FormFieldName); + throw new InvalidOperationException(message); + } + else if (!httpContext.Request.HasFormContentType) + { + var message = Resources.FormatAntiforgery_HeaderToken_MustBeProvided(_options.HeaderName); + throw new InvalidOperationException(message); + } + else + { + var message = Resources.FormatAntiforgery_RequestToken_MustBeProvided( + _options.FormFieldName, + _options.HeaderName); + throw new InvalidOperationException(message); + } + } + + return new AntiforgeryTokenSet(requestToken, requestCookie); } public void SaveCookieToken(HttpContext httpContext, AntiforgeryToken token) diff --git a/src/Microsoft.AspNet.Antiforgery/IAntiforgery.cs b/src/Microsoft.AspNet.Antiforgery/IAntiforgery.cs index 9d11d4dad6..1944b02622 100644 --- a/src/Microsoft.AspNet.Antiforgery/IAntiforgery.cs +++ b/src/Microsoft.AspNet.Antiforgery/IAntiforgery.cs @@ -61,7 +61,7 @@ namespace Microsoft.AspNet.Antiforgery /// /// The associated with the current request. /// - /// The (cookie and form token) for this request. + /// The (cookie and request token) for this request. /// void ValidateTokens(HttpContext context, AntiforgeryTokenSet antiforgeryTokenSet); diff --git a/src/Microsoft.AspNet.Antiforgery/IAntiforgeryTokenGenerator.cs b/src/Microsoft.AspNet.Antiforgery/IAntiforgeryTokenGenerator.cs index 0918d26917..47b701817c 100644 --- a/src/Microsoft.AspNet.Antiforgery/IAntiforgeryTokenGenerator.cs +++ b/src/Microsoft.AspNet.Antiforgery/IAntiforgeryTokenGenerator.cs @@ -13,9 +13,9 @@ namespace Microsoft.AspNet.Antiforgery // Generates a new random cookie token. AntiforgeryToken GenerateCookieToken(); - // Given a cookie token, generates a corresponding form token. + // Given a cookie token, generates a corresponding request token. // The incoming cookie token must be valid. - AntiforgeryToken GenerateFormToken( + AntiforgeryToken GenerateRequestToken( HttpContext httpContext, AntiforgeryToken cookieToken); @@ -23,10 +23,10 @@ namespace Microsoft.AspNet.Antiforgery // If it is not, the caller must call GenerateCookieToken() before calling GenerateFormToken(). bool IsCookieTokenValid(AntiforgeryToken cookieToken); - // Validates a (cookie, form) token pair. + // Validates a (cookie, request) token pair. void ValidateTokens( HttpContext httpContext, AntiforgeryToken cookieToken, - AntiforgeryToken formToken); + AntiforgeryToken requestToken); } } \ No newline at end of file diff --git a/src/Microsoft.AspNet.Antiforgery/IAntiforgeryTokenStore.cs b/src/Microsoft.AspNet.Antiforgery/IAntiforgeryTokenStore.cs index c600d68e53..15ea992cb8 100644 --- a/src/Microsoft.AspNet.Antiforgery/IAntiforgeryTokenStore.cs +++ b/src/Microsoft.AspNet.Antiforgery/IAntiforgeryTokenStore.cs @@ -12,7 +12,7 @@ namespace Microsoft.AspNet.Antiforgery AntiforgeryToken GetCookieToken(HttpContext httpContext); /// - /// Gets the cookie and form tokens from the request. Will throw an exception if either token is + /// Gets the cookie and request tokens from the request. Will throw an exception if either token is /// not present. /// /// The for the current request. diff --git a/src/Microsoft.AspNet.Antiforgery/Properties/Resources.Designer.cs b/src/Microsoft.AspNet.Antiforgery/Properties/Resources.Designer.cs index e4542a56f5..df958a3454 100644 --- a/src/Microsoft.AspNet.Antiforgery/Properties/Resources.Designer.cs +++ b/src/Microsoft.AspNet.Antiforgery/Properties/Resources.Designer.cs @@ -75,7 +75,7 @@ namespace Microsoft.AspNet.Antiforgery } /// - /// The antiforgery cookie token and form field token do not match. + /// The antiforgery cookie token and request token do not match. /// internal static string AntiforgeryToken_SecurityTokenMismatch { @@ -83,7 +83,7 @@ namespace Microsoft.AspNet.Antiforgery } /// - /// The antiforgery cookie token and form field token do not match. + /// The antiforgery cookie token and request token do not match. /// internal static string FormatAntiforgeryToken_SecurityTokenMismatch() { @@ -91,7 +91,7 @@ namespace Microsoft.AspNet.Antiforgery } /// - /// Validation of the provided antiforgery token failed. The cookie token and the form token were swapped. + /// Validation of the provided antiforgery token failed. The cookie token and the request token were swapped. /// internal static string AntiforgeryToken_TokensSwapped { @@ -99,7 +99,7 @@ namespace Microsoft.AspNet.Antiforgery } /// - /// Validation of the provided antiforgery token failed. The cookie token and the form token were swapped. + /// Validation of the provided antiforgery token failed. The cookie token and the request token were swapped. /// internal static string FormatAntiforgeryToken_TokensSwapped() { @@ -155,7 +155,7 @@ namespace Microsoft.AspNet.Antiforgery } /// - /// The cookie token must be provided. + /// The required antiforgery cookie token must be provided. /// internal static string Antiforgery_CookieToken_MustBeProvided_Generic { @@ -163,7 +163,7 @@ namespace Microsoft.AspNet.Antiforgery } /// - /// The cookie token must be provided. + /// The required antiforgery cookie token must be provided. /// internal static string FormatAntiforgery_CookieToken_MustBeProvided_Generic() { @@ -187,19 +187,51 @@ namespace Microsoft.AspNet.Antiforgery } /// - /// The form token must be provided. + /// The required antiforgery header value "{0}" is not present. /// - internal static string Antiforgery_FormToken_MustBeProvided_Generic + internal static string Antiforgery_HeaderToken_MustBeProvided { - get { return GetString("Antiforgery_FormToken_MustBeProvided_Generic"); } + get { return GetString("Antiforgery_HeaderToken_MustBeProvided"); } } /// - /// The form token must be provided. + /// The required antiforgery header value "{0}" is not present. /// - internal static string FormatAntiforgery_FormToken_MustBeProvided_Generic() + internal static string FormatAntiforgery_HeaderToken_MustBeProvided(object p0) { - return GetString("Antiforgery_FormToken_MustBeProvided_Generic"); + return string.Format(CultureInfo.CurrentCulture, GetString("Antiforgery_HeaderToken_MustBeProvided"), p0); + } + + /// + /// The required antiforgery request token was not provided in either form field "{0}" or header value "{1}". + /// + internal static string Antiforgery_RequestToken_MustBeProvided + { + get { return GetString("Antiforgery_RequestToken_MustBeProvided"); } + } + + /// + /// The required antiforgery request token was not provided in either form field "{0}" or header value "{1}". + /// + internal static string FormatAntiforgery_RequestToken_MustBeProvided(object p0, object p1) + { + return string.Format(CultureInfo.CurrentCulture, GetString("Antiforgery_RequestToken_MustBeProvided"), p0, p1); + } + + /// + /// The required antiforgery request token must be provided. + /// + internal static string Antiforgery_RequestToken_MustBeProvided_Generic + { + get { return GetString("Antiforgery_RequestToken_MustBeProvided_Generic"); } + } + + /// + /// The required antiforgery request token must be provided. + /// + internal static string FormatAntiforgery_RequestToken_MustBeProvided_Generic() + { + return GetString("Antiforgery_RequestToken_MustBeProvided_Generic"); } /// diff --git a/src/Microsoft.AspNet.Antiforgery/Resources.resx b/src/Microsoft.AspNet.Antiforgery/Resources.resx index cb8f9c3db8..8e84c4cac5 100644 --- a/src/Microsoft.AspNet.Antiforgery/Resources.resx +++ b/src/Microsoft.AspNet.Antiforgery/Resources.resx @@ -131,10 +131,10 @@ The antiforgery token could not be decrypted. - The antiforgery cookie token and form field token do not match. + The antiforgery cookie token and request token do not match. - Validation of the provided antiforgery token failed. The cookie token and the form token were swapped. + Validation of the provided antiforgery token failed. The cookie token and the request token were swapped. The provided antiforgery token was meant for user "{0}", but the current user is "{1}". @@ -147,13 +147,19 @@ The required antiforgery cookie "{0}" is not present. - The cookie token must be provided. + The required antiforgery cookie token must be provided. The required antiforgery form field "{0}" is not present. - - The form token must be provided. + + The required antiforgery header value "{0}" is not present. + + + The required antiforgery request token was not provided in either form field "{0}" or header value "{1}". + + + The required antiforgery request token must be provided. Value cannot be null or empty. diff --git a/test/Microsoft.AspNet.Antiforgery.Test/AntiforgeryTokenTest.cs b/test/Microsoft.AspNet.Antiforgery.Test/AntiforgeryTokenTest.cs index cddd47e43f..c56055bee7 100644 --- a/test/Microsoft.AspNet.Antiforgery.Test/AntiforgeryTokenTest.cs +++ b/test/Microsoft.AspNet.Antiforgery.Test/AntiforgeryTokenTest.cs @@ -45,21 +45,21 @@ namespace Microsoft.AspNet.Antiforgery } [Fact] - public void IsSessionTokenProperty() + public void IsCookieTokenProperty() { // Arrange var token = new AntiforgeryToken(); // Act & assert - 1 - Assert.False(token.IsSessionToken); + Assert.False(token.IsCookieToken); // Act & assert - 2 - token.IsSessionToken = true; - Assert.True(token.IsSessionToken); + token.IsCookieToken = true; + Assert.True(token.IsCookieToken); // Act & assert - 3 - token.IsSessionToken = false; - Assert.False(token.IsSessionToken); + token.IsCookieToken = false; + Assert.False(token.IsCookieToken); } [Fact] diff --git a/test/Microsoft.AspNet.Antiforgery.Test/DefaultAntiforgeryTest.cs b/test/Microsoft.AspNet.Antiforgery.Test/DefaultAntiforgeryTest.cs index 5f6b2ea59f..1a85a6826a 100644 --- a/test/Microsoft.AspNet.Antiforgery.Test/DefaultAntiforgeryTest.cs +++ b/test/Microsoft.AspNet.Antiforgery.Test/DefaultAntiforgeryTest.cs @@ -289,7 +289,7 @@ namespace Microsoft.AspNet.Antiforgery // Assert Assert.Equal("serialized-new-cookie-token", tokenset.CookieToken); - Assert.Equal("serialized-form-token", tokenset.FormToken); + Assert.Equal("serialized-form-token", tokenset.RequestToken); } [Fact] @@ -316,7 +316,7 @@ namespace Microsoft.AspNet.Antiforgery // Assert Assert.Equal("serialized-new-cookie-token", tokenset.CookieToken); - Assert.Equal("serialized-form-token", tokenset.FormToken); + Assert.Equal("serialized-form-token", tokenset.RequestToken); } [Fact] @@ -334,7 +334,7 @@ namespace Microsoft.AspNet.Antiforgery // Assert Assert.Equal("serialized-old-cookie-token", tokenset.CookieToken); - Assert.Equal("serialized-form-token", tokenset.FormToken); + Assert.Equal("serialized-form-token", tokenset.RequestToken); } [Fact] @@ -356,7 +356,7 @@ namespace Microsoft.AspNet.Antiforgery t => t.SaveCookieToken(It.IsAny(), It.IsAny()), Times.Never); Assert.Equal("serialized-old-cookie-token", tokenSet.CookieToken); - Assert.Equal("serialized-form-token", tokenSet.FormToken); + Assert.Equal("serialized-form-token", tokenSet.RequestToken); } [Fact] @@ -377,7 +377,7 @@ namespace Microsoft.AspNet.Antiforgery t => t.SaveCookieToken(It.IsAny(), It.IsAny()), Times.Once); Assert.Equal("serialized-new-cookie-token", tokenSet.CookieToken); - Assert.Equal("serialized-form-token", tokenSet.FormToken); + Assert.Equal("serialized-form-token", tokenSet.RequestToken); } [Fact] @@ -391,13 +391,13 @@ namespace Microsoft.AspNet.Antiforgery .Returns(context.TestTokenSet.OldCookieToken); context.TokenSerializer .Setup(o => o.Deserialize("form-token")) - .Returns(context.TestTokenSet.FormToken); + .Returns(context.TestTokenSet.RequestToken); context.TokenGenerator .Setup(o => o.ValidateTokens( context.HttpContext, context.TestTokenSet.OldCookieToken, - context.TestTokenSet.FormToken)) + context.TestTokenSet.RequestToken)) .Throws(new InvalidOperationException("my-message")); context.TokenStore = null; var antiforgery = GetAntiforgery(context); @@ -421,13 +421,13 @@ namespace Microsoft.AspNet.Antiforgery .Returns(context.TestTokenSet.OldCookieToken); context.TokenSerializer .Setup(o => o.Deserialize("form-token")) - .Returns(context.TestTokenSet.FormToken); + .Returns(context.TestTokenSet.RequestToken); context.TokenGenerator .Setup(o => o.ValidateTokens( context.HttpContext, context.TestTokenSet.OldCookieToken, - context.TestTokenSet.FormToken)) + context.TestTokenSet.RequestToken)) .Verifiable(); context.TokenStore = null; var antiforgery = GetAntiforgery(context); @@ -455,7 +455,7 @@ namespace Microsoft.AspNet.Antiforgery // Assert var trimmed = exception.Message.Substring(0, exception.Message.IndexOf(Environment.NewLine)); - Assert.Equal("The cookie token must be provided.", trimmed); + Assert.Equal("The required antiforgery cookie token must be provided.", trimmed); } [Fact] @@ -468,7 +468,7 @@ namespace Microsoft.AspNet.Antiforgery .Setup(o => o.ValidateTokens( context.HttpContext, context.TestTokenSet.OldCookieToken, - context.TestTokenSet.FormToken)) + context.TestTokenSet.RequestToken)) .Throws(new InvalidOperationException("my-message")); var antiforgery = GetAntiforgery(context); @@ -489,7 +489,7 @@ namespace Microsoft.AspNet.Antiforgery .Setup(o => o.ValidateTokens( context.HttpContext, context.TestTokenSet.OldCookieToken, - context.TestTokenSet.FormToken)) + context.TestTokenSet.RequestToken)) .Verifiable(); var antiforgery = GetAntiforgery(context); @@ -567,7 +567,7 @@ namespace Microsoft.AspNet.Antiforgery bool saveNewCookie = true) { var oldCookieToken = testTokenSet.OldCookieToken; - var formToken = testTokenSet.FormToken; + var formToken = testTokenSet.RequestToken; var mockTokenStore = new Mock(MockBehavior.Strict); mockTokenStore.Setup(o => o.GetCookieToken(context)) .Returns(oldCookieToken); @@ -591,7 +591,7 @@ namespace Microsoft.AspNet.Antiforgery { var oldCookieToken = testTokenSet.OldCookieToken; var newCookieToken = testTokenSet.NewCookieToken; - var formToken = testTokenSet.FormToken; + var formToken = testTokenSet.RequestToken; var mockSerializer = new Mock(MockBehavior.Strict); mockSerializer.Setup(o => o.Serialize(formToken)) .Returns(testTokenSet.FormTokenString); @@ -613,7 +613,7 @@ namespace Microsoft.AspNet.Antiforgery { // Arrange var httpContext = GetHttpContext(); - var testTokenSet = GetTokenSet(isOldCookieTokenSessionToken: true, isNewCookieSessionToken: true); + var testTokenSet = GetTokenSet(); var mockSerializer = GetTokenSerializer(testTokenSet); @@ -621,10 +621,10 @@ namespace Microsoft.AspNet.Antiforgery var mockGenerator = new Mock(MockBehavior.Strict); mockGenerator - .Setup(o => o.GenerateFormToken( + .Setup(o => o.GenerateRequestToken( httpContext, useOldCookie ? testTokenSet.OldCookieToken : testTokenSet.NewCookieToken)) - .Returns(testTokenSet.FormToken); + .Returns(testTokenSet.RequestToken); mockGenerator .Setup(o => o.GenerateCookieToken()) @@ -649,22 +649,22 @@ namespace Microsoft.AspNet.Antiforgery }; } - private TestTokenSet GetTokenSet(bool isOldCookieTokenSessionToken = true, bool isNewCookieSessionToken = true) + private TestTokenSet GetTokenSet() { return new TestTokenSet() { - FormToken = new AntiforgeryToken() { IsSessionToken = false }, + RequestToken = new AntiforgeryToken() { IsCookieToken = false }, FormTokenString = "serialized-form-token", - OldCookieToken = new AntiforgeryToken() { IsSessionToken = isOldCookieTokenSessionToken }, + OldCookieToken = new AntiforgeryToken() { IsCookieToken = true }, OldCookieTokenString = "serialized-old-cookie-token", - NewCookieToken = new AntiforgeryToken() { IsSessionToken = isNewCookieSessionToken }, + NewCookieToken = new AntiforgeryToken() { IsCookieToken = true }, NewCookieTokenString = "serialized-new-cookie-token", }; } private class TestTokenSet { - public AntiforgeryToken FormToken { get; set; } + public AntiforgeryToken RequestToken { get; set; } public string FormTokenString { get; set; } diff --git a/test/Microsoft.AspNet.Antiforgery.Test/DefaultAntiforgeryTokenGeneratorTest.cs b/test/Microsoft.AspNet.Antiforgery.Test/DefaultAntiforgeryTokenGeneratorTest.cs index 10fd048d19..4813d68411 100644 --- a/test/Microsoft.AspNet.Antiforgery.Test/DefaultAntiforgeryTokenGeneratorTest.cs +++ b/test/Microsoft.AspNet.Antiforgery.Test/DefaultAntiforgeryTokenGeneratorTest.cs @@ -31,7 +31,7 @@ namespace Microsoft.AspNet.Antiforgery public void GenerateFormToken_AnonymousUser() { // Arrange - var cookieToken = new AntiforgeryToken() { IsSessionToken = true }; + var cookieToken = new AntiforgeryToken() { IsCookieToken = true }; var httpContext = new DefaultHttpContext(); httpContext.User = new ClaimsPrincipal(new ClaimsIdentity()); Assert.False(httpContext.User.Identity.IsAuthenticated); @@ -41,12 +41,12 @@ namespace Microsoft.AspNet.Antiforgery additionalDataProvider: null); // Act - var fieldToken = tokenProvider.GenerateFormToken(httpContext, cookieToken); + var fieldToken = tokenProvider.GenerateRequestToken(httpContext, cookieToken); // Assert Assert.NotNull(fieldToken); Assert.Equal(cookieToken.SecurityToken, fieldToken.SecurityToken); - Assert.False(fieldToken.IsSessionToken); + Assert.False(fieldToken.IsCookieToken); Assert.Empty(fieldToken.Username); Assert.Null(fieldToken.ClaimUid); Assert.Empty(fieldToken.AdditionalData); @@ -58,7 +58,7 @@ namespace Microsoft.AspNet.Antiforgery // Arrange var cookieToken = new AntiforgeryToken() { - IsSessionToken = true + IsCookieToken = true }; var httpContext = new DefaultHttpContext(); @@ -73,7 +73,7 @@ namespace Microsoft.AspNet.Antiforgery // Act & assert var exception = Assert.Throws( - () => tokenProvider.GenerateFormToken(httpContext, cookieToken)); + () => tokenProvider.GenerateRequestToken(httpContext, cookieToken)); Assert.Equal( "The provided identity of type " + $"'{typeof(MyAuthenticatedIdentityWithoutUsername).FullName}' " + @@ -90,7 +90,7 @@ namespace Microsoft.AspNet.Antiforgery public void GenerateFormToken_AuthenticatedWithoutUsername_WithAdditionalData() { // Arrange - var cookieToken = new AntiforgeryToken() { IsSessionToken = true }; + var cookieToken = new AntiforgeryToken() { IsCookieToken = true }; var httpContext = new DefaultHttpContext(); httpContext.User = new ClaimsPrincipal(new MyAuthenticatedIdentityWithoutUsername()); @@ -106,12 +106,12 @@ namespace Microsoft.AspNet.Antiforgery additionalDataProvider: mockAdditionalDataProvider.Object); // Act - var fieldToken = tokenProvider.GenerateFormToken(httpContext, cookieToken); + var fieldToken = tokenProvider.GenerateRequestToken(httpContext, cookieToken); // Assert Assert.NotNull(fieldToken); Assert.Equal(cookieToken.SecurityToken, fieldToken.SecurityToken); - Assert.False(fieldToken.IsSessionToken); + Assert.False(fieldToken.IsCookieToken); Assert.Empty(fieldToken.Username); Assert.Null(fieldToken.ClaimUid); Assert.Equal("additional-data", fieldToken.AdditionalData); @@ -121,7 +121,7 @@ namespace Microsoft.AspNet.Antiforgery public void GenerateFormToken_ClaimsBasedIdentity() { // Arrange - var cookieToken = new AntiforgeryToken() { IsSessionToken = true }; + var cookieToken = new AntiforgeryToken() { IsCookieToken = true }; var identity = GetAuthenticatedIdentity("some-identity"); var httpContext = new DefaultHttpContext(); @@ -144,12 +144,12 @@ namespace Microsoft.AspNet.Antiforgery additionalDataProvider: null); // Act - var fieldToken = tokenProvider.GenerateFormToken(httpContext, cookieToken); + var fieldToken = tokenProvider.GenerateRequestToken(httpContext, cookieToken); // Assert Assert.NotNull(fieldToken); Assert.Equal(cookieToken.SecurityToken, fieldToken.SecurityToken); - Assert.False(fieldToken.IsSessionToken); + Assert.False(fieldToken.IsCookieToken); Assert.Equal("", fieldToken.Username); Assert.Equal(expectedClaimUid, fieldToken.ClaimUid); Assert.Equal("", fieldToken.AdditionalData); @@ -159,7 +159,7 @@ namespace Microsoft.AspNet.Antiforgery public void GenerateFormToken_RegularUserWithUsername() { // Arrange - var cookieToken = new AntiforgeryToken() { IsSessionToken = true }; + var cookieToken = new AntiforgeryToken() { IsCookieToken = true }; var httpContext = new DefaultHttpContext(); var mockIdentity = new Mock(); @@ -177,12 +177,12 @@ namespace Microsoft.AspNet.Antiforgery additionalDataProvider: null); // Act - var fieldToken = tokenProvider.GenerateFormToken(httpContext, cookieToken); + var fieldToken = tokenProvider.GenerateRequestToken(httpContext, cookieToken); // Assert Assert.NotNull(fieldToken); Assert.Equal(cookieToken.SecurityToken, fieldToken.SecurityToken); - Assert.False(fieldToken.IsSessionToken); + Assert.False(fieldToken.IsCookieToken); Assert.Equal("my-username", fieldToken.Username); Assert.Null(fieldToken.ClaimUid); Assert.Empty(fieldToken.AdditionalData); @@ -194,7 +194,7 @@ namespace Microsoft.AspNet.Antiforgery // Arrange var cookieToken = new AntiforgeryToken() { - IsSessionToken = false + IsCookieToken = false }; var tokenProvider = new DefaultAntiforgeryTokenGenerator( @@ -230,7 +230,7 @@ namespace Microsoft.AspNet.Antiforgery // Arrange var cookieToken = new AntiforgeryToken() { - IsSessionToken = true + IsCookieToken = true }; var tokenProvider = new DefaultAntiforgeryTokenGenerator( @@ -246,13 +246,13 @@ namespace Microsoft.AspNet.Antiforgery [Fact] - public void ValidateTokens_SessionTokenMissing() + public void ValidateTokens_CookieTokenMissing() { // Arrange var httpContext = new DefaultHttpContext(); httpContext.User = new ClaimsPrincipal(new ClaimsIdentity()); - var fieldtoken = new AntiforgeryToken() { IsSessionToken = false }; + var fieldtoken = new AntiforgeryToken() { IsCookieToken = false }; var tokenProvider = new DefaultAntiforgeryTokenGenerator( claimUidExtractor: null, @@ -263,7 +263,7 @@ namespace Microsoft.AspNet.Antiforgery () => tokenProvider.ValidateTokens(httpContext, null, fieldtoken)); var trimmed = ex.Message.Substring(0, ex.Message.IndexOf(Environment.NewLine)); - Assert.Equal(@"The cookie token must be provided.", trimmed); + Assert.Equal(@"The required antiforgery cookie token must be provided.", trimmed); } [Fact] @@ -273,7 +273,7 @@ namespace Microsoft.AspNet.Antiforgery var httpContext = new DefaultHttpContext(); httpContext.User = new ClaimsPrincipal(new ClaimsIdentity()); - var sessionToken = new AntiforgeryToken() { IsSessionToken = true }; + var cookieToken = new AntiforgeryToken() { IsCookieToken = true }; var tokenProvider = new DefaultAntiforgeryTokenGenerator( claimUidExtractor: null, @@ -281,21 +281,21 @@ namespace Microsoft.AspNet.Antiforgery // Act & assert var ex = Assert.Throws( - () => tokenProvider.ValidateTokens(httpContext, sessionToken, null)); + () => tokenProvider.ValidateTokens(httpContext, cookieToken, null)); var trimmed = ex.Message.Substring(0, ex.Message.IndexOf(Environment.NewLine)); - Assert.Equal("The form token must be provided.", trimmed); + Assert.Equal("The required antiforgery request token must be provided.", trimmed); } [Fact] - public void ValidateTokens_FieldAndSessionTokensSwapped() + public void ValidateTokens_FieldAndCookieTokensSwapped() { // Arrange var httpContext = new DefaultHttpContext(); httpContext.User = new ClaimsPrincipal(new ClaimsIdentity()); - var sessionToken = new AntiforgeryToken() { IsSessionToken = true }; - var fieldtoken = new AntiforgeryToken() { IsSessionToken = false }; + var cookieToken = new AntiforgeryToken() { IsCookieToken = true }; + var fieldtoken = new AntiforgeryToken() { IsCookieToken = false }; var tokenProvider = new DefaultAntiforgeryTokenGenerator( claimUidExtractor: null, @@ -307,27 +307,27 @@ namespace Microsoft.AspNet.Antiforgery () => tokenProvider.ValidateTokens(httpContext, fieldtoken, fieldtoken)); Assert.Equal( "Validation of the provided antiforgery token failed. " + - @"The cookie token and the form token were swapped.", + @"The cookie token and the request token were swapped.", ex1.Message); var ex2 = Assert.Throws( - () => tokenProvider.ValidateTokens(httpContext, sessionToken, sessionToken)); + () => tokenProvider.ValidateTokens(httpContext, cookieToken, cookieToken)); Assert.Equal( "Validation of the provided antiforgery token failed. " + - @"The cookie token and the form token were swapped.", + @"The cookie token and the request token were swapped.", ex2.Message); } [Fact] - public void ValidateTokens_FieldAndSessionTokensHaveDifferentSecurityKeys() + public void ValidateTokens_FieldAndCookieTokensHaveDifferentSecurityKeys() { // Arrange var httpContext = new DefaultHttpContext(); httpContext.User = new ClaimsPrincipal(new ClaimsIdentity()); - var sessionToken = new AntiforgeryToken() { IsSessionToken = true }; - var fieldtoken = new AntiforgeryToken() { IsSessionToken = false }; + var cookieToken = new AntiforgeryToken() { IsCookieToken = true }; + var fieldtoken = new AntiforgeryToken() { IsCookieToken = false }; var tokenProvider = new DefaultAntiforgeryTokenGenerator( claimUidExtractor: null, @@ -335,9 +335,9 @@ namespace Microsoft.AspNet.Antiforgery // Act & Assert var exception = Assert.Throws( - () => tokenProvider.ValidateTokens(httpContext, sessionToken, fieldtoken)); + () => tokenProvider.ValidateTokens(httpContext, cookieToken, fieldtoken)); Assert.Equal( - @"The antiforgery cookie token and form field token do not match.", + @"The antiforgery cookie token and request token do not match.", exception.Message); } @@ -352,12 +352,12 @@ namespace Microsoft.AspNet.Antiforgery var identity = GetAuthenticatedIdentity(identityUsername); httpContext.User = new ClaimsPrincipal(identity); - var sessionToken = new AntiforgeryToken() { IsSessionToken = true }; + var cookieToken = new AntiforgeryToken() { IsCookieToken = true }; var fieldtoken = new AntiforgeryToken() { - SecurityToken = sessionToken.SecurityToken, + SecurityToken = cookieToken.SecurityToken, Username = embeddedUsername, - IsSessionToken = false + IsCookieToken = false }; var mockClaimUidExtractor = new Mock(); @@ -370,7 +370,7 @@ namespace Microsoft.AspNet.Antiforgery // Act & Assert var exception = Assert.Throws( - () => tokenProvider.ValidateTokens(httpContext, sessionToken, fieldtoken)); + () => tokenProvider.ValidateTokens(httpContext, cookieToken, fieldtoken)); Assert.Equal( @"The provided antiforgery token was meant for user """ + embeddedUsername + @""", but the current user is """ + identityUsername + @""".", @@ -385,11 +385,11 @@ namespace Microsoft.AspNet.Antiforgery var identity = GetAuthenticatedIdentity("the-user"); httpContext.User = new ClaimsPrincipal(identity); - var sessionToken = new AntiforgeryToken() { IsSessionToken = true }; + var cookieToken = new AntiforgeryToken() { IsCookieToken = true }; var fieldtoken = new AntiforgeryToken() { - SecurityToken = sessionToken.SecurityToken, - IsSessionToken = false, + SecurityToken = cookieToken.SecurityToken, + IsCookieToken = false, ClaimUid = new BinaryBlob(256) }; @@ -404,7 +404,7 @@ namespace Microsoft.AspNet.Antiforgery // Act & assert var exception = Assert.Throws( - () => tokenProvider.ValidateTokens(httpContext, sessionToken, fieldtoken)); + () => tokenProvider.ValidateTokens(httpContext, cookieToken, fieldtoken)); Assert.Equal( @"The provided antiforgery token was meant for a different claims-based user than the current user.", exception.Message); @@ -418,12 +418,12 @@ namespace Microsoft.AspNet.Antiforgery var identity = new ClaimsIdentity(); httpContext.User = new ClaimsPrincipal(identity); - var sessionToken = new AntiforgeryToken() { IsSessionToken = true }; + var cookieToken = new AntiforgeryToken() { IsCookieToken = true }; var fieldtoken = new AntiforgeryToken() { - SecurityToken = sessionToken.SecurityToken, + SecurityToken = cookieToken.SecurityToken, Username = String.Empty, - IsSessionToken = false, + IsCookieToken = false, AdditionalData = "some-additional-data" }; @@ -437,7 +437,7 @@ namespace Microsoft.AspNet.Antiforgery // Act & assert var exception = Assert.Throws( - () => tokenProvider.ValidateTokens(httpContext, sessionToken, fieldtoken)); + () => tokenProvider.ValidateTokens(httpContext, cookieToken, fieldtoken)); Assert.Equal(@"The provided antiforgery token failed a custom data check.", exception.Message); } @@ -449,12 +449,12 @@ namespace Microsoft.AspNet.Antiforgery var identity = new ClaimsIdentity(); httpContext.User = new ClaimsPrincipal(identity); - var sessionToken = new AntiforgeryToken() { IsSessionToken = true }; + var cookieToken = new AntiforgeryToken() { IsCookieToken = true }; var fieldtoken = new AntiforgeryToken() { - SecurityToken = sessionToken.SecurityToken, + SecurityToken = cookieToken.SecurityToken, Username = String.Empty, - IsSessionToken = false, + IsCookieToken = false, AdditionalData = "some-additional-data" }; @@ -467,7 +467,7 @@ namespace Microsoft.AspNet.Antiforgery additionalDataProvider: mockAdditionalDataProvider.Object); // Act - tokenProvider.ValidateTokens(httpContext, sessionToken, fieldtoken); + tokenProvider.ValidateTokens(httpContext, cookieToken, fieldtoken); // Assert // Nothing to assert - if we got this far, success! @@ -481,12 +481,12 @@ namespace Microsoft.AspNet.Antiforgery var identity = GetAuthenticatedIdentity("the-user"); httpContext.User = new ClaimsPrincipal(identity); - var sessionToken = new AntiforgeryToken() { IsSessionToken = true }; + var cookieToken = new AntiforgeryToken() { IsCookieToken = true }; var fieldtoken = new AntiforgeryToken() { - SecurityToken = sessionToken.SecurityToken, + SecurityToken = cookieToken.SecurityToken, Username = "THE-USER", - IsSessionToken = false, + IsCookieToken = false, AdditionalData = "some-additional-data" }; @@ -499,7 +499,7 @@ namespace Microsoft.AspNet.Antiforgery additionalDataProvider: mockAdditionalDataProvider.Object); // Act - tokenProvider.ValidateTokens(httpContext, sessionToken, fieldtoken); + tokenProvider.ValidateTokens(httpContext, cookieToken, fieldtoken); // Assert // Nothing to assert - if we got this far, success! @@ -513,11 +513,11 @@ namespace Microsoft.AspNet.Antiforgery var identity = GetAuthenticatedIdentity("the-user"); httpContext.User = new ClaimsPrincipal(identity); - var sessionToken = new AntiforgeryToken() { IsSessionToken = true }; + var cookieToken = new AntiforgeryToken() { IsCookieToken = true }; var fieldtoken = new AntiforgeryToken() { - SecurityToken = sessionToken.SecurityToken, - IsSessionToken = false, + SecurityToken = cookieToken.SecurityToken, + IsCookieToken = false, ClaimUid = new BinaryBlob(256) }; @@ -530,7 +530,7 @@ namespace Microsoft.AspNet.Antiforgery additionalDataProvider: null); // Act - tokenProvider.ValidateTokens(httpContext, sessionToken, fieldtoken); + tokenProvider.ValidateTokens(httpContext, cookieToken, fieldtoken); // Assert // Nothing to assert - if we got this far, success! diff --git a/test/Microsoft.AspNet.Antiforgery.Test/DefaultAntiforgeryTokenSerializerTest.cs b/test/Microsoft.AspNet.Antiforgery.Test/DefaultAntiforgeryTokenSerializerTest.cs index 0c074a2b13..a6012bcbe7 100644 --- a/test/Microsoft.AspNet.Antiforgery.Test/DefaultAntiforgeryTokenSerializerTest.cs +++ b/test/Microsoft.AspNet.Antiforgery.Test/DefaultAntiforgeryTokenSerializerTest.cs @@ -26,18 +26,18 @@ namespace Microsoft.AspNet.Antiforgery [InlineData( "01" // Version + "705EEDCC7D42F1D6B3B98A593625BB4C" // SecurityToken - + "01" // IsSessionToken + + "01" // IsCookieToken + "00" // (WRONG!) Too much data in stream )] [InlineData( "02" // (WRONG! - must be 0x01) Version + "705EEDCC7D42F1D6B3B98A593625BB4C" // SecurityToken - + "01" // IsSessionToken + + "01" // IsCookieToken )] [InlineData( "01" // Version + "705EEDCC7D42F1D6B3B98A593625BB4C" // SecurityToken - + "00" // IsSessionToken + + "00" // IsCookieToken + "00" // IsClaimsBased + "05" // Username length header + "0000" // (WRONG!) Too little data in stream @@ -60,7 +60,7 @@ namespace Microsoft.AspNet.Antiforgery //"01" // Version //+ "705EEDCC7D42F1D6B3B98A593625BB4C" // SecurityToken - //+ "00" // IsSessionToken + //+ "00" // IsCookieToken //+ "01" // IsClaimsBased //+ "6F1648E97249AA58754036A67E248CF044F07ECFB0ED387556CE029A4F9A40E0" // ClaimUid //+ "05" // AdditionalData length header @@ -68,7 +68,7 @@ namespace Microsoft.AspNet.Antiforgery var token = new AntiforgeryToken() { SecurityToken = _securityToken, - IsSessionToken = false, + IsCookieToken = false, ClaimUid = _claimUid, AdditionalData = "€47" }; @@ -90,7 +90,7 @@ namespace Microsoft.AspNet.Antiforgery //"01" // Version //+ "705EEDCC7D42F1D6B3B98A593625BB4C" // SecurityToken - //+ "00" // IsSessionToken + //+ "00" // IsCookieToken //+ "00" // IsClaimsBased //+ "08" // Username length header //+ "4AC3A972C3B46D65" // Username ("Jérôme") as UTF8 @@ -99,7 +99,7 @@ namespace Microsoft.AspNet.Antiforgery var token = new AntiforgeryToken() { SecurityToken = _securityToken, - IsSessionToken = false, + IsCookieToken = false, Username = "Jérôme", AdditionalData = "€47" }; @@ -114,18 +114,18 @@ namespace Microsoft.AspNet.Antiforgery } [Fact] - public void Serialize_SessionToken_TokenRoundTripSuccessful() + public void Serialize_CookieToken_TokenRoundTripSuccessful() { // Arrange var testSerializer = new DefaultAntiforgeryTokenSerializer(_dataProtector.Object); //"01" // Version //+ "705EEDCC7D42F1D6B3B98A593625BB4C" // SecurityToken - //+ "01"; // IsSessionToken + //+ "01"; // IsCookieToken var token = new AntiforgeryToken() { SecurityToken = _securityToken, - IsSessionToken = true + IsCookieToken = true }; // Act @@ -178,7 +178,7 @@ namespace Microsoft.AspNet.Antiforgery Assert.NotNull(actual); Assert.Equal(expected.AdditionalData, actual.AdditionalData); Assert.Equal(expected.ClaimUid, actual.ClaimUid); - Assert.Equal(expected.IsSessionToken, actual.IsSessionToken); + Assert.Equal(expected.IsCookieToken, actual.IsCookieToken); Assert.Equal(expected.SecurityToken, actual.SecurityToken); Assert.Equal(expected.Username, actual.Username); } diff --git a/test/Microsoft.AspNet.Antiforgery.Test/DefaultAntiforgeryTokenStoreTest.cs b/test/Microsoft.AspNet.Antiforgery.Test/DefaultAntiforgeryTokenStoreTest.cs index 275632ab4f..585c42e171 100644 --- a/test/Microsoft.AspNet.Antiforgery.Test/DefaultAntiforgeryTokenStoreTest.cs +++ b/test/Microsoft.AspNet.Antiforgery.Test/DefaultAntiforgeryTokenStoreTest.cs @@ -187,7 +187,7 @@ namespace Microsoft.AspNet.Antiforgery } [Fact] - public async Task GetRequestTokens_NonFormContentType_Throws() + public async Task GetRequestTokens_NonFormContentType_HeaderDisabled_Throws() { // Arrange var httpContext = new DefaultHttpContext(); @@ -204,6 +204,7 @@ namespace Microsoft.AspNet.Antiforgery { CookieName = "cookie-name", FormFieldName = "form-field-name", + HeaderName = null, }; var tokenStore = new DefaultAntiforgeryTokenStore( @@ -219,7 +220,110 @@ namespace Microsoft.AspNet.Antiforgery } [Fact] - public async Task GetRequestTokens_FormFieldIsEmpty_Throws() + public async Task GetRequestTokens_FormContentType_FallbackHeaderToken() + { + // Arrange + var httpContext = new DefaultHttpContext(); + httpContext.Request.ContentType = "application/json"; + + // Will not be accessed + httpContext.Request.ContentType = "application/x-www-form-urlencoded"; + httpContext.Request.Form = new FormCollection(new Dictionary()); + httpContext.Request.Cookies = new RequestCookieCollection(new Dictionary() + { + { "cookie-name", "cookie-value" }, + }); + httpContext.Request.Headers.Add("header-name", "header-value"); + + var options = new AntiforgeryOptions() + { + CookieName = "cookie-name", + FormFieldName = "form-field-name", + HeaderName = "header-name", + }; + + var tokenStore = new DefaultAntiforgeryTokenStore( + optionsAccessor: new TestOptionsManager(options), + tokenSerializer: new DefaultAntiforgeryTokenSerializer(new EphemeralDataProtectionProvider())); + + // Act + var tokens = await tokenStore.GetRequestTokensAsync(httpContext); + + // Assert + Assert.Equal("cookie-value", tokens.CookieToken); + Assert.Equal("header-value", tokens.RequestToken); + } + + [Fact] + public async Task GetRequestTokens_NonFormContentType_UsesHeaderToken() + { + // Arrange + var httpContext = new DefaultHttpContext(); + httpContext.Request.ContentType = "application/json"; + + // Will not be accessed + httpContext.Request.Form = null; + httpContext.Request.Cookies = new RequestCookieCollection(new Dictionary() + { + { "cookie-name", "cookie-value" }, + }); + + httpContext.Request.Headers.Add("header-name", "header-value"); + + var options = new AntiforgeryOptions() + { + CookieName = "cookie-name", + FormFieldName = "form-field-name", + HeaderName = "header-name", + }; + + var tokenStore = new DefaultAntiforgeryTokenStore( + optionsAccessor: new TestOptionsManager(options), + tokenSerializer: new DefaultAntiforgeryTokenSerializer(new EphemeralDataProtectionProvider())); + + // Act + var tokens = await tokenStore.GetRequestTokensAsync(httpContext); + + // Assert + Assert.Equal("cookie-value", tokens.CookieToken); + Assert.Equal("header-value", tokens.RequestToken); + } + + [Fact] + public async Task GetRequestTokens_NonFormContentType_UsesHeaderToken_ThrowsOnMissingValue() + { + // Arrange + var httpContext = new DefaultHttpContext(); + httpContext.Request.ContentType = "application/json"; + + // Will not be accessed + httpContext.Request.Form = null; + httpContext.Request.Cookies = new RequestCookieCollection(new Dictionary() + { + { "cookie-name", "cookie-value" }, + }); + + var options = new AntiforgeryOptions() + { + CookieName = "cookie-name", + FormFieldName = "form-field-name", + HeaderName = "header-name", + }; + + var tokenStore = new DefaultAntiforgeryTokenStore( + optionsAccessor: new TestOptionsManager(options), + tokenSerializer: new DefaultAntiforgeryTokenSerializer(new EphemeralDataProtectionProvider())); + + // Act + var exception = await Assert.ThrowsAsync( + async () => await tokenStore.GetRequestTokensAsync(httpContext)); + + // Assert + Assert.Equal("The required antiforgery header value \"header-name\" is not present.", exception.Message); + } + + [Fact] + public async Task GetRequestTokens_BothFieldsEmpty_Throws() { // Arrange var httpContext = new DefaultHttpContext(); @@ -234,6 +338,7 @@ namespace Microsoft.AspNet.Antiforgery { CookieName = "cookie-name", FormFieldName = "form-field-name", + HeaderName = "header-name", }; var tokenStore = new DefaultAntiforgeryTokenStore( @@ -245,7 +350,10 @@ namespace Microsoft.AspNet.Antiforgery async () => await tokenStore.GetRequestTokensAsync(httpContext)); // Assert - Assert.Equal("The required antiforgery form field \"form-field-name\" is not present.", exception.Message); + Assert.Equal( + "The required antiforgery request token was not provided in either form field \"form-field-name\" " + + "or header value \"header-name\".", + exception.Message); } [Fact] @@ -262,11 +370,13 @@ namespace Microsoft.AspNet.Antiforgery { { "cookie-name", "cookie-value" }, }); + httpContext.Request.Headers.Add("header-name", "header-value"); // form value has priority. var options = new AntiforgeryOptions() { CookieName = "cookie-name", FormFieldName = "form-field-name", + HeaderName = "header-name", }; var tokenStore = new DefaultAntiforgeryTokenStore( @@ -278,7 +388,7 @@ namespace Microsoft.AspNet.Antiforgery // Assert Assert.Equal("cookie-value", tokens.CookieToken); - Assert.Equal("form-value", tokens.FormToken); + Assert.Equal("form-value", tokens.RequestToken); } [Theory] From ea43ce1bb7e227576b8c156fa6611a52424d3507 Mon Sep 17 00:00:00 2001 From: Ryan Nowak Date: Wed, 16 Dec 2015 12:38:21 -0800 Subject: [PATCH 057/296] update gitignore --- .gitignore | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/.gitignore b/.gitignore index 321d03f03c..648eae61cf 100644 --- a/.gitignore +++ b/.gitignore @@ -8,13 +8,17 @@ packages/ artifacts/ PublishProfiles/ .vs/ +bower_components/ +node_modules/ +**/wwwroot/lib/ +debugSettings.json +project.lock.json *.user *.suo *.cache *.docstates _ReSharper.* nuget.exe -project.lock.json *net45.csproj *net451.csproj *k10.csproj @@ -26,4 +30,8 @@ project.lock.json *.ncrunchsolution *.*sdf *.ipch -launchSettings.json \ No newline at end of file +.settings +*.sln.ide +node_modules +**/[Cc]ompiler/[Rr]esources/**/*.js +*launchSettings.json \ No newline at end of file From bf6406bc2a9127c11c41b2ef048ee527a8be871c Mon Sep 17 00:00:00 2001 From: Ryan Nowak Date: Wed, 16 Dec 2015 12:48:03 -0800 Subject: [PATCH 058/296] PR feedback --- .../AntiforgeryOptions.cs | 9 ++------- .../DefaultAntiforgeryTokenGenerator.cs | 17 ++++++++--------- 2 files changed, 10 insertions(+), 16 deletions(-) diff --git a/src/Microsoft.AspNet.Antiforgery/AntiforgeryOptions.cs b/src/Microsoft.AspNet.Antiforgery/AntiforgeryOptions.cs index 2308e36699..49656dd068 100644 --- a/src/Microsoft.AspNet.Antiforgery/AntiforgeryOptions.cs +++ b/src/Microsoft.AspNet.Antiforgery/AntiforgeryOptions.cs @@ -11,10 +11,9 @@ namespace Microsoft.AspNet.Antiforgery public class AntiforgeryOptions { private const string AntiforgeryTokenFieldName = "__RequestVerificationToken"; - private const string AntiforgertyTokenHeaderName = "RequestVerificationToken"; + private const string AntiforgeryTokenHeaderName = "RequestVerificationToken"; private string _cookieName; - private string _headerName = AntiforgertyTokenHeaderName; private string _formFieldName = AntiforgeryTokenFieldName; /// @@ -64,11 +63,7 @@ namespace Microsoft.AspNet.Antiforgery /// Specifies the name of the header value that is used by the antiforgery system. If null then /// antiforgery validation will only consider form data. /// - public string HeaderName - { - get { return _headerName; } - set { _headerName = value; } - } + public string HeaderName { get; set; } = AntiforgeryTokenHeaderName; /// /// Specifies whether SSL is required for the antiforgery system diff --git a/src/Microsoft.AspNet.Antiforgery/DefaultAntiforgeryTokenGenerator.cs b/src/Microsoft.AspNet.Antiforgery/DefaultAntiforgeryTokenGenerator.cs index 32a2581f71..8cd2160238 100644 --- a/src/Microsoft.AspNet.Antiforgery/DefaultAntiforgeryTokenGenerator.cs +++ b/src/Microsoft.AspNet.Antiforgery/DefaultAntiforgeryTokenGenerator.cs @@ -123,7 +123,7 @@ namespace Microsoft.AspNet.Antiforgery } // Are the security tokens embedded in each incoming token identical? - if (!Equals(cookieToken.SecurityToken, requestToken.SecurityToken)) + if (!object.Equals(cookieToken.SecurityToken, requestToken.SecurityToken)) { throw new InvalidOperationException(Resources.AntiforgeryToken_SecurityTokenMismatch); } @@ -144,15 +144,14 @@ namespace Microsoft.AspNet.Antiforgery // OpenID and other similar authentication schemes use URIs for the username. // These should be treated as case-sensitive. - var useCaseSensitiveUsernameComparison = - currentUsername.StartsWith("http://", StringComparison.OrdinalIgnoreCase) || - currentUsername.StartsWith("https://", StringComparison.OrdinalIgnoreCase); + var comparer = StringComparer.OrdinalIgnoreCase; + if (currentUsername.StartsWith("http://", StringComparison.OrdinalIgnoreCase) || + currentUsername.StartsWith("https://", StringComparison.OrdinalIgnoreCase)) + { + comparer = StringComparer.Ordinal; + } - if (!string.Equals(requestToken.Username, - currentUsername, - (useCaseSensitiveUsernameComparison) ? - StringComparison.Ordinal : - StringComparison.OrdinalIgnoreCase)) + if (!comparer.Equals(requestToken.Username, currentUsername)) { throw new InvalidOperationException( Resources.FormatAntiforgeryToken_UsernameMismatch(requestToken.Username, currentUsername)); From 1c0996c625dd7f8212d3fa4893dd7f6529a924f9 Mon Sep 17 00:00:00 2001 From: Ryan Nowak Date: Tue, 15 Dec 2015 13:49:32 -0800 Subject: [PATCH 059/296] Add a sample demonstrating Antiforgery with AJAX --- .../FormPostSampleMiddleware.cs | 66 ------------------- samples/AntiforgerySample/Startup.cs | 57 +++++++++++++++- samples/AntiforgerySample/TodoItem.cs | 13 ++++ samples/AntiforgerySample/TodoRepository.cs | 31 +++++++++ samples/AntiforgerySample/bower.json | 8 +++ samples/AntiforgerySample/gulpfile.js | 18 +++++ samples/AntiforgerySample/package.json | 13 ++++ samples/AntiforgerySample/project.json | 20 +++--- samples/AntiforgerySample/wwwroot/Index.html | 45 +++++++++++-- samples/AntiforgerySample/wwwroot/app.js | 4 ++ .../AntiforgerySample/wwwroot/controllers.js | 21 ++++++ samples/AntiforgerySample/wwwroot/favicon.ico | 1 - samples/AntiforgerySample/wwwroot/services.js | 22 +++++++ .../ServiceCollectionExtensions.cs | 9 +-- 14 files changed, 241 insertions(+), 87 deletions(-) delete mode 100644 samples/AntiforgerySample/FormPostSampleMiddleware.cs create mode 100644 samples/AntiforgerySample/TodoItem.cs create mode 100644 samples/AntiforgerySample/TodoRepository.cs create mode 100644 samples/AntiforgerySample/bower.json create mode 100644 samples/AntiforgerySample/gulpfile.js create mode 100644 samples/AntiforgerySample/package.json create mode 100644 samples/AntiforgerySample/wwwroot/app.js create mode 100644 samples/AntiforgerySample/wwwroot/controllers.js delete mode 100644 samples/AntiforgerySample/wwwroot/favicon.ico create mode 100644 samples/AntiforgerySample/wwwroot/services.js diff --git a/samples/AntiforgerySample/FormPostSampleMiddleware.cs b/samples/AntiforgerySample/FormPostSampleMiddleware.cs deleted file mode 100644 index ef0a8a5421..0000000000 --- a/samples/AntiforgerySample/FormPostSampleMiddleware.cs +++ /dev/null @@ -1,66 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System.Threading.Tasks; -using Microsoft.AspNet.Antiforgery; -using Microsoft.AspNet.Builder; -using Microsoft.AspNet.Http; -using Microsoft.Extensions.OptionsModel; - -namespace AntiforgerySample -{ - public class FormPostSampleMiddleware - { - private readonly IAntiforgery _antiforgery; - private readonly AntiforgeryOptions _options; - private readonly RequestDelegate _next; - - public FormPostSampleMiddleware( - RequestDelegate next, - IAntiforgery antiforgery, - IOptions options) - { - _next = next; - _antiforgery = antiforgery; - _options = options.Value; - } - - public async Task Invoke(HttpContext context) - { - if (context.Request.Method == "GET") - { - var page = -@" - -
- - -
- -"; - - var tokenSet = _antiforgery.GetAndStoreTokens(context); - await context.Response.WriteAsync(string.Format(page, _options.FormFieldName, tokenSet.RequestToken)); - } - else if (context.Request.Method == "POST") - { - // This will throw if invalid. - await _antiforgery.ValidateRequestAsync(context); - - var page = -@" - -

Everything is fine

-

Try Again

- - -"; - await context.Response.WriteAsync(page); - } - else - { - await _next(context); - } - } - } -} diff --git a/samples/AntiforgerySample/Startup.cs b/samples/AntiforgerySample/Startup.cs index 6fef43186c..7920eb3c6d 100644 --- a/samples/AntiforgerySample/Startup.cs +++ b/samples/AntiforgerySample/Startup.cs @@ -1,8 +1,15 @@ // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. +using System; +using System.IO; +using Microsoft.AspNet.Antiforgery; using Microsoft.AspNet.Builder; +using Microsoft.AspNet.Http; +using Microsoft.AspNet.Routing; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.OptionsModel; +using Newtonsoft.Json; namespace AntiforgerySample { @@ -10,13 +17,57 @@ namespace AntiforgerySample { public void ConfigureServices(IServiceCollection services) { - services.AddAntiforgery(); + services.AddRouting(); + + // Angular's default header name for sending the XSRF token. + services.AddAntiforgery(options => options.HeaderName = "X-XSRF-TOKEN"); + + services.AddSingleton(); } - public void Configure(IApplicationBuilder app) + public void Configure(IApplicationBuilder app, IAntiforgery antiforgery, IOptions options, TodoRepository repository) { + app.Use(next => context => + { + if ( + string.Equals(context.Request.Path.Value, "/", StringComparison.OrdinalIgnoreCase) || + string.Equals(context.Request.Path.Value, "/index.html", StringComparison.OrdinalIgnoreCase)) + { + // We can send the request token as a JavaScript-readable cookie, and Angular will use it by default. + var tokens = antiforgery.GetAndStoreTokens(context); + context.Response.Cookies.Append("XSRF-TOKEN", tokens.RequestToken, new CookieOptions() { HttpOnly = false }); + } + + return next(context); + }); + + app.UseDefaultFiles(); app.UseStaticFiles(); - app.UseMiddleware(); + + var routes = new RouteBuilder(app); + + routes.MapGet("api/items", (HttpContext context) => + { + var items = repository.GetItems(); + return context.Response.WriteAsync(JsonConvert.SerializeObject(items)); + }); + + routes.MapPost("api/items", async (HttpContext context) => + { + // This will throw if the token is invalid. + await antiforgery.ValidateRequestAsync(context); + + var serializer = new JsonSerializer(); + using (var reader = new JsonTextReader(new StreamReader(context.Request.Body))) + { + var item = serializer.Deserialize(reader); + repository.Add(item); + } + + context.Response.StatusCode = 204; + }); + + app.UseRouter(routes.Build()); } } } diff --git a/samples/AntiforgerySample/TodoItem.cs b/samples/AntiforgerySample/TodoItem.cs new file mode 100644 index 0000000000..e58adb37ad --- /dev/null +++ b/samples/AntiforgerySample/TodoItem.cs @@ -0,0 +1,13 @@ +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using Newtonsoft.Json; + +namespace AntiforgerySample +{ + public class TodoItem + { + [JsonProperty(PropertyName = "name")] + public string Name { get; set; } + } +} diff --git a/samples/AntiforgerySample/TodoRepository.cs b/samples/AntiforgerySample/TodoRepository.cs new file mode 100644 index 0000000000..8625882c0a --- /dev/null +++ b/samples/AntiforgerySample/TodoRepository.cs @@ -0,0 +1,31 @@ +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System.Collections.Generic; + +namespace AntiforgerySample +{ + public class TodoRepository + { + private List _items; + + public TodoRepository() + { + _items = new List() + { + new TodoItem() { Name = "Mow the lawn" }, + new TodoItem() { Name = "Do the dishes" }, + }; + } + + public IEnumerable GetItems() + { + return _items; + } + + public void Add(TodoItem item) + { + _items.Add(item); + } + } +} diff --git a/samples/AntiforgerySample/bower.json b/samples/AntiforgerySample/bower.json new file mode 100644 index 0000000000..89471a5f27 --- /dev/null +++ b/samples/AntiforgerySample/bower.json @@ -0,0 +1,8 @@ +{ + "name": "ASP.NET", + "private": true, + "dependencies": { + "angular": "~1.4.8", + "bootstrap-css": "~3.3.4" + } +} diff --git a/samples/AntiforgerySample/gulpfile.js b/samples/AntiforgerySample/gulpfile.js new file mode 100644 index 0000000000..dedfea6f45 --- /dev/null +++ b/samples/AntiforgerySample/gulpfile.js @@ -0,0 +1,18 @@ +/// +"use strict"; + +var gulp = require("gulp"), + bowerFiles = require('main-bower-files'); + +var paths = { + webroot: "./wwwroot/" +}; + +paths.bowerFilesDest = paths.webroot + '/bower_components'; + +gulp.task("copy:bower", function () { + return gulp.src(bowerFiles()).pipe(gulp.dest(paths.bowerFilesDest)); +}); + +gulp.task("default", ["copy:bower"]); + diff --git a/samples/AntiforgerySample/package.json b/samples/AntiforgerySample/package.json new file mode 100644 index 0000000000..e3693fbdb7 --- /dev/null +++ b/samples/AntiforgerySample/package.json @@ -0,0 +1,13 @@ +{ + "name": "ASP.NET", + "private": true, + "version": "0.0.0", + "devDependencies": { + "gulp": "^3.9.0", + "gulp-concat": "^2.6.0", + "gulp-cssmin": "^0.1.7", + "gulp-uglify": "^1.5.1", + "main-bower-files": "^2.9.0", + "rimraf": "^2.4.4" + } +} diff --git a/samples/AntiforgerySample/project.json b/samples/AntiforgerySample/project.json index 34f061b15b..0bd3d43bb3 100644 --- a/samples/AntiforgerySample/project.json +++ b/samples/AntiforgerySample/project.json @@ -1,15 +1,17 @@ -{ +{ "webroot": "wwwroot", "version": "1.0.0-*", - "dependencies": { - "Microsoft.AspNet.Antiforgery": "1.0.0-*", - "Microsoft.AspNet.Http.Extensions": "1.0.0-*", - "Microsoft.AspNet.Server.IIS": "1.0.0-*", - "Microsoft.AspNet.Server.Kestrel": "1.0.0-*", - "Microsoft.AspNet.Server.WebListener": "1.0.0-*", - "Microsoft.AspNet.StaticFiles": "1.0.0-*" - }, + "dependencies": { + "Microsoft.AspNet.Antiforgery": "1.0.0-*", + "Microsoft.AspNet.Http.Abstractions": "1.0.0-rc2-16062", + "Microsoft.AspNet.Http.Extensions": "1.0.0-*", + "Microsoft.AspNet.Routing.Extensions": "1.0.0-*", + "Microsoft.AspNet.Server.Kestrel": "1.0.0-*", + "Microsoft.AspNet.Server.WebListener": "1.0.0-*", + "Microsoft.AspNet.StaticFiles": "1.0.0-*", + "Newtonsoft.Json": "7.0.1" + }, "commands": { "kestrel": "Microsoft.AspNet.Hosting --server Microsoft.AspNet.Server.Kestrel --server.urls http://localhost:5000", diff --git a/samples/AntiforgerySample/wwwroot/Index.html b/samples/AntiforgerySample/wwwroot/Index.html index 94edeefc78..b9a1fc0182 100644 --- a/samples/AntiforgerySample/wwwroot/Index.html +++ b/samples/AntiforgerySample/wwwroot/Index.html @@ -1,10 +1,47 @@  - + + - Antiforgery Sample + Todo List Antiforgery Sample + - -

Hello, World!

+ +
+
+

Todo List Antiforgery Sample

+
+
+
+ + + + + + + + + + +
TODO List
{{$index + 1}} + {{item.name}} +
+
+
+
+
+
+ + +
+ +
+
+
+ + + + + \ No newline at end of file diff --git a/samples/AntiforgerySample/wwwroot/app.js b/samples/AntiforgerySample/wwwroot/app.js new file mode 100644 index 0000000000..f57425a553 --- /dev/null +++ b/samples/AntiforgerySample/wwwroot/app.js @@ -0,0 +1,4 @@ +angular.module('TODO', [ + 'TODO.controllers', + 'TODO.services' +]); \ No newline at end of file diff --git a/samples/AntiforgerySample/wwwroot/controllers.js b/samples/AntiforgerySample/wwwroot/controllers.js new file mode 100644 index 0000000000..df35c5cab0 --- /dev/null +++ b/samples/AntiforgerySample/wwwroot/controllers.js @@ -0,0 +1,21 @@ +angular.module('TODO.controllers', []). +controller('todoController', function ($scope, todoApi) { + $scope.itemList = []; + $scope.item = {}; + + $scope.refresh = function (item) { + todoApi.getItems().success(function (response) { + $scope.itemList = response; + }); + }; + + $scope.create = function (item) { + todoApi.create(item).success(function (response) { + $scope.item = {}; + $scope.refresh(); + }); + }; + + // Load initial items + $scope.refresh(); +}); \ No newline at end of file diff --git a/samples/AntiforgerySample/wwwroot/favicon.ico b/samples/AntiforgerySample/wwwroot/favicon.ico deleted file mode 100644 index 5f282702bb..0000000000 --- a/samples/AntiforgerySample/wwwroot/favicon.ico +++ /dev/null @@ -1 +0,0 @@ - \ No newline at end of file diff --git a/samples/AntiforgerySample/wwwroot/services.js b/samples/AntiforgerySample/wwwroot/services.js new file mode 100644 index 0000000000..be27281ba6 --- /dev/null +++ b/samples/AntiforgerySample/wwwroot/services.js @@ -0,0 +1,22 @@ +angular.module('TODO.services', []). + factory('todoApi', function ($http) { + + var todoApi = {}; + + todoApi.getItems = function () { + return $http({ + method: 'GET', + url: '/api/items' + }); + } + + todoApi.create = function (item) { + return $http({ + method: 'POST', + url: '/api/items', + data: item + }); + }; + + return todoApi; + }); \ No newline at end of file diff --git a/src/Microsoft.AspNet.Antiforgery/ServiceCollectionExtensions.cs b/src/Microsoft.AspNet.Antiforgery/ServiceCollectionExtensions.cs index f728cdb40f..fc4839eb03 100644 --- a/src/Microsoft.AspNet.Antiforgery/ServiceCollectionExtensions.cs +++ b/src/Microsoft.AspNet.Antiforgery/ServiceCollectionExtensions.cs @@ -33,7 +33,7 @@ namespace Microsoft.Extensions.DependencyInjection return services; } - public static IServiceCollection ConfigureAntiforgery( + public static IServiceCollection AddAntiforgery( this IServiceCollection services, Action setupAction) { @@ -42,12 +42,13 @@ namespace Microsoft.Extensions.DependencyInjection throw new ArgumentNullException(nameof(services)); } - if (setupAction == null) + services.AddAntiforgery(); + + if (setupAction != null) { - throw new ArgumentNullException(nameof(setupAction)); + services.Configure(setupAction); } - services.Configure(setupAction); return services; } } From f49c218bdff8085387d1cb89b4301ae655f0dcbe Mon Sep 17 00:00:00 2001 From: John Luo Date: Thu, 17 Dec 2015 21:04:04 -0800 Subject: [PATCH 060/296] Reacting to new Hosting API --- samples/AntiforgerySample/Startup.cs | 11 +++++ samples/AntiforgerySample/hosting.json | 3 ++ samples/AntiforgerySample/project.json | 49 ++++++++++---------- samples/AntiforgerySample/wwwroot/web.config | 9 ++++ 4 files changed, 48 insertions(+), 24 deletions(-) create mode 100644 samples/AntiforgerySample/hosting.json create mode 100644 samples/AntiforgerySample/wwwroot/web.config diff --git a/samples/AntiforgerySample/Startup.cs b/samples/AntiforgerySample/Startup.cs index 7920eb3c6d..bf846c635f 100644 --- a/samples/AntiforgerySample/Startup.cs +++ b/samples/AntiforgerySample/Startup.cs @@ -5,6 +5,7 @@ using System; using System.IO; using Microsoft.AspNet.Antiforgery; using Microsoft.AspNet.Builder; +using Microsoft.AspNet.Hosting; using Microsoft.AspNet.Http; using Microsoft.AspNet.Routing; using Microsoft.Extensions.DependencyInjection; @@ -69,5 +70,15 @@ namespace AntiforgerySample app.UseRouter(routes.Build()); } + + public static void Main(string[] args) + { + var application = new WebApplicationBuilder() + .UseConfiguration(WebApplicationConfiguration.GetDefault(args)) + .UseStartup() + .Build(); + + application.Run(); + } } } diff --git a/samples/AntiforgerySample/hosting.json b/samples/AntiforgerySample/hosting.json new file mode 100644 index 0000000000..f8ef14574d --- /dev/null +++ b/samples/AntiforgerySample/hosting.json @@ -0,0 +1,3 @@ +{ + "server": "Microsoft.AspNet.Server.Kestrel" +} diff --git a/samples/AntiforgerySample/project.json b/samples/AntiforgerySample/project.json index 0bd3d43bb3..d9b8cc547d 100644 --- a/samples/AntiforgerySample/project.json +++ b/samples/AntiforgerySample/project.json @@ -1,38 +1,39 @@ { - "webroot": "wwwroot", - "version": "1.0.0-*", + "version": "1.0.0-*", "dependencies": { "Microsoft.AspNet.Antiforgery": "1.0.0-*", - "Microsoft.AspNet.Http.Abstractions": "1.0.0-rc2-16062", + "Microsoft.AspNet.Http.Abstractions": "1.0.0-*", "Microsoft.AspNet.Http.Extensions": "1.0.0-*", "Microsoft.AspNet.Routing.Extensions": "1.0.0-*", "Microsoft.AspNet.Server.Kestrel": "1.0.0-*", - "Microsoft.AspNet.Server.WebListener": "1.0.0-*", "Microsoft.AspNet.StaticFiles": "1.0.0-*", "Newtonsoft.Json": "7.0.1" }, - "commands": { - "kestrel": "Microsoft.AspNet.Hosting --server Microsoft.AspNet.Server.Kestrel --server.urls http://localhost:5000", - "web": "Microsoft.AspNet.Hosting --server Microsoft.AspNet.Server.WebListener --server.urls http://localhost:5000" - }, + "compilationOptions": { + "emitEntryPoint": true + }, - "frameworks": { - "dnx451": { }, - "dnxcore50": { } - }, + "commands": { + "web": "AntiforgerySample" + }, - "publishExclude": [ - "node_modules", - "bower_components", - "**.xproj", - "**.user", - "**.vspscc" - ], - "exclude": [ - "wwwroot", - "node_modules", - "bower_components" - ] + "frameworks": { + "dnx451": { }, + "dnxcore50": { } + }, + + "publishExclude": [ + "node_modules", + "bower_components", + "**.xproj", + "**.user", + "**.vspscc" + ], + "exclude": [ + "wwwroot", + "node_modules", + "bower_components" + ] } diff --git a/samples/AntiforgerySample/wwwroot/web.config b/samples/AntiforgerySample/wwwroot/web.config new file mode 100644 index 0000000000..9a0d90abf8 --- /dev/null +++ b/samples/AntiforgerySample/wwwroot/web.config @@ -0,0 +1,9 @@ + + + + + + + + + \ No newline at end of file From 0eec60b0ac845269108554642c76a937ccdf39ff Mon Sep 17 00:00:00 2001 From: Hao Kung Date: Mon, 21 Dec 2015 14:54:54 -0800 Subject: [PATCH 061/296] React to OptionsModel => Options --- samples/AntiforgerySample/Startup.cs | 2 +- src/Microsoft.AspNet.Antiforgery/AntiforgeryOptionsSetup.cs | 2 +- src/Microsoft.AspNet.Antiforgery/DefaultAntiforgery.cs | 2 +- .../DefaultAntiforgeryTokenStore.cs | 2 +- src/Microsoft.AspNet.Antiforgery/ServiceCollectionExtensions.cs | 2 +- .../AntiforgeryOptionsSetupTest.cs | 2 +- .../Microsoft.AspNet.Antiforgery.Test/DefaultAntiforgeryTest.cs | 2 +- test/Microsoft.AspNet.Antiforgery.Test/TestOptionsManager.cs | 2 +- 8 files changed, 8 insertions(+), 8 deletions(-) diff --git a/samples/AntiforgerySample/Startup.cs b/samples/AntiforgerySample/Startup.cs index bf846c635f..6b609f1c07 100644 --- a/samples/AntiforgerySample/Startup.cs +++ b/samples/AntiforgerySample/Startup.cs @@ -9,7 +9,7 @@ using Microsoft.AspNet.Hosting; using Microsoft.AspNet.Http; using Microsoft.AspNet.Routing; using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.OptionsModel; +using Microsoft.Extensions.Options; using Newtonsoft.Json; namespace AntiforgerySample diff --git a/src/Microsoft.AspNet.Antiforgery/AntiforgeryOptionsSetup.cs b/src/Microsoft.AspNet.Antiforgery/AntiforgeryOptionsSetup.cs index 58b38be7a6..c8dca4d39d 100644 --- a/src/Microsoft.AspNet.Antiforgery/AntiforgeryOptionsSetup.cs +++ b/src/Microsoft.AspNet.Antiforgery/AntiforgeryOptionsSetup.cs @@ -6,7 +6,7 @@ using System.Security.Cryptography; using System.Text; using Microsoft.AspNet.DataProtection; using Microsoft.AspNet.WebUtilities; -using Microsoft.Extensions.OptionsModel; +using Microsoft.Extensions.Options; namespace Microsoft.AspNet.Antiforgery { diff --git a/src/Microsoft.AspNet.Antiforgery/DefaultAntiforgery.cs b/src/Microsoft.AspNet.Antiforgery/DefaultAntiforgery.cs index 7aa43f581d..b17c3edb4c 100644 --- a/src/Microsoft.AspNet.Antiforgery/DefaultAntiforgery.cs +++ b/src/Microsoft.AspNet.Antiforgery/DefaultAntiforgery.cs @@ -6,7 +6,7 @@ using System.Diagnostics; using System.Threading.Tasks; using Microsoft.AspNet.Html; using Microsoft.AspNet.Http; -using Microsoft.Extensions.OptionsModel; +using Microsoft.Extensions.Options; namespace Microsoft.AspNet.Antiforgery { diff --git a/src/Microsoft.AspNet.Antiforgery/DefaultAntiforgeryTokenStore.cs b/src/Microsoft.AspNet.Antiforgery/DefaultAntiforgeryTokenStore.cs index 8adbd024ea..2b347a6ac8 100644 --- a/src/Microsoft.AspNet.Antiforgery/DefaultAntiforgeryTokenStore.cs +++ b/src/Microsoft.AspNet.Antiforgery/DefaultAntiforgeryTokenStore.cs @@ -6,7 +6,7 @@ using System.Diagnostics; using System.Threading.Tasks; using Microsoft.AspNet.Http; using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.OptionsModel; +using Microsoft.Extensions.Options; using Microsoft.Extensions.Primitives; namespace Microsoft.AspNet.Antiforgery diff --git a/src/Microsoft.AspNet.Antiforgery/ServiceCollectionExtensions.cs b/src/Microsoft.AspNet.Antiforgery/ServiceCollectionExtensions.cs index fc4839eb03..556647b56a 100644 --- a/src/Microsoft.AspNet.Antiforgery/ServiceCollectionExtensions.cs +++ b/src/Microsoft.AspNet.Antiforgery/ServiceCollectionExtensions.cs @@ -4,7 +4,7 @@ using System; using Microsoft.AspNet.Antiforgery; using Microsoft.Extensions.DependencyInjection.Extensions; -using Microsoft.Extensions.OptionsModel; +using Microsoft.Extensions.Options; namespace Microsoft.Extensions.DependencyInjection { diff --git a/test/Microsoft.AspNet.Antiforgery.Test/AntiforgeryOptionsSetupTest.cs b/test/Microsoft.AspNet.Antiforgery.Test/AntiforgeryOptionsSetupTest.cs index 91b9482081..5211a6b383 100644 --- a/test/Microsoft.AspNet.Antiforgery.Test/AntiforgeryOptionsSetupTest.cs +++ b/test/Microsoft.AspNet.Antiforgery.Test/AntiforgeryOptionsSetupTest.cs @@ -2,7 +2,7 @@ // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.OptionsModel; +using Microsoft.Extensions.Options; using Xunit; namespace Microsoft.AspNet.Antiforgery diff --git a/test/Microsoft.AspNet.Antiforgery.Test/DefaultAntiforgeryTest.cs b/test/Microsoft.AspNet.Antiforgery.Test/DefaultAntiforgeryTest.cs index 1a85a6826a..b5283bef2e 100644 --- a/test/Microsoft.AspNet.Antiforgery.Test/DefaultAntiforgeryTest.cs +++ b/test/Microsoft.AspNet.Antiforgery.Test/DefaultAntiforgeryTest.cs @@ -8,7 +8,7 @@ using System.Threading.Tasks; using Microsoft.AspNet.Html; using Microsoft.AspNet.Http; using Microsoft.AspNet.Http.Internal; -using Microsoft.Extensions.OptionsModel; +using Microsoft.Extensions.Options; using Microsoft.Extensions.WebEncoders.Testing; using Moq; using Xunit; diff --git a/test/Microsoft.AspNet.Antiforgery.Test/TestOptionsManager.cs b/test/Microsoft.AspNet.Antiforgery.Test/TestOptionsManager.cs index c0a47a3537..0aea27a9d9 100644 --- a/test/Microsoft.AspNet.Antiforgery.Test/TestOptionsManager.cs +++ b/test/Microsoft.AspNet.Antiforgery.Test/TestOptionsManager.cs @@ -1,7 +1,7 @@ // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. -using Microsoft.Extensions.OptionsModel; +using Microsoft.Extensions.Options; namespace Microsoft.AspNet.Antiforgery { From a281b2e3698df209a46fabeb2068b9a9505bc024 Mon Sep 17 00:00:00 2001 From: ryanbrandenburg Date: Wed, 30 Dec 2015 13:46:09 -0800 Subject: [PATCH 062/296] * Add functional tests for sample --- .bowerrc | 3 + Antiforgery.sln | 9 +- samples/AntiforgerySample/wwwroot/Index.html | 4 +- .../AntiForgerySampleTestFixture.cs | 45 +++++++++ .../AntiforgerySampleTest.cs | 98 +++++++++++++++++++ ...t.AspNet.Antiforgery.FunctionalTests.xproj | 21 ++++ .../project.json | 25 +++++ 7 files changed, 202 insertions(+), 3 deletions(-) create mode 100644 .bowerrc create mode 100644 test/Microsoft.AspNet.Antiforgery.FunctionalTests/AntiForgerySampleTestFixture.cs create mode 100644 test/Microsoft.AspNet.Antiforgery.FunctionalTests/AntiforgerySampleTest.cs create mode 100644 test/Microsoft.AspNet.Antiforgery.FunctionalTests/Microsoft.AspNet.Antiforgery.FunctionalTests.xproj create mode 100644 test/Microsoft.AspNet.Antiforgery.FunctionalTests/project.json diff --git a/.bowerrc b/.bowerrc new file mode 100644 index 0000000000..eae11312d8 --- /dev/null +++ b/.bowerrc @@ -0,0 +1,3 @@ +{ + "directory": "wwwroot/lib" +} \ No newline at end of file diff --git a/Antiforgery.sln b/Antiforgery.sln index 3074ae4f3d..48fb0ca448 100644 --- a/Antiforgery.sln +++ b/Antiforgery.sln @@ -1,7 +1,7 @@  Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio 14 -VisualStudioVersion = 14.0.22808.1 +VisualStudioVersion = 14.0.24720.0 MinimumVisualStudioVersion = 10.0.40219.1 Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{71D070C4-B325-48F7-9F25-DD4E91C2BBCA}" EndProject @@ -15,6 +15,8 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "samples", "samples", "{D8C4 EndProject Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "AntiforgerySample", "samples\AntiforgerySample\AntiforgerySample.xproj", "{AF9E0784-5EDB-494F-B46C-1A8DA785C49C}" EndProject +Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "Microsoft.AspNet.Antiforgery.FunctionalTests", "test\Microsoft.AspNet.Antiforgery.FunctionalTests\Microsoft.AspNet.Antiforgery.FunctionalTests.xproj", "{8B288810-5A96-4AF5-9836-8BA2D2953203}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -33,6 +35,10 @@ Global {AF9E0784-5EDB-494F-B46C-1A8DA785C49C}.Debug|Any CPU.Build.0 = Debug|Any CPU {AF9E0784-5EDB-494F-B46C-1A8DA785C49C}.Release|Any CPU.ActiveCfg = Release|Any CPU {AF9E0784-5EDB-494F-B46C-1A8DA785C49C}.Release|Any CPU.Build.0 = Release|Any CPU + {8B288810-5A96-4AF5-9836-8BA2D2953203}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {8B288810-5A96-4AF5-9836-8BA2D2953203}.Debug|Any CPU.Build.0 = Debug|Any CPU + {8B288810-5A96-4AF5-9836-8BA2D2953203}.Release|Any CPU.ActiveCfg = Release|Any CPU + {8B288810-5A96-4AF5-9836-8BA2D2953203}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -41,5 +47,6 @@ Global {46FB03FB-7A44-4106-BDDE-D6F5417544AB} = {71D070C4-B325-48F7-9F25-DD4E91C2BBCA} {415E83F8-6002-47E4-AA8E-CD5169C06F28} = {6EDD8B57-4DE8-4246-A6A3-47ECD92740B4} {AF9E0784-5EDB-494F-B46C-1A8DA785C49C} = {D8C46ADF-E40A-4B48-ADE9-E1FA80466FE3} + {8B288810-5A96-4AF5-9836-8BA2D2953203} = {6EDD8B57-4DE8-4246-A6A3-47ECD92740B4} EndGlobalSection EndGlobal diff --git a/samples/AntiforgerySample/wwwroot/Index.html b/samples/AntiforgerySample/wwwroot/Index.html index b9a1fc0182..7789fe514b 100644 --- a/samples/AntiforgerySample/wwwroot/Index.html +++ b/samples/AntiforgerySample/wwwroot/Index.html @@ -4,7 +4,7 @@ Todo List Antiforgery Sample - +
@@ -38,7 +38,7 @@
- + diff --git a/test/Microsoft.AspNet.Antiforgery.FunctionalTests/AntiForgerySampleTestFixture.cs b/test/Microsoft.AspNet.Antiforgery.FunctionalTests/AntiForgerySampleTestFixture.cs new file mode 100644 index 0000000000..dd43b79399 --- /dev/null +++ b/test/Microsoft.AspNet.Antiforgery.FunctionalTests/AntiForgerySampleTestFixture.cs @@ -0,0 +1,45 @@ +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System; +using System.Collections.Generic; +using System.Net.Http; +using Microsoft.AspNet.Hosting; +using Microsoft.AspNet.TestHost; +using Microsoft.Extensions.Configuration; + +namespace Microsoft.AspNet.Antiforgery.FunctionalTests +{ + public class AntiForgerySampleTestFixture : IDisposable + { + private readonly TestServer _server; + + public AntiForgerySampleTestFixture() + { + var configurationBuilder = new ConfigurationBuilder(); + + configurationBuilder.AddInMemoryCollection(new[] + { + new KeyValuePair("webroot", "wwwroot") + }); + + var builder = new WebApplicationBuilder() + .UseConfiguration(configurationBuilder.Build()) + .UseStartup(typeof(AntiforgerySample.Startup)) + .UseApplicationBasePath("../../samples/AntiforgerySample"); + + _server = new TestServer(builder); + + Client = _server.CreateClient(); + Client.BaseAddress = new Uri("http://localhost"); + } + + public HttpClient Client { get; } + + public void Dispose() + { + Client.Dispose(); + _server.Dispose(); + } + } +} diff --git a/test/Microsoft.AspNet.Antiforgery.FunctionalTests/AntiforgerySampleTest.cs b/test/Microsoft.AspNet.Antiforgery.FunctionalTests/AntiforgerySampleTest.cs new file mode 100644 index 0000000000..4135a56bd3 --- /dev/null +++ b/test/Microsoft.AspNet.Antiforgery.FunctionalTests/AntiforgerySampleTest.cs @@ -0,0 +1,98 @@ +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net; +using System.Net.Http; +using System.Threading.Tasks; +using Xunit; + +namespace Microsoft.AspNet.Antiforgery.FunctionalTests +{ + public class AntiforgerySampleTests : IClassFixture + { + public AntiforgerySampleTests(AntiForgerySampleTestFixture fixture) + { + Client = fixture.Client; + } + + public HttpClient Client { get; } + + [Fact] + public async Task ItemsPage_SetsXSRFTokens() + { + // Arrange & Act + var response = await Client.GetAsync("http://localhost/Index.html"); + + // Assert + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + + var cookie = RetrieveAntiforgeryCookie(response); + Assert.NotNull(cookie.Value); + + var token = RetrieveAntiforgeryToken(response); + Assert.NotNull(token.Value); + } + + [Fact] + public async Task PostItem_NeedsHeader() + { + // Arrange + var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, "http://localhost/api/items"); + + // Act + var exception = await Assert.ThrowsAsync(async () => + { + var response = await Client.SendAsync(httpRequestMessage); + }); + + // Assert + Assert.Contains("required antiforgery cookie", exception.Message); + } + + [Fact] + public async Task PostItem_XSRFWorks() + { + // Arrange + var content = new StringContent("{'name': 'Todoitem'}"); + var httpResponse = await Client.GetAsync("http://localhost/Index.html"); + + var cookie = RetrieveAntiforgeryCookie(httpResponse); + var token = RetrieveAntiforgeryToken(httpResponse); + + var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, "http://localhost/api/items"); + + httpRequestMessage.Headers.Add("X-XSRF-TOKEN", token.Value); + httpRequestMessage.Headers.Add("Cookie", $"{cookie.Key}={cookie.Value}"); + + // Act + var response = await Client.SendAsync(httpRequestMessage); + + // Assert + Assert.Equal(HttpStatusCode.OK, httpResponse.StatusCode); + Assert.Equal(HttpStatusCode.NoContent, response.StatusCode); + } + + private static KeyValuePair RetrieveAntiforgeryToken(HttpResponseMessage response) + { + return GetCookie(response, 1); + } + + private static KeyValuePair RetrieveAntiforgeryCookie(HttpResponseMessage response) + { + return GetCookie(response, 0); + } + + private static KeyValuePair GetCookie(HttpResponseMessage response, int index) + { + var setCookieArray = response.Headers.GetValues("Set-Cookie").ToArray(); + var cookie = setCookieArray[index].Split(';').First().Split('='); + var cookieKey = cookie[0]; + var cookieData = cookie[1]; + + return new KeyValuePair(cookieKey, cookieData); + } + } +} \ No newline at end of file diff --git a/test/Microsoft.AspNet.Antiforgery.FunctionalTests/Microsoft.AspNet.Antiforgery.FunctionalTests.xproj b/test/Microsoft.AspNet.Antiforgery.FunctionalTests/Microsoft.AspNet.Antiforgery.FunctionalTests.xproj new file mode 100644 index 0000000000..775501b0ed --- /dev/null +++ b/test/Microsoft.AspNet.Antiforgery.FunctionalTests/Microsoft.AspNet.Antiforgery.FunctionalTests.xproj @@ -0,0 +1,21 @@ + + + + 14.0.24720 + $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion) + + + + 8b288810-5a96-4af5-9836-8ba2d2953203 + FunctionalTests + ..\..\artifacts\obj\$(MSBuildProjectName) + ..\..\artifacts\bin\$(MSBuildProjectName)\ + + + 2.0 + + + + + + \ No newline at end of file diff --git a/test/Microsoft.AspNet.Antiforgery.FunctionalTests/project.json b/test/Microsoft.AspNet.Antiforgery.FunctionalTests/project.json new file mode 100644 index 0000000000..0df539fa57 --- /dev/null +++ b/test/Microsoft.AspNet.Antiforgery.FunctionalTests/project.json @@ -0,0 +1,25 @@ +{ + "dependencies": { + "AntiforgerySample": "1.0.0-*", + "Microsoft.AspNet.TestHost": "1.0.0-*", + "Microsoft.AspNet.Testing": "1.0.0-*", + "xunit.runner.aspnet": "2.0.0-aspnet-*" + }, + "commands": { + "run": "xunit.runner.aspnet", + "test": "xunit.runner.aspnet" + }, + "frameworks": { + "dnx451": { + "dependencies": { + "Moq": "4.2.1312.1622", + "System.Net.Http": "4.0.1-rc2-23621" + } + }, + "dnxcore50": { + "dependencies": { + "moq.netcore": "4.4.0-beta8" + } + } + } +} From 80fa2908bdacd6d0d45852a4264bc2873bbce2ea Mon Sep 17 00:00:00 2001 From: Ajay Bhargav Baaskaran Date: Tue, 5 Jan 2016 16:42:41 -0800 Subject: [PATCH 063/296] Throwing custom AntiforgeryException for token validation failure scenarios --- .../AntiforgeryValidationException.cs | 23 +++++++++++++++++++ .../DefaultAntiforgeryTokenGenerator.cs | 12 +++++----- .../DefaultAntiforgeryTokenStore.cs | 8 +++---- .../AntiforgerySampleTest.cs | 4 ++-- .../DefaultAntiforgeryTokenGeneratorTest.cs | 12 +++++----- .../DefaultAntiforgeryTokenStoreTest.cs | 12 +++++----- 6 files changed, 47 insertions(+), 24 deletions(-) create mode 100644 src/Microsoft.AspNet.Antiforgery/AntiforgeryValidationException.cs diff --git a/src/Microsoft.AspNet.Antiforgery/AntiforgeryValidationException.cs b/src/Microsoft.AspNet.Antiforgery/AntiforgeryValidationException.cs new file mode 100644 index 0000000000..d5ea22e52b --- /dev/null +++ b/src/Microsoft.AspNet.Antiforgery/AntiforgeryValidationException.cs @@ -0,0 +1,23 @@ +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System; + +namespace Microsoft.AspNet.Antiforgery +{ + /// + /// The that is thrown when the antiforgery token validation fails. + /// + public class AntiforgeryValidationException : Exception + { + /// + /// Creates a new instance of with the specified + /// exception . + /// + /// The message that describes the error. + public AntiforgeryValidationException(string message) + : base(message) + { + } + } +} diff --git a/src/Microsoft.AspNet.Antiforgery/DefaultAntiforgeryTokenGenerator.cs b/src/Microsoft.AspNet.Antiforgery/DefaultAntiforgeryTokenGenerator.cs index 8cd2160238..ae43f846b6 100644 --- a/src/Microsoft.AspNet.Antiforgery/DefaultAntiforgeryTokenGenerator.cs +++ b/src/Microsoft.AspNet.Antiforgery/DefaultAntiforgeryTokenGenerator.cs @@ -119,13 +119,13 @@ namespace Microsoft.AspNet.Antiforgery // Do the tokens have the correct format? if (!cookieToken.IsCookieToken || requestToken.IsCookieToken) { - throw new InvalidOperationException(Resources.AntiforgeryToken_TokensSwapped); + throw new AntiforgeryValidationException(Resources.AntiforgeryToken_TokensSwapped); } // Are the security tokens embedded in each incoming token identical? if (!object.Equals(cookieToken.SecurityToken, requestToken.SecurityToken)) { - throw new InvalidOperationException(Resources.AntiforgeryToken_SecurityTokenMismatch); + throw new AntiforgeryValidationException(Resources.AntiforgeryToken_SecurityTokenMismatch); } // Is the incoming token meant for the current user? @@ -153,20 +153,20 @@ namespace Microsoft.AspNet.Antiforgery if (!comparer.Equals(requestToken.Username, currentUsername)) { - throw new InvalidOperationException( + throw new AntiforgeryValidationException( Resources.FormatAntiforgeryToken_UsernameMismatch(requestToken.Username, currentUsername)); } - if (!Equals(requestToken.ClaimUid, currentClaimUid)) + if (!object.Equals(requestToken.ClaimUid, currentClaimUid)) { - throw new InvalidOperationException(Resources.AntiforgeryToken_ClaimUidMismatch); + throw new AntiforgeryValidationException(Resources.AntiforgeryToken_ClaimUidMismatch); } // Is the AdditionalData valid? if (_additionalDataProvider != null && !_additionalDataProvider.ValidateAdditionalData(httpContext, requestToken.AdditionalData)) { - throw new InvalidOperationException(Resources.AntiforgeryToken_AdditionalDataCheckFailed); + throw new AntiforgeryValidationException(Resources.AntiforgeryToken_AdditionalDataCheckFailed); } } diff --git a/src/Microsoft.AspNet.Antiforgery/DefaultAntiforgeryTokenStore.cs b/src/Microsoft.AspNet.Antiforgery/DefaultAntiforgeryTokenStore.cs index 2b347a6ac8..ee677af059 100644 --- a/src/Microsoft.AspNet.Antiforgery/DefaultAntiforgeryTokenStore.cs +++ b/src/Microsoft.AspNet.Antiforgery/DefaultAntiforgeryTokenStore.cs @@ -68,7 +68,7 @@ namespace Microsoft.AspNet.Antiforgery var requestCookie = httpContext.Request.Cookies[_options.CookieName]; if (string.IsNullOrEmpty(requestCookie)) { - throw new InvalidOperationException( + throw new AntiforgeryValidationException( Resources.FormatAntiforgery_CookieToken_MustBeProvided(_options.CookieName)); } @@ -92,19 +92,19 @@ namespace Microsoft.AspNet.Antiforgery if (_options.HeaderName == null) { var message = Resources.FormatAntiforgery_FormToken_MustBeProvided(_options.FormFieldName); - throw new InvalidOperationException(message); + throw new AntiforgeryValidationException(message); } else if (!httpContext.Request.HasFormContentType) { var message = Resources.FormatAntiforgery_HeaderToken_MustBeProvided(_options.HeaderName); - throw new InvalidOperationException(message); + throw new AntiforgeryValidationException(message); } else { var message = Resources.FormatAntiforgery_RequestToken_MustBeProvided( _options.FormFieldName, _options.HeaderName); - throw new InvalidOperationException(message); + throw new AntiforgeryValidationException(message); } } diff --git a/test/Microsoft.AspNet.Antiforgery.FunctionalTests/AntiforgerySampleTest.cs b/test/Microsoft.AspNet.Antiforgery.FunctionalTests/AntiforgerySampleTest.cs index 4135a56bd3..32431f6801 100644 --- a/test/Microsoft.AspNet.Antiforgery.FunctionalTests/AntiforgerySampleTest.cs +++ b/test/Microsoft.AspNet.Antiforgery.FunctionalTests/AntiforgerySampleTest.cs @@ -43,13 +43,13 @@ namespace Microsoft.AspNet.Antiforgery.FunctionalTests var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, "http://localhost/api/items"); // Act - var exception = await Assert.ThrowsAsync(async () => + var exception = await Assert.ThrowsAsync(async () => { var response = await Client.SendAsync(httpRequestMessage); }); // Assert - Assert.Contains("required antiforgery cookie", exception.Message); + Assert.Contains("The required antiforgery cookie \"3Cs-jwHTMFk\" is not present.", exception.Message); } [Fact] diff --git a/test/Microsoft.AspNet.Antiforgery.Test/DefaultAntiforgeryTokenGeneratorTest.cs b/test/Microsoft.AspNet.Antiforgery.Test/DefaultAntiforgeryTokenGeneratorTest.cs index 4813d68411..005f00f10c 100644 --- a/test/Microsoft.AspNet.Antiforgery.Test/DefaultAntiforgeryTokenGeneratorTest.cs +++ b/test/Microsoft.AspNet.Antiforgery.Test/DefaultAntiforgeryTokenGeneratorTest.cs @@ -303,7 +303,7 @@ namespace Microsoft.AspNet.Antiforgery // Act & assert var ex1 = - Assert.Throws( + Assert.Throws( () => tokenProvider.ValidateTokens(httpContext, fieldtoken, fieldtoken)); Assert.Equal( "Validation of the provided antiforgery token failed. " + @@ -311,7 +311,7 @@ namespace Microsoft.AspNet.Antiforgery ex1.Message); var ex2 = - Assert.Throws( + Assert.Throws( () => tokenProvider.ValidateTokens(httpContext, cookieToken, cookieToken)); Assert.Equal( "Validation of the provided antiforgery token failed. " + @@ -334,7 +334,7 @@ namespace Microsoft.AspNet.Antiforgery additionalDataProvider: null); // Act & Assert - var exception = Assert.Throws( + var exception = Assert.Throws( () => tokenProvider.ValidateTokens(httpContext, cookieToken, fieldtoken)); Assert.Equal( @"The antiforgery cookie token and request token do not match.", @@ -369,7 +369,7 @@ namespace Microsoft.AspNet.Antiforgery additionalDataProvider: null); // Act & Assert - var exception = Assert.Throws( + var exception = Assert.Throws( () => tokenProvider.ValidateTokens(httpContext, cookieToken, fieldtoken)); Assert.Equal( @"The provided antiforgery token was meant for user """ + embeddedUsername + @@ -403,7 +403,7 @@ namespace Microsoft.AspNet.Antiforgery additionalDataProvider: null); // Act & assert - var exception = Assert.Throws( + var exception = Assert.Throws( () => tokenProvider.ValidateTokens(httpContext, cookieToken, fieldtoken)); Assert.Equal( @"The provided antiforgery token was meant for a different claims-based user than the current user.", @@ -436,7 +436,7 @@ namespace Microsoft.AspNet.Antiforgery additionalDataProvider: mockAdditionalDataProvider.Object); // Act & assert - var exception = Assert.Throws( + var exception = Assert.Throws( () => tokenProvider.ValidateTokens(httpContext, cookieToken, fieldtoken)); Assert.Equal(@"The provided antiforgery token failed a custom data check.", exception.Message); } diff --git a/test/Microsoft.AspNet.Antiforgery.Test/DefaultAntiforgeryTokenStoreTest.cs b/test/Microsoft.AspNet.Antiforgery.Test/DefaultAntiforgeryTokenStoreTest.cs index 585c42e171..61660652ab 100644 --- a/test/Microsoft.AspNet.Antiforgery.Test/DefaultAntiforgeryTokenStoreTest.cs +++ b/test/Microsoft.AspNet.Antiforgery.Test/DefaultAntiforgeryTokenStoreTest.cs @@ -112,7 +112,7 @@ namespace Microsoft.AspNet.Antiforgery // Arrange var mockHttpContext = GetMockHttpContext(_cookieName, "invalid-value"); - var expectedException = new InvalidOperationException("some exception"); + var expectedException = new AntiforgeryValidationException("some exception"); var mockSerializer = new Mock(); mockSerializer .Setup(o => o.Deserialize("invalid-value")) @@ -128,7 +128,7 @@ namespace Microsoft.AspNet.Antiforgery tokenSerializer: mockSerializer.Object); // Act & assert - var ex = Assert.Throws(() => tokenStore.GetCookieToken(mockHttpContext)); + var ex = Assert.Throws(() => tokenStore.GetCookieToken(mockHttpContext)); Assert.Same(expectedException, ex); } @@ -179,7 +179,7 @@ namespace Microsoft.AspNet.Antiforgery tokenSerializer: Mock.Of()); // Act - var exception = await Assert.ThrowsAsync( + var exception = await Assert.ThrowsAsync( async () => await tokenStore.GetRequestTokensAsync(httpContext)); // Assert @@ -212,7 +212,7 @@ namespace Microsoft.AspNet.Antiforgery tokenSerializer: new DefaultAntiforgeryTokenSerializer(new EphemeralDataProtectionProvider())); // Act - var exception = await Assert.ThrowsAsync( + var exception = await Assert.ThrowsAsync( async () => await tokenStore.GetRequestTokensAsync(httpContext)); // Assert @@ -315,7 +315,7 @@ namespace Microsoft.AspNet.Antiforgery tokenSerializer: new DefaultAntiforgeryTokenSerializer(new EphemeralDataProtectionProvider())); // Act - var exception = await Assert.ThrowsAsync( + var exception = await Assert.ThrowsAsync( async () => await tokenStore.GetRequestTokensAsync(httpContext)); // Assert @@ -346,7 +346,7 @@ namespace Microsoft.AspNet.Antiforgery tokenSerializer: Mock.Of()); // Act - var exception = await Assert.ThrowsAsync( + var exception = await Assert.ThrowsAsync( async () => await tokenStore.GetRequestTokensAsync(httpContext)); // Assert From 807cd77307ab3f3bb9bbed77cd3acd544541a4c9 Mon Sep 17 00:00:00 2001 From: John Luo Date: Tue, 12 Jan 2016 16:03:24 -0800 Subject: [PATCH 064/296] Reacting to Hosting API changes --- samples/AntiforgerySample/Startup.cs | 1 + samples/AntiforgerySample/project.json | 1 + 2 files changed, 2 insertions(+) diff --git a/samples/AntiforgerySample/Startup.cs b/samples/AntiforgerySample/Startup.cs index 6b609f1c07..8c00c95793 100644 --- a/samples/AntiforgerySample/Startup.cs +++ b/samples/AntiforgerySample/Startup.cs @@ -75,6 +75,7 @@ namespace AntiforgerySample { var application = new WebApplicationBuilder() .UseConfiguration(WebApplicationConfiguration.GetDefault(args)) + .UseIISPlatformHandlerUrl() .UseStartup() .Build(); diff --git a/samples/AntiforgerySample/project.json b/samples/AntiforgerySample/project.json index d9b8cc547d..819ff29f70 100644 --- a/samples/AntiforgerySample/project.json +++ b/samples/AntiforgerySample/project.json @@ -5,6 +5,7 @@ "Microsoft.AspNet.Antiforgery": "1.0.0-*", "Microsoft.AspNet.Http.Abstractions": "1.0.0-*", "Microsoft.AspNet.Http.Extensions": "1.0.0-*", + "Microsoft.AspNet.IISPlatformHandler": "1.0.0-*", "Microsoft.AspNet.Routing.Extensions": "1.0.0-*", "Microsoft.AspNet.Server.Kestrel": "1.0.0-*", "Microsoft.AspNet.StaticFiles": "1.0.0-*", From 9e032102f65378a76ddaf895b7becafd21665253 Mon Sep 17 00:00:00 2001 From: Victor Hurdugaci Date: Mon, 11 Jan 2016 15:53:38 -0800 Subject: [PATCH 065/296] Build with dotnet --- .gitattributes | 1 + .gitignore | 4 +- .travis.yml | 8 ++- appveyor.yml | 2 +- build.cmd | 68 +++++++++---------- build.sh | 42 ++++++------ .../AntiForgerySampleTestFixture.cs | 2 +- .../AntiforgerySampleTest.cs | 11 ++- .../project.json | 11 +-- .../project.json | 13 ++-- 10 files changed, 87 insertions(+), 75 deletions(-) diff --git a/.gitattributes b/.gitattributes index bdaa5ba982..97b827b758 100644 --- a/.gitattributes +++ b/.gitattributes @@ -48,3 +48,4 @@ *.fsproj text=auto *.dbproj text=auto *.sln text=auto eol=crlf +*.sh eol=lf diff --git a/.gitignore b/.gitignore index 648eae61cf..980ee002d9 100644 --- a/.gitignore +++ b/.gitignore @@ -34,4 +34,6 @@ nuget.exe *.sln.ide node_modules **/[Cc]ompiler/[Rr]esources/**/*.js -*launchSettings.json \ No newline at end of file +*launchSettings.json +.build/ +.testPublish/ \ No newline at end of file diff --git a/.travis.yml b/.travis.yml index c0befaffcf..e8f77f0f14 100644 --- a/.travis.yml +++ b/.travis.yml @@ -10,9 +10,11 @@ addons: - libssl-dev - libunwind8 - zlib1g -env: - - KOREBUILD_DNU_RESTORE_CORECLR=true KOREBUILD_TEST_DNXCORE=true mono: - 4.0.5 +os: + - linux + - osx +osx_image: xcode7.1 script: - - ./build.sh --quiet verify + - ./build.sh --quiet verify \ No newline at end of file diff --git a/appveyor.yml b/appveyor.yml index 58a3e1bc22..636a7618d3 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -1,7 +1,7 @@ init: - git config --global core.autocrlf true build_script: - - build.cmd --quiet --parallel verify + - build.cmd --quiet verify clone_depth: 1 test: off deploy: off \ No newline at end of file diff --git a/build.cmd b/build.cmd index 553e3929a0..65fb3e3353 100644 --- a/build.cmd +++ b/build.cmd @@ -1,40 +1,40 @@ -@echo off -cd %~dp0 - +@ECHO off SETLOCAL + +SET REPO_FOLDER=%~dp0 +CD "%REPO_FOLDER%" + +SET BUILD_FOLDER=.build +SET KOREBUILD_FOLDER=%BUILD_FOLDER%\KoreBuild-dotnet +SET KOREBUILD_VERSION= + +SET NUGET_PATH=%BUILD_FOLDER%\NuGet.exe SET NUGET_VERSION=latest SET CACHED_NUGET=%LocalAppData%\NuGet\nuget.%NUGET_VERSION%.exe -SET BUILDCMD_KOREBUILD_VERSION= -SET BUILDCMD_DNX_VERSION= -IF EXIST %CACHED_NUGET% goto copynuget -echo Downloading latest version of NuGet.exe... -IF NOT EXIST %LocalAppData%\NuGet md %LocalAppData%\NuGet -@powershell -NoProfile -ExecutionPolicy unrestricted -Command "$ProgressPreference = 'SilentlyContinue'; Invoke-WebRequest 'https://dist.nuget.org/win-x86-commandline/%NUGET_VERSION%/nuget.exe' -OutFile '%CACHED_NUGET%'" - -:copynuget -IF EXIST .nuget\nuget.exe goto restore -md .nuget -copy %CACHED_NUGET% .nuget\nuget.exe > nul - -:restore -IF EXIST packages\Sake goto getdnx -IF "%BUILDCMD_KOREBUILD_VERSION%"=="" ( - .nuget\nuget.exe install KoreBuild -ExcludeVersion -o packages -nocache -pre -) ELSE ( - .nuget\nuget.exe install KoreBuild -version %BUILDCMD_KOREBUILD_VERSION% -ExcludeVersion -o packages -nocache -pre -) -.nuget\NuGet.exe install Sake -ExcludeVersion -Source https://www.nuget.org/api/v2/ -Out packages - -:getdnx -IF "%BUILDCMD_DNX_VERSION%"=="" ( - SET BUILDCMD_DNX_VERSION=latest -) -IF "%SKIP_DNX_INSTALL%"=="" ( - CALL packages\KoreBuild\build\dnvm install %BUILDCMD_DNX_VERSION% -runtime CoreCLR -arch x86 -alias default - CALL packages\KoreBuild\build\dnvm install default -runtime CLR -arch x86 -alias default -) ELSE ( - CALL packages\KoreBuild\build\dnvm use default -runtime CLR -arch x86 +IF NOT EXIST %BUILD_FOLDER% ( + md %BUILD_FOLDER% ) -packages\Sake\tools\Sake.exe -I packages\KoreBuild\build -f makefile.shade %* +IF NOT EXIST %NUGET_PATH% ( + IF NOT EXIST %CACHED_NUGET% ( + echo Downloading latest version of NuGet.exe... + IF NOT EXIST %LocalAppData%\NuGet ( + md %LocalAppData%\NuGet + ) + @powershell -NoProfile -ExecutionPolicy unrestricted -Command "$ProgressPreference = 'SilentlyContinue'; Invoke-WebRequest 'https://dist.nuget.org/win-x86-commandline/%NUGET_VERSION%/nuget.exe' -OutFile '%CACHED_NUGET%'" + ) + + copy %CACHED_NUGET% %NUGET_PATH% > nul +) + +IF NOT EXIST %KOREBUILD_FOLDER% ( + SET KOREBUILD_DOWNLOAD_ARGS= + IF NOT "%KOREBUILD_VERSION%"=="" ( + SET KOREBUILD_DOWNLOAD_ARGS=-version %KOREBUILD_VERSION% + ) + + %BUILD_FOLDER%\nuget.exe install KoreBuild-dotnet -ExcludeVersion -o %BUILD_FOLDER% -nocache -pre %KOREBUILD_DOWNLOAD_ARGS% +) + +"%KOREBUILD_FOLDER%\build\KoreBuild.cmd" %* diff --git a/build.sh b/build.sh index da4e3fcd1c..263fb667a8 100755 --- a/build.sh +++ b/build.sh @@ -1,5 +1,10 @@ #!/usr/bin/env bash +buildFolder=.build +koreBuildFolder=$buildFolder/KoreBuild-dotnet + +nugetPath=$buildFolder/nuget.exe + if test `uname` = Darwin; then cachedir=~/Library/Caches/KBuild else @@ -11,33 +16,30 @@ else fi mkdir -p $cachedir nugetVersion=latest -cachePath=$cachedir/nuget.$nugetVersion.exe +cacheNuget=$cachedir/nuget.$nugetVersion.exe -url=https://dist.nuget.org/win-x86-commandline/$nugetVersion/nuget.exe +nugetUrl=https://dist.nuget.org/win-x86-commandline/$nugetVersion/nuget.exe -if test ! -f $cachePath; then - wget -O $cachePath $url 2>/dev/null || curl -o $cachePath --location $url /dev/null +if test ! -d $buildFolder; then + mkdir $buildFolder fi -if test ! -e .nuget; then - mkdir .nuget - cp $cachePath .nuget/nuget.exe +if test ! -f $nugetPath; then + if test ! -f $cacheNuget; then + wget -O $cacheNuget $nugetUrl 2>/dev/null || curl -o $cacheNuget --location $nugetUrl /dev/null + fi + + cp $cacheNuget $nugetPath fi -if test ! -d packages/Sake; then - mono .nuget/nuget.exe install KoreBuild -ExcludeVersion -o packages -nocache -pre - mono .nuget/nuget.exe install Sake -ExcludeVersion -Source https://www.nuget.org/api/v2/ -Out packages +if test ! -d $koreBuildFolder; then + mono $nugetPath install KoreBuild-dotnet -ExcludeVersion -o $buildFolder -nocache -pre + chmod +x $koreBuildFolder/build/KoreBuild.sh fi -if ! type dnvm > /dev/null 2>&1; then - source packages/KoreBuild/build/dnvm.sh +makeFile=makefile.shade +if [ ! -e $makeFile ]; then + makeFile=$koreBuildFolder/build/makefile.shade fi -if ! type dnx > /dev/null 2>&1 || [ -z "$SKIP_DNX_INSTALL" ]; then - dnvm install latest -runtime coreclr -alias default - dnvm install default -runtime mono -alias default -else - dnvm use default -runtime mono -fi - -mono packages/Sake/tools/Sake.exe -I packages/KoreBuild/build -f makefile.shade "$@" +./$koreBuildFolder/build/KoreBuild.sh -n $nugetPath -m $makeFile "$@" diff --git a/test/Microsoft.AspNet.Antiforgery.FunctionalTests/AntiForgerySampleTestFixture.cs b/test/Microsoft.AspNet.Antiforgery.FunctionalTests/AntiForgerySampleTestFixture.cs index dd43b79399..7e77232ed4 100644 --- a/test/Microsoft.AspNet.Antiforgery.FunctionalTests/AntiForgerySampleTestFixture.cs +++ b/test/Microsoft.AspNet.Antiforgery.FunctionalTests/AntiForgerySampleTestFixture.cs @@ -26,7 +26,7 @@ namespace Microsoft.AspNet.Antiforgery.FunctionalTests var builder = new WebApplicationBuilder() .UseConfiguration(configurationBuilder.Build()) .UseStartup(typeof(AntiforgerySample.Startup)) - .UseApplicationBasePath("../../samples/AntiforgerySample"); + .UseApplicationBasePath("../../../../samples/AntiforgerySample"); _server = new TestServer(builder); diff --git a/test/Microsoft.AspNet.Antiforgery.FunctionalTests/AntiforgerySampleTest.cs b/test/Microsoft.AspNet.Antiforgery.FunctionalTests/AntiforgerySampleTest.cs index 32431f6801..72926809ad 100644 --- a/test/Microsoft.AspNet.Antiforgery.FunctionalTests/AntiforgerySampleTest.cs +++ b/test/Microsoft.AspNet.Antiforgery.FunctionalTests/AntiforgerySampleTest.cs @@ -27,8 +27,6 @@ namespace Microsoft.AspNet.Antiforgery.FunctionalTests var response = await Client.GetAsync("http://localhost/Index.html"); // Assert - Assert.Equal(HttpStatusCode.OK, response.StatusCode); - var cookie = RetrieveAntiforgeryCookie(response); Assert.NotNull(cookie.Value); @@ -40,6 +38,9 @@ namespace Microsoft.AspNet.Antiforgery.FunctionalTests public async Task PostItem_NeedsHeader() { // Arrange + var httpResponse = await Client.GetAsync("http://localhost"); + var cookie = RetrieveAntiforgeryCookie(httpResponse); + var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, "http://localhost/api/items"); // Act @@ -49,15 +50,14 @@ namespace Microsoft.AspNet.Antiforgery.FunctionalTests }); // Assert - Assert.Contains("The required antiforgery cookie \"3Cs-jwHTMFk\" is not present.", exception.Message); + Assert.Contains($"The required antiforgery cookie \"{cookie.Key}\" is not present.", exception.Message); } [Fact] public async Task PostItem_XSRFWorks() { // Arrange - var content = new StringContent("{'name': 'Todoitem'}"); - var httpResponse = await Client.GetAsync("http://localhost/Index.html"); + var httpResponse = await Client.GetAsync("/Index.html"); var cookie = RetrieveAntiforgeryCookie(httpResponse); var token = RetrieveAntiforgeryToken(httpResponse); @@ -71,7 +71,6 @@ namespace Microsoft.AspNet.Antiforgery.FunctionalTests var response = await Client.SendAsync(httpRequestMessage); // Assert - Assert.Equal(HttpStatusCode.OK, httpResponse.StatusCode); Assert.Equal(HttpStatusCode.NoContent, response.StatusCode); } diff --git a/test/Microsoft.AspNet.Antiforgery.FunctionalTests/project.json b/test/Microsoft.AspNet.Antiforgery.FunctionalTests/project.json index 0df539fa57..572352d718 100644 --- a/test/Microsoft.AspNet.Antiforgery.FunctionalTests/project.json +++ b/test/Microsoft.AspNet.Antiforgery.FunctionalTests/project.json @@ -2,23 +2,24 @@ "dependencies": { "AntiforgerySample": "1.0.0-*", "Microsoft.AspNet.TestHost": "1.0.0-*", - "Microsoft.AspNet.Testing": "1.0.0-*", - "xunit.runner.aspnet": "2.0.0-aspnet-*" + "Microsoft.AspNet.Testing": "1.0.0-*" }, + "testRunner": "xunit", "commands": { - "run": "xunit.runner.aspnet", "test": "xunit.runner.aspnet" }, "frameworks": { "dnx451": { "dependencies": { "Moq": "4.2.1312.1622", - "System.Net.Http": "4.0.1-rc2-23621" + "System.Net.Http": "4.0.1-rc2-23621", + "xunit.runner.console": "2.1.0" } }, "dnxcore50": { "dependencies": { - "moq.netcore": "4.4.0-beta8" + "moq.netcore": "4.4.0-beta8", + "xunit.runner.aspnet": "2.0.0-aspnet-*" } } } diff --git a/test/Microsoft.AspNet.Antiforgery.Test/project.json b/test/Microsoft.AspNet.Antiforgery.Test/project.json index a9bab13140..2669aae1e5 100644 --- a/test/Microsoft.AspNet.Antiforgery.Test/project.json +++ b/test/Microsoft.AspNet.Antiforgery.Test/project.json @@ -8,21 +8,26 @@ "Microsoft.AspNet.Http": "1.0.0-*", "Microsoft.Extensions.DependencyInjection": "1.0.0-*", "Microsoft.Extensions.WebEncoders": "1.0.0-*", - "xunit.runner.aspnet": "2.0.0-aspnet-*" + "xunit": "2.1.0-*" }, + "testRunner": "xunit", "commands": { - "run": "xunit.runner.aspnet", "test": "xunit.runner.aspnet" }, "frameworks": { "dnx451": { + "frameworkAssemblies": { + "System.Threading.Tasks": "" + }, "dependencies": { - "Moq": "4.2.1312.1622" + "Moq": "4.2.1312.1622", + "xunit.runner.console": "2.1.0" } }, "dnxcore50": { "dependencies": { - "moq.netcore": "4.4.0-beta8" + "moq.netcore": "4.4.0-beta8", + "xunit.runner.aspnet": "2.0.0-aspnet-*" } } } From 115e89d6f87a5257a525887812fa107a1ddaa3cb Mon Sep 17 00:00:00 2001 From: John Luo Date: Sun, 17 Jan 2016 17:08:20 -0800 Subject: [PATCH 066/296] Reacting to hosting rename --- samples/AntiforgerySample/Startup.cs | 6 +++--- .../AntiForgerySampleTestFixture.cs | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/samples/AntiforgerySample/Startup.cs b/samples/AntiforgerySample/Startup.cs index 8c00c95793..e2f548fc75 100644 --- a/samples/AntiforgerySample/Startup.cs +++ b/samples/AntiforgerySample/Startup.cs @@ -73,13 +73,13 @@ namespace AntiforgerySample public static void Main(string[] args) { - var application = new WebApplicationBuilder() - .UseConfiguration(WebApplicationConfiguration.GetDefault(args)) + var host = new WebHostBuilder() + .UseDefaultConfiguration(args) .UseIISPlatformHandlerUrl() .UseStartup() .Build(); - application.Run(); + host.Run(); } } } diff --git a/test/Microsoft.AspNet.Antiforgery.FunctionalTests/AntiForgerySampleTestFixture.cs b/test/Microsoft.AspNet.Antiforgery.FunctionalTests/AntiForgerySampleTestFixture.cs index 7e77232ed4..fbdb3e0ea9 100644 --- a/test/Microsoft.AspNet.Antiforgery.FunctionalTests/AntiForgerySampleTestFixture.cs +++ b/test/Microsoft.AspNet.Antiforgery.FunctionalTests/AntiForgerySampleTestFixture.cs @@ -23,7 +23,7 @@ namespace Microsoft.AspNet.Antiforgery.FunctionalTests new KeyValuePair("webroot", "wwwroot") }); - var builder = new WebApplicationBuilder() + var builder = new WebHostBuilder() .UseConfiguration(configurationBuilder.Build()) .UseStartup(typeof(AntiforgerySample.Startup)) .UseApplicationBasePath("../../../../samples/AntiforgerySample"); From bc0d5528a3cc210c13d41a7db05df0dc1afedcc9 Mon Sep 17 00:00:00 2001 From: "N. Taylor Mullen" Date: Fri, 22 Jan 2016 12:24:19 -0800 Subject: [PATCH 067/296] Rename AspNet 5 folders and files. See https://github.com/aspnet/Announcements/issues/144 for more information. --- .../AntiforgeryContext.cs | 0 .../AntiforgeryOptions.cs | 0 .../AntiforgeryOptionsSetup.cs | 0 .../AntiforgeryToken.cs | 0 .../AntiforgeryTokenSet.cs | 0 .../AntiforgeryValidationException.cs | 0 .../BinaryBlob.cs | 0 .../DefaultAntiforgery.cs | 0 .../DefaultAntiforgeryAdditionalDataProvider.cs | 0 .../DefaultAntiforgeryContextAccessor.cs | 0 .../DefaultAntiforgeryTokenGenerator.cs | 0 .../DefaultAntiforgeryTokenSerializer.cs | 0 .../DefaultAntiforgeryTokenStore.cs | 0 .../DefaultClaimUidExtractor.cs | 0 .../IAntiforgery.cs | 0 .../IAntiforgeryAdditionalDataProvider.cs | 0 .../IAntiforgeryContextAccessor.cs | 0 .../IAntiforgeryTokenGenerator.cs | 0 .../IAntiforgeryTokenSerializer.cs | 0 .../IAntiforgeryTokenStore.cs | 0 .../IClaimUidExtractor.cs | 0 .../Microsoft.AspNetCore.Antiforgery.xproj} | 0 .../Properties/AssemblyInfo.cs | 0 .../Properties/Resources.Designer.cs | 0 .../Resources.resx | 0 .../ServiceCollectionExtensions.cs | 0 .../project.json | 0 .../AntiForgerySampleTestFixture.cs | 0 .../AntiforgerySampleTest.cs | 0 .../Microsoft.AspNetCore.Antiforgery.FunctionalTests.xproj} | 0 .../project.json | 0 .../AntiforgeryOptionsSetupTest.cs | 0 .../AntiforgeryTokenTest.cs | 0 .../BinaryBlobTest.cs | 0 .../DefaultAntiforgeryTest.cs | 0 .../DefaultAntiforgeryTokenGeneratorTest.cs | 0 .../DefaultAntiforgeryTokenSerializerTest.cs | 0 .../DefaultAntiforgeryTokenStoreTest.cs | 0 .../DefaultClaimUidExtractorTest.cs | 0 .../Microsoft.AspNetCore.Antiforgery.Test.xproj} | 0 .../TestOptionsManager.cs | 0 .../project.json | 0 42 files changed, 0 insertions(+), 0 deletions(-) rename src/{Microsoft.AspNet.Antiforgery => Microsoft.AspNetCore.Antiforgery}/AntiforgeryContext.cs (100%) rename src/{Microsoft.AspNet.Antiforgery => Microsoft.AspNetCore.Antiforgery}/AntiforgeryOptions.cs (100%) rename src/{Microsoft.AspNet.Antiforgery => Microsoft.AspNetCore.Antiforgery}/AntiforgeryOptionsSetup.cs (100%) rename src/{Microsoft.AspNet.Antiforgery => Microsoft.AspNetCore.Antiforgery}/AntiforgeryToken.cs (100%) rename src/{Microsoft.AspNet.Antiforgery => Microsoft.AspNetCore.Antiforgery}/AntiforgeryTokenSet.cs (100%) rename src/{Microsoft.AspNet.Antiforgery => Microsoft.AspNetCore.Antiforgery}/AntiforgeryValidationException.cs (100%) rename src/{Microsoft.AspNet.Antiforgery => Microsoft.AspNetCore.Antiforgery}/BinaryBlob.cs (100%) rename src/{Microsoft.AspNet.Antiforgery => Microsoft.AspNetCore.Antiforgery}/DefaultAntiforgery.cs (100%) rename src/{Microsoft.AspNet.Antiforgery => Microsoft.AspNetCore.Antiforgery}/DefaultAntiforgeryAdditionalDataProvider.cs (100%) rename src/{Microsoft.AspNet.Antiforgery => Microsoft.AspNetCore.Antiforgery}/DefaultAntiforgeryContextAccessor.cs (100%) rename src/{Microsoft.AspNet.Antiforgery => Microsoft.AspNetCore.Antiforgery}/DefaultAntiforgeryTokenGenerator.cs (100%) rename src/{Microsoft.AspNet.Antiforgery => Microsoft.AspNetCore.Antiforgery}/DefaultAntiforgeryTokenSerializer.cs (100%) rename src/{Microsoft.AspNet.Antiforgery => Microsoft.AspNetCore.Antiforgery}/DefaultAntiforgeryTokenStore.cs (100%) rename src/{Microsoft.AspNet.Antiforgery => Microsoft.AspNetCore.Antiforgery}/DefaultClaimUidExtractor.cs (100%) rename src/{Microsoft.AspNet.Antiforgery => Microsoft.AspNetCore.Antiforgery}/IAntiforgery.cs (100%) rename src/{Microsoft.AspNet.Antiforgery => Microsoft.AspNetCore.Antiforgery}/IAntiforgeryAdditionalDataProvider.cs (100%) rename src/{Microsoft.AspNet.Antiforgery => Microsoft.AspNetCore.Antiforgery}/IAntiforgeryContextAccessor.cs (100%) rename src/{Microsoft.AspNet.Antiforgery => Microsoft.AspNetCore.Antiforgery}/IAntiforgeryTokenGenerator.cs (100%) rename src/{Microsoft.AspNet.Antiforgery => Microsoft.AspNetCore.Antiforgery}/IAntiforgeryTokenSerializer.cs (100%) rename src/{Microsoft.AspNet.Antiforgery => Microsoft.AspNetCore.Antiforgery}/IAntiforgeryTokenStore.cs (100%) rename src/{Microsoft.AspNet.Antiforgery => Microsoft.AspNetCore.Antiforgery}/IClaimUidExtractor.cs (100%) rename src/{Microsoft.AspNet.Antiforgery/Microsoft.AspNet.Antiforgery.xproj => Microsoft.AspNetCore.Antiforgery/Microsoft.AspNetCore.Antiforgery.xproj} (100%) rename src/{Microsoft.AspNet.Antiforgery => Microsoft.AspNetCore.Antiforgery}/Properties/AssemblyInfo.cs (100%) rename src/{Microsoft.AspNet.Antiforgery => Microsoft.AspNetCore.Antiforgery}/Properties/Resources.Designer.cs (100%) rename src/{Microsoft.AspNet.Antiforgery => Microsoft.AspNetCore.Antiforgery}/Resources.resx (100%) rename src/{Microsoft.AspNet.Antiforgery => Microsoft.AspNetCore.Antiforgery}/ServiceCollectionExtensions.cs (100%) rename src/{Microsoft.AspNet.Antiforgery => Microsoft.AspNetCore.Antiforgery}/project.json (100%) rename test/{Microsoft.AspNet.Antiforgery.FunctionalTests => Microsoft.AspNetCore.Antiforgery.FunctionalTests}/AntiForgerySampleTestFixture.cs (100%) rename test/{Microsoft.AspNet.Antiforgery.FunctionalTests => Microsoft.AspNetCore.Antiforgery.FunctionalTests}/AntiforgerySampleTest.cs (100%) rename test/{Microsoft.AspNet.Antiforgery.FunctionalTests/Microsoft.AspNet.Antiforgery.FunctionalTests.xproj => Microsoft.AspNetCore.Antiforgery.FunctionalTests/Microsoft.AspNetCore.Antiforgery.FunctionalTests.xproj} (100%) rename test/{Microsoft.AspNet.Antiforgery.FunctionalTests => Microsoft.AspNetCore.Antiforgery.FunctionalTests}/project.json (100%) rename test/{Microsoft.AspNet.Antiforgery.Test => Microsoft.AspNetCore.Antiforgery.Test}/AntiforgeryOptionsSetupTest.cs (100%) rename test/{Microsoft.AspNet.Antiforgery.Test => Microsoft.AspNetCore.Antiforgery.Test}/AntiforgeryTokenTest.cs (100%) rename test/{Microsoft.AspNet.Antiforgery.Test => Microsoft.AspNetCore.Antiforgery.Test}/BinaryBlobTest.cs (100%) rename test/{Microsoft.AspNet.Antiforgery.Test => Microsoft.AspNetCore.Antiforgery.Test}/DefaultAntiforgeryTest.cs (100%) rename test/{Microsoft.AspNet.Antiforgery.Test => Microsoft.AspNetCore.Antiforgery.Test}/DefaultAntiforgeryTokenGeneratorTest.cs (100%) rename test/{Microsoft.AspNet.Antiforgery.Test => Microsoft.AspNetCore.Antiforgery.Test}/DefaultAntiforgeryTokenSerializerTest.cs (100%) rename test/{Microsoft.AspNet.Antiforgery.Test => Microsoft.AspNetCore.Antiforgery.Test}/DefaultAntiforgeryTokenStoreTest.cs (100%) rename test/{Microsoft.AspNet.Antiforgery.Test => Microsoft.AspNetCore.Antiforgery.Test}/DefaultClaimUidExtractorTest.cs (100%) rename test/{Microsoft.AspNet.Antiforgery.Test/Microsoft.AspNet.Antiforgery.Test.xproj => Microsoft.AspNetCore.Antiforgery.Test/Microsoft.AspNetCore.Antiforgery.Test.xproj} (100%) rename test/{Microsoft.AspNet.Antiforgery.Test => Microsoft.AspNetCore.Antiforgery.Test}/TestOptionsManager.cs (100%) rename test/{Microsoft.AspNet.Antiforgery.Test => Microsoft.AspNetCore.Antiforgery.Test}/project.json (100%) diff --git a/src/Microsoft.AspNet.Antiforgery/AntiforgeryContext.cs b/src/Microsoft.AspNetCore.Antiforgery/AntiforgeryContext.cs similarity index 100% rename from src/Microsoft.AspNet.Antiforgery/AntiforgeryContext.cs rename to src/Microsoft.AspNetCore.Antiforgery/AntiforgeryContext.cs diff --git a/src/Microsoft.AspNet.Antiforgery/AntiforgeryOptions.cs b/src/Microsoft.AspNetCore.Antiforgery/AntiforgeryOptions.cs similarity index 100% rename from src/Microsoft.AspNet.Antiforgery/AntiforgeryOptions.cs rename to src/Microsoft.AspNetCore.Antiforgery/AntiforgeryOptions.cs diff --git a/src/Microsoft.AspNet.Antiforgery/AntiforgeryOptionsSetup.cs b/src/Microsoft.AspNetCore.Antiforgery/AntiforgeryOptionsSetup.cs similarity index 100% rename from src/Microsoft.AspNet.Antiforgery/AntiforgeryOptionsSetup.cs rename to src/Microsoft.AspNetCore.Antiforgery/AntiforgeryOptionsSetup.cs diff --git a/src/Microsoft.AspNet.Antiforgery/AntiforgeryToken.cs b/src/Microsoft.AspNetCore.Antiforgery/AntiforgeryToken.cs similarity index 100% rename from src/Microsoft.AspNet.Antiforgery/AntiforgeryToken.cs rename to src/Microsoft.AspNetCore.Antiforgery/AntiforgeryToken.cs diff --git a/src/Microsoft.AspNet.Antiforgery/AntiforgeryTokenSet.cs b/src/Microsoft.AspNetCore.Antiforgery/AntiforgeryTokenSet.cs similarity index 100% rename from src/Microsoft.AspNet.Antiforgery/AntiforgeryTokenSet.cs rename to src/Microsoft.AspNetCore.Antiforgery/AntiforgeryTokenSet.cs diff --git a/src/Microsoft.AspNet.Antiforgery/AntiforgeryValidationException.cs b/src/Microsoft.AspNetCore.Antiforgery/AntiforgeryValidationException.cs similarity index 100% rename from src/Microsoft.AspNet.Antiforgery/AntiforgeryValidationException.cs rename to src/Microsoft.AspNetCore.Antiforgery/AntiforgeryValidationException.cs diff --git a/src/Microsoft.AspNet.Antiforgery/BinaryBlob.cs b/src/Microsoft.AspNetCore.Antiforgery/BinaryBlob.cs similarity index 100% rename from src/Microsoft.AspNet.Antiforgery/BinaryBlob.cs rename to src/Microsoft.AspNetCore.Antiforgery/BinaryBlob.cs diff --git a/src/Microsoft.AspNet.Antiforgery/DefaultAntiforgery.cs b/src/Microsoft.AspNetCore.Antiforgery/DefaultAntiforgery.cs similarity index 100% rename from src/Microsoft.AspNet.Antiforgery/DefaultAntiforgery.cs rename to src/Microsoft.AspNetCore.Antiforgery/DefaultAntiforgery.cs diff --git a/src/Microsoft.AspNet.Antiforgery/DefaultAntiforgeryAdditionalDataProvider.cs b/src/Microsoft.AspNetCore.Antiforgery/DefaultAntiforgeryAdditionalDataProvider.cs similarity index 100% rename from src/Microsoft.AspNet.Antiforgery/DefaultAntiforgeryAdditionalDataProvider.cs rename to src/Microsoft.AspNetCore.Antiforgery/DefaultAntiforgeryAdditionalDataProvider.cs diff --git a/src/Microsoft.AspNet.Antiforgery/DefaultAntiforgeryContextAccessor.cs b/src/Microsoft.AspNetCore.Antiforgery/DefaultAntiforgeryContextAccessor.cs similarity index 100% rename from src/Microsoft.AspNet.Antiforgery/DefaultAntiforgeryContextAccessor.cs rename to src/Microsoft.AspNetCore.Antiforgery/DefaultAntiforgeryContextAccessor.cs diff --git a/src/Microsoft.AspNet.Antiforgery/DefaultAntiforgeryTokenGenerator.cs b/src/Microsoft.AspNetCore.Antiforgery/DefaultAntiforgeryTokenGenerator.cs similarity index 100% rename from src/Microsoft.AspNet.Antiforgery/DefaultAntiforgeryTokenGenerator.cs rename to src/Microsoft.AspNetCore.Antiforgery/DefaultAntiforgeryTokenGenerator.cs diff --git a/src/Microsoft.AspNet.Antiforgery/DefaultAntiforgeryTokenSerializer.cs b/src/Microsoft.AspNetCore.Antiforgery/DefaultAntiforgeryTokenSerializer.cs similarity index 100% rename from src/Microsoft.AspNet.Antiforgery/DefaultAntiforgeryTokenSerializer.cs rename to src/Microsoft.AspNetCore.Antiforgery/DefaultAntiforgeryTokenSerializer.cs diff --git a/src/Microsoft.AspNet.Antiforgery/DefaultAntiforgeryTokenStore.cs b/src/Microsoft.AspNetCore.Antiforgery/DefaultAntiforgeryTokenStore.cs similarity index 100% rename from src/Microsoft.AspNet.Antiforgery/DefaultAntiforgeryTokenStore.cs rename to src/Microsoft.AspNetCore.Antiforgery/DefaultAntiforgeryTokenStore.cs diff --git a/src/Microsoft.AspNet.Antiforgery/DefaultClaimUidExtractor.cs b/src/Microsoft.AspNetCore.Antiforgery/DefaultClaimUidExtractor.cs similarity index 100% rename from src/Microsoft.AspNet.Antiforgery/DefaultClaimUidExtractor.cs rename to src/Microsoft.AspNetCore.Antiforgery/DefaultClaimUidExtractor.cs diff --git a/src/Microsoft.AspNet.Antiforgery/IAntiforgery.cs b/src/Microsoft.AspNetCore.Antiforgery/IAntiforgery.cs similarity index 100% rename from src/Microsoft.AspNet.Antiforgery/IAntiforgery.cs rename to src/Microsoft.AspNetCore.Antiforgery/IAntiforgery.cs diff --git a/src/Microsoft.AspNet.Antiforgery/IAntiforgeryAdditionalDataProvider.cs b/src/Microsoft.AspNetCore.Antiforgery/IAntiforgeryAdditionalDataProvider.cs similarity index 100% rename from src/Microsoft.AspNet.Antiforgery/IAntiforgeryAdditionalDataProvider.cs rename to src/Microsoft.AspNetCore.Antiforgery/IAntiforgeryAdditionalDataProvider.cs diff --git a/src/Microsoft.AspNet.Antiforgery/IAntiforgeryContextAccessor.cs b/src/Microsoft.AspNetCore.Antiforgery/IAntiforgeryContextAccessor.cs similarity index 100% rename from src/Microsoft.AspNet.Antiforgery/IAntiforgeryContextAccessor.cs rename to src/Microsoft.AspNetCore.Antiforgery/IAntiforgeryContextAccessor.cs diff --git a/src/Microsoft.AspNet.Antiforgery/IAntiforgeryTokenGenerator.cs b/src/Microsoft.AspNetCore.Antiforgery/IAntiforgeryTokenGenerator.cs similarity index 100% rename from src/Microsoft.AspNet.Antiforgery/IAntiforgeryTokenGenerator.cs rename to src/Microsoft.AspNetCore.Antiforgery/IAntiforgeryTokenGenerator.cs diff --git a/src/Microsoft.AspNet.Antiforgery/IAntiforgeryTokenSerializer.cs b/src/Microsoft.AspNetCore.Antiforgery/IAntiforgeryTokenSerializer.cs similarity index 100% rename from src/Microsoft.AspNet.Antiforgery/IAntiforgeryTokenSerializer.cs rename to src/Microsoft.AspNetCore.Antiforgery/IAntiforgeryTokenSerializer.cs diff --git a/src/Microsoft.AspNet.Antiforgery/IAntiforgeryTokenStore.cs b/src/Microsoft.AspNetCore.Antiforgery/IAntiforgeryTokenStore.cs similarity index 100% rename from src/Microsoft.AspNet.Antiforgery/IAntiforgeryTokenStore.cs rename to src/Microsoft.AspNetCore.Antiforgery/IAntiforgeryTokenStore.cs diff --git a/src/Microsoft.AspNet.Antiforgery/IClaimUidExtractor.cs b/src/Microsoft.AspNetCore.Antiforgery/IClaimUidExtractor.cs similarity index 100% rename from src/Microsoft.AspNet.Antiforgery/IClaimUidExtractor.cs rename to src/Microsoft.AspNetCore.Antiforgery/IClaimUidExtractor.cs diff --git a/src/Microsoft.AspNet.Antiforgery/Microsoft.AspNet.Antiforgery.xproj b/src/Microsoft.AspNetCore.Antiforgery/Microsoft.AspNetCore.Antiforgery.xproj similarity index 100% rename from src/Microsoft.AspNet.Antiforgery/Microsoft.AspNet.Antiforgery.xproj rename to src/Microsoft.AspNetCore.Antiforgery/Microsoft.AspNetCore.Antiforgery.xproj diff --git a/src/Microsoft.AspNet.Antiforgery/Properties/AssemblyInfo.cs b/src/Microsoft.AspNetCore.Antiforgery/Properties/AssemblyInfo.cs similarity index 100% rename from src/Microsoft.AspNet.Antiforgery/Properties/AssemblyInfo.cs rename to src/Microsoft.AspNetCore.Antiforgery/Properties/AssemblyInfo.cs diff --git a/src/Microsoft.AspNet.Antiforgery/Properties/Resources.Designer.cs b/src/Microsoft.AspNetCore.Antiforgery/Properties/Resources.Designer.cs similarity index 100% rename from src/Microsoft.AspNet.Antiforgery/Properties/Resources.Designer.cs rename to src/Microsoft.AspNetCore.Antiforgery/Properties/Resources.Designer.cs diff --git a/src/Microsoft.AspNet.Antiforgery/Resources.resx b/src/Microsoft.AspNetCore.Antiforgery/Resources.resx similarity index 100% rename from src/Microsoft.AspNet.Antiforgery/Resources.resx rename to src/Microsoft.AspNetCore.Antiforgery/Resources.resx diff --git a/src/Microsoft.AspNet.Antiforgery/ServiceCollectionExtensions.cs b/src/Microsoft.AspNetCore.Antiforgery/ServiceCollectionExtensions.cs similarity index 100% rename from src/Microsoft.AspNet.Antiforgery/ServiceCollectionExtensions.cs rename to src/Microsoft.AspNetCore.Antiforgery/ServiceCollectionExtensions.cs diff --git a/src/Microsoft.AspNet.Antiforgery/project.json b/src/Microsoft.AspNetCore.Antiforgery/project.json similarity index 100% rename from src/Microsoft.AspNet.Antiforgery/project.json rename to src/Microsoft.AspNetCore.Antiforgery/project.json diff --git a/test/Microsoft.AspNet.Antiforgery.FunctionalTests/AntiForgerySampleTestFixture.cs b/test/Microsoft.AspNetCore.Antiforgery.FunctionalTests/AntiForgerySampleTestFixture.cs similarity index 100% rename from test/Microsoft.AspNet.Antiforgery.FunctionalTests/AntiForgerySampleTestFixture.cs rename to test/Microsoft.AspNetCore.Antiforgery.FunctionalTests/AntiForgerySampleTestFixture.cs diff --git a/test/Microsoft.AspNet.Antiforgery.FunctionalTests/AntiforgerySampleTest.cs b/test/Microsoft.AspNetCore.Antiforgery.FunctionalTests/AntiforgerySampleTest.cs similarity index 100% rename from test/Microsoft.AspNet.Antiforgery.FunctionalTests/AntiforgerySampleTest.cs rename to test/Microsoft.AspNetCore.Antiforgery.FunctionalTests/AntiforgerySampleTest.cs diff --git a/test/Microsoft.AspNet.Antiforgery.FunctionalTests/Microsoft.AspNet.Antiforgery.FunctionalTests.xproj b/test/Microsoft.AspNetCore.Antiforgery.FunctionalTests/Microsoft.AspNetCore.Antiforgery.FunctionalTests.xproj similarity index 100% rename from test/Microsoft.AspNet.Antiforgery.FunctionalTests/Microsoft.AspNet.Antiforgery.FunctionalTests.xproj rename to test/Microsoft.AspNetCore.Antiforgery.FunctionalTests/Microsoft.AspNetCore.Antiforgery.FunctionalTests.xproj diff --git a/test/Microsoft.AspNet.Antiforgery.FunctionalTests/project.json b/test/Microsoft.AspNetCore.Antiforgery.FunctionalTests/project.json similarity index 100% rename from test/Microsoft.AspNet.Antiforgery.FunctionalTests/project.json rename to test/Microsoft.AspNetCore.Antiforgery.FunctionalTests/project.json diff --git a/test/Microsoft.AspNet.Antiforgery.Test/AntiforgeryOptionsSetupTest.cs b/test/Microsoft.AspNetCore.Antiforgery.Test/AntiforgeryOptionsSetupTest.cs similarity index 100% rename from test/Microsoft.AspNet.Antiforgery.Test/AntiforgeryOptionsSetupTest.cs rename to test/Microsoft.AspNetCore.Antiforgery.Test/AntiforgeryOptionsSetupTest.cs diff --git a/test/Microsoft.AspNet.Antiforgery.Test/AntiforgeryTokenTest.cs b/test/Microsoft.AspNetCore.Antiforgery.Test/AntiforgeryTokenTest.cs similarity index 100% rename from test/Microsoft.AspNet.Antiforgery.Test/AntiforgeryTokenTest.cs rename to test/Microsoft.AspNetCore.Antiforgery.Test/AntiforgeryTokenTest.cs diff --git a/test/Microsoft.AspNet.Antiforgery.Test/BinaryBlobTest.cs b/test/Microsoft.AspNetCore.Antiforgery.Test/BinaryBlobTest.cs similarity index 100% rename from test/Microsoft.AspNet.Antiforgery.Test/BinaryBlobTest.cs rename to test/Microsoft.AspNetCore.Antiforgery.Test/BinaryBlobTest.cs diff --git a/test/Microsoft.AspNet.Antiforgery.Test/DefaultAntiforgeryTest.cs b/test/Microsoft.AspNetCore.Antiforgery.Test/DefaultAntiforgeryTest.cs similarity index 100% rename from test/Microsoft.AspNet.Antiforgery.Test/DefaultAntiforgeryTest.cs rename to test/Microsoft.AspNetCore.Antiforgery.Test/DefaultAntiforgeryTest.cs diff --git a/test/Microsoft.AspNet.Antiforgery.Test/DefaultAntiforgeryTokenGeneratorTest.cs b/test/Microsoft.AspNetCore.Antiforgery.Test/DefaultAntiforgeryTokenGeneratorTest.cs similarity index 100% rename from test/Microsoft.AspNet.Antiforgery.Test/DefaultAntiforgeryTokenGeneratorTest.cs rename to test/Microsoft.AspNetCore.Antiforgery.Test/DefaultAntiforgeryTokenGeneratorTest.cs diff --git a/test/Microsoft.AspNet.Antiforgery.Test/DefaultAntiforgeryTokenSerializerTest.cs b/test/Microsoft.AspNetCore.Antiforgery.Test/DefaultAntiforgeryTokenSerializerTest.cs similarity index 100% rename from test/Microsoft.AspNet.Antiforgery.Test/DefaultAntiforgeryTokenSerializerTest.cs rename to test/Microsoft.AspNetCore.Antiforgery.Test/DefaultAntiforgeryTokenSerializerTest.cs diff --git a/test/Microsoft.AspNet.Antiforgery.Test/DefaultAntiforgeryTokenStoreTest.cs b/test/Microsoft.AspNetCore.Antiforgery.Test/DefaultAntiforgeryTokenStoreTest.cs similarity index 100% rename from test/Microsoft.AspNet.Antiforgery.Test/DefaultAntiforgeryTokenStoreTest.cs rename to test/Microsoft.AspNetCore.Antiforgery.Test/DefaultAntiforgeryTokenStoreTest.cs diff --git a/test/Microsoft.AspNet.Antiforgery.Test/DefaultClaimUidExtractorTest.cs b/test/Microsoft.AspNetCore.Antiforgery.Test/DefaultClaimUidExtractorTest.cs similarity index 100% rename from test/Microsoft.AspNet.Antiforgery.Test/DefaultClaimUidExtractorTest.cs rename to test/Microsoft.AspNetCore.Antiforgery.Test/DefaultClaimUidExtractorTest.cs diff --git a/test/Microsoft.AspNet.Antiforgery.Test/Microsoft.AspNet.Antiforgery.Test.xproj b/test/Microsoft.AspNetCore.Antiforgery.Test/Microsoft.AspNetCore.Antiforgery.Test.xproj similarity index 100% rename from test/Microsoft.AspNet.Antiforgery.Test/Microsoft.AspNet.Antiforgery.Test.xproj rename to test/Microsoft.AspNetCore.Antiforgery.Test/Microsoft.AspNetCore.Antiforgery.Test.xproj diff --git a/test/Microsoft.AspNet.Antiforgery.Test/TestOptionsManager.cs b/test/Microsoft.AspNetCore.Antiforgery.Test/TestOptionsManager.cs similarity index 100% rename from test/Microsoft.AspNet.Antiforgery.Test/TestOptionsManager.cs rename to test/Microsoft.AspNetCore.Antiforgery.Test/TestOptionsManager.cs diff --git a/test/Microsoft.AspNet.Antiforgery.Test/project.json b/test/Microsoft.AspNetCore.Antiforgery.Test/project.json similarity index 100% rename from test/Microsoft.AspNet.Antiforgery.Test/project.json rename to test/Microsoft.AspNetCore.Antiforgery.Test/project.json From 9c9543dde4bfcaa1b2cb89b368b8f63a5ab214e1 Mon Sep 17 00:00:00 2001 From: "N. Taylor Mullen" Date: Fri, 22 Jan 2016 12:24:22 -0800 Subject: [PATCH 068/296] Rename AspNet 5 file contents. See https://github.com/aspnet/Announcements/issues/144 for more information. --- Antiforgery.sln | 8 ++++---- NuGetPackageVerifier.json | 2 +- samples/AntiforgerySample/Startup.cs | 10 +++++----- samples/AntiforgerySample/hosting.json | 4 ++-- samples/AntiforgerySample/project.json | 14 +++++++------- .../AntiforgeryContext.cs | 2 +- .../AntiforgeryOptions.cs | 2 +- .../AntiforgeryOptionsSetup.cs | 6 +++--- .../AntiforgeryToken.cs | 2 +- .../AntiforgeryTokenSet.cs | 2 +- .../AntiforgeryValidationException.cs | 4 ++-- src/Microsoft.AspNetCore.Antiforgery/BinaryBlob.cs | 2 +- .../DefaultAntiforgery.cs | 6 +++--- .../DefaultAntiforgeryAdditionalDataProvider.cs | 4 ++-- .../DefaultAntiforgeryContextAccessor.cs | 4 ++-- .../DefaultAntiforgeryTokenGenerator.cs | 4 ++-- .../DefaultAntiforgeryTokenSerializer.cs | 8 ++++---- .../DefaultAntiforgeryTokenStore.cs | 4 ++-- .../DefaultClaimUidExtractor.cs | 2 +- .../IAntiforgery.cs | 6 +++--- .../IAntiforgeryAdditionalDataProvider.cs | 4 ++-- .../IAntiforgeryContextAccessor.cs | 4 ++-- .../IAntiforgeryTokenGenerator.cs | 4 ++-- .../IAntiforgeryTokenSerializer.cs | 2 +- .../IAntiforgeryTokenStore.cs | 4 ++-- .../IClaimUidExtractor.cs | 2 +- .../Microsoft.AspNetCore.Antiforgery.xproj | 4 ++-- .../Properties/AssemblyInfo.cs | 4 ++-- .../Properties/Resources.Designer.cs | 4 ++-- .../ServiceCollectionExtensions.cs | 2 +- src/Microsoft.AspNetCore.Antiforgery/project.json | 8 ++++---- .../AntiForgerySampleTestFixture.cs | 6 +++--- .../AntiforgerySampleTest.cs | 2 +- .../project.json | 4 ++-- .../AntiforgeryOptionsSetupTest.cs | 2 +- .../AntiforgeryTokenTest.cs | 2 +- .../BinaryBlobTest.cs | 2 +- .../DefaultAntiforgeryTest.cs | 8 ++++---- .../DefaultAntiforgeryTokenGeneratorTest.cs | 4 ++-- .../DefaultAntiforgeryTokenSerializerTest.cs | 4 ++-- .../DefaultAntiforgeryTokenStoreTest.cs | 8 ++++---- .../DefaultClaimUidExtractorTest.cs | 2 +- .../Microsoft.AspNetCore.Antiforgery.Test.xproj | 4 ++-- .../TestOptionsManager.cs | 2 +- .../project.json | 4 ++-- 45 files changed, 96 insertions(+), 96 deletions(-) diff --git a/Antiforgery.sln b/Antiforgery.sln index 48fb0ca448..b25af44097 100644 --- a/Antiforgery.sln +++ b/Antiforgery.sln @@ -1,4 +1,4 @@ - + Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio 14 VisualStudioVersion = 14.0.24720.0 @@ -7,15 +7,15 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{71D070C4-B32 EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "test", "test", "{6EDD8B57-4DE8-4246-A6A3-47ECD92740B4}" EndProject -Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "Microsoft.AspNet.Antiforgery", "src\Microsoft.AspNet.Antiforgery\Microsoft.AspNet.Antiforgery.xproj", "{46FB03FB-7A44-4106-BDDE-D6F5417544AB}" +Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "Microsoft.AspNetCore.Antiforgery", "src\Microsoft.AspNetCore.Antiforgery\Microsoft.AspNetCore.Antiforgery.xproj", "{46FB03FB-7A44-4106-BDDE-D6F5417544AB}" EndProject -Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "Microsoft.AspNet.Antiforgery.Test", "test\Microsoft.AspNet.Antiforgery.Test\Microsoft.AspNet.Antiforgery.Test.xproj", "{415E83F8-6002-47E4-AA8E-CD5169C06F28}" +Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "Microsoft.AspNetCore.Antiforgery.Test", "test\Microsoft.AspNetCore.Antiforgery.Test\Microsoft.AspNetCore.Antiforgery.Test.xproj", "{415E83F8-6002-47E4-AA8E-CD5169C06F28}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "samples", "samples", "{D8C46ADF-E40A-4B48-ADE9-E1FA80466FE3}" EndProject Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "AntiforgerySample", "samples\AntiforgerySample\AntiforgerySample.xproj", "{AF9E0784-5EDB-494F-B46C-1A8DA785C49C}" EndProject -Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "Microsoft.AspNet.Antiforgery.FunctionalTests", "test\Microsoft.AspNet.Antiforgery.FunctionalTests\Microsoft.AspNet.Antiforgery.FunctionalTests.xproj", "{8B288810-5A96-4AF5-9836-8BA2D2953203}" +Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "Microsoft.AspNetCore.Antiforgery.FunctionalTests", "test\Microsoft.AspNetCore.Antiforgery.FunctionalTests\Microsoft.AspNetCore.Antiforgery.FunctionalTests.xproj", "{8B288810-5A96-4AF5-9836-8BA2D2953203}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution diff --git a/NuGetPackageVerifier.json b/NuGetPackageVerifier.json index 5627d30493..49fcb32a52 100644 --- a/NuGetPackageVerifier.json +++ b/NuGetPackageVerifier.json @@ -9,7 +9,7 @@ "StrictSemanticVersionValidationRule" ], "packages": { - "Microsoft.AspNet.Antiforgery": { } + "Microsoft.AspNetCore.Antiforgery": { } } }, "Default": { // Rules to run for packages not listed in any other set. diff --git a/samples/AntiforgerySample/Startup.cs b/samples/AntiforgerySample/Startup.cs index e2f548fc75..171fe66e81 100644 --- a/samples/AntiforgerySample/Startup.cs +++ b/samples/AntiforgerySample/Startup.cs @@ -3,11 +3,11 @@ using System; using System.IO; -using Microsoft.AspNet.Antiforgery; -using Microsoft.AspNet.Builder; -using Microsoft.AspNet.Hosting; -using Microsoft.AspNet.Http; -using Microsoft.AspNet.Routing; +using Microsoft.AspNetCore.Antiforgery; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Routing; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Options; using Newtonsoft.Json; diff --git a/samples/AntiforgerySample/hosting.json b/samples/AntiforgerySample/hosting.json index f8ef14574d..6a93dbafa8 100644 --- a/samples/AntiforgerySample/hosting.json +++ b/samples/AntiforgerySample/hosting.json @@ -1,3 +1,3 @@ -{ - "server": "Microsoft.AspNet.Server.Kestrel" +{ + "server": "Microsoft.AspNetCore.Server.Kestrel" } diff --git a/samples/AntiforgerySample/project.json b/samples/AntiforgerySample/project.json index 819ff29f70..dc978175bc 100644 --- a/samples/AntiforgerySample/project.json +++ b/samples/AntiforgerySample/project.json @@ -2,13 +2,13 @@ "version": "1.0.0-*", "dependencies": { - "Microsoft.AspNet.Antiforgery": "1.0.0-*", - "Microsoft.AspNet.Http.Abstractions": "1.0.0-*", - "Microsoft.AspNet.Http.Extensions": "1.0.0-*", - "Microsoft.AspNet.IISPlatformHandler": "1.0.0-*", - "Microsoft.AspNet.Routing.Extensions": "1.0.0-*", - "Microsoft.AspNet.Server.Kestrel": "1.0.0-*", - "Microsoft.AspNet.StaticFiles": "1.0.0-*", + "Microsoft.AspNetCore.Antiforgery": "1.0.0-*", + "Microsoft.AspNetCore.Http.Abstractions": "1.0.0-*", + "Microsoft.AspNetCore.Http.Extensions": "1.0.0-*", + "Microsoft.AspNetCore.IISPlatformHandler": "1.0.0-*", + "Microsoft.AspNetCore.Routing.Extensions": "1.0.0-*", + "Microsoft.AspNetCore.Server.Kestrel": "1.0.0-*", + "Microsoft.AspNetCore.StaticFiles": "1.0.0-*", "Newtonsoft.Json": "7.0.1" }, diff --git a/src/Microsoft.AspNetCore.Antiforgery/AntiforgeryContext.cs b/src/Microsoft.AspNetCore.Antiforgery/AntiforgeryContext.cs index ded759255c..3615fc25b1 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/AntiforgeryContext.cs +++ b/src/Microsoft.AspNetCore.Antiforgery/AntiforgeryContext.cs @@ -1,7 +1,7 @@ // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. -namespace Microsoft.AspNet.Antiforgery +namespace Microsoft.AspNetCore.Antiforgery { /// /// Used as a per request state. diff --git a/src/Microsoft.AspNetCore.Antiforgery/AntiforgeryOptions.cs b/src/Microsoft.AspNetCore.Antiforgery/AntiforgeryOptions.cs index 49656dd068..e59b6aecd9 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/AntiforgeryOptions.cs +++ b/src/Microsoft.AspNetCore.Antiforgery/AntiforgeryOptions.cs @@ -3,7 +3,7 @@ using System; -namespace Microsoft.AspNet.Antiforgery +namespace Microsoft.AspNetCore.Antiforgery { /// /// Provides programmatic configuration for the antiforgery token system. diff --git a/src/Microsoft.AspNetCore.Antiforgery/AntiforgeryOptionsSetup.cs b/src/Microsoft.AspNetCore.Antiforgery/AntiforgeryOptionsSetup.cs index c8dca4d39d..c397845599 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/AntiforgeryOptionsSetup.cs +++ b/src/Microsoft.AspNetCore.Antiforgery/AntiforgeryOptionsSetup.cs @@ -4,11 +4,11 @@ using System.Linq; using System.Security.Cryptography; using System.Text; -using Microsoft.AspNet.DataProtection; -using Microsoft.AspNet.WebUtilities; +using Microsoft.AspNetCore.DataProtection; +using Microsoft.AspNetCore.WebUtilities; using Microsoft.Extensions.Options; -namespace Microsoft.AspNet.Antiforgery +namespace Microsoft.AspNetCore.Antiforgery { public class AntiforgeryOptionsSetup : ConfigureOptions { diff --git a/src/Microsoft.AspNetCore.Antiforgery/AntiforgeryToken.cs b/src/Microsoft.AspNetCore.Antiforgery/AntiforgeryToken.cs index 233c5c51cd..bf9ba5e9bf 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/AntiforgeryToken.cs +++ b/src/Microsoft.AspNetCore.Antiforgery/AntiforgeryToken.cs @@ -1,7 +1,7 @@ // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. -namespace Microsoft.AspNet.Antiforgery +namespace Microsoft.AspNetCore.Antiforgery { public sealed class AntiforgeryToken { diff --git a/src/Microsoft.AspNetCore.Antiforgery/AntiforgeryTokenSet.cs b/src/Microsoft.AspNetCore.Antiforgery/AntiforgeryTokenSet.cs index 8fabd782ee..9446cba3c6 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/AntiforgeryTokenSet.cs +++ b/src/Microsoft.AspNetCore.Antiforgery/AntiforgeryTokenSet.cs @@ -3,7 +3,7 @@ using System; -namespace Microsoft.AspNet.Antiforgery +namespace Microsoft.AspNetCore.Antiforgery { /// /// The antiforgery token pair (cookie and request token) for a request. diff --git a/src/Microsoft.AspNetCore.Antiforgery/AntiforgeryValidationException.cs b/src/Microsoft.AspNetCore.Antiforgery/AntiforgeryValidationException.cs index d5ea22e52b..b2fb6e9618 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/AntiforgeryValidationException.cs +++ b/src/Microsoft.AspNetCore.Antiforgery/AntiforgeryValidationException.cs @@ -1,9 +1,9 @@ -// Copyright (c) .NET Foundation. All rights reserved. +// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; -namespace Microsoft.AspNet.Antiforgery +namespace Microsoft.AspNetCore.Antiforgery { /// /// The that is thrown when the antiforgery token validation fails. diff --git a/src/Microsoft.AspNetCore.Antiforgery/BinaryBlob.cs b/src/Microsoft.AspNetCore.Antiforgery/BinaryBlob.cs index e0faebed0a..9cb78296b5 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/BinaryBlob.cs +++ b/src/Microsoft.AspNetCore.Antiforgery/BinaryBlob.cs @@ -8,7 +8,7 @@ using System.Runtime.CompilerServices; using System.Security.Cryptography; using System.Text; -namespace Microsoft.AspNet.Antiforgery +namespace Microsoft.AspNetCore.Antiforgery { // Represents a binary blob (token) that contains random data. // Useful for binary data inside a serialized stream. diff --git a/src/Microsoft.AspNetCore.Antiforgery/DefaultAntiforgery.cs b/src/Microsoft.AspNetCore.Antiforgery/DefaultAntiforgery.cs index b17c3edb4c..9239609498 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/DefaultAntiforgery.cs +++ b/src/Microsoft.AspNetCore.Antiforgery/DefaultAntiforgery.cs @@ -4,11 +4,11 @@ using System; using System.Diagnostics; using System.Threading.Tasks; -using Microsoft.AspNet.Html; -using Microsoft.AspNet.Http; +using Microsoft.AspNetCore.Html; +using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Options; -namespace Microsoft.AspNet.Antiforgery +namespace Microsoft.AspNetCore.Antiforgery { /// /// Provides access to the antiforgery system, which provides protection against diff --git a/src/Microsoft.AspNetCore.Antiforgery/DefaultAntiforgeryAdditionalDataProvider.cs b/src/Microsoft.AspNetCore.Antiforgery/DefaultAntiforgeryAdditionalDataProvider.cs index 2d5967f368..e0797d2696 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/DefaultAntiforgeryAdditionalDataProvider.cs +++ b/src/Microsoft.AspNetCore.Antiforgery/DefaultAntiforgeryAdditionalDataProvider.cs @@ -1,9 +1,9 @@ // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. -using Microsoft.AspNet.Http; +using Microsoft.AspNetCore.Http; -namespace Microsoft.AspNet.Antiforgery +namespace Microsoft.AspNetCore.Antiforgery { /// /// A default implementation. diff --git a/src/Microsoft.AspNetCore.Antiforgery/DefaultAntiforgeryContextAccessor.cs b/src/Microsoft.AspNetCore.Antiforgery/DefaultAntiforgeryContextAccessor.cs index c19eb312e2..7dd27634e6 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/DefaultAntiforgeryContextAccessor.cs +++ b/src/Microsoft.AspNetCore.Antiforgery/DefaultAntiforgeryContextAccessor.cs @@ -1,7 +1,7 @@ -// Copyright (c) .NET Foundation. All rights reserved. +// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. -namespace Microsoft.AspNet.Antiforgery +namespace Microsoft.AspNetCore.Antiforgery { public class DefaultAntiforgeryContextAccessor : IAntiforgeryContextAccessor { diff --git a/src/Microsoft.AspNetCore.Antiforgery/DefaultAntiforgeryTokenGenerator.cs b/src/Microsoft.AspNetCore.Antiforgery/DefaultAntiforgeryTokenGenerator.cs index ae43f846b6..27e82d9a96 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/DefaultAntiforgeryTokenGenerator.cs +++ b/src/Microsoft.AspNetCore.Antiforgery/DefaultAntiforgeryTokenGenerator.cs @@ -5,9 +5,9 @@ using System; using System.Diagnostics; using System.Security.Claims; using System.Security.Principal; -using Microsoft.AspNet.Http; +using Microsoft.AspNetCore.Http; -namespace Microsoft.AspNet.Antiforgery +namespace Microsoft.AspNetCore.Antiforgery { public class DefaultAntiforgeryTokenGenerator : IAntiforgeryTokenGenerator { diff --git a/src/Microsoft.AspNetCore.Antiforgery/DefaultAntiforgeryTokenSerializer.cs b/src/Microsoft.AspNetCore.Antiforgery/DefaultAntiforgeryTokenSerializer.cs index e1ecd406e8..7c48a9d3d3 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/DefaultAntiforgeryTokenSerializer.cs +++ b/src/Microsoft.AspNetCore.Antiforgery/DefaultAntiforgeryTokenSerializer.cs @@ -3,14 +3,14 @@ using System; using System.IO; -using Microsoft.AspNet.DataProtection; -using Microsoft.AspNet.WebUtilities; +using Microsoft.AspNetCore.DataProtection; +using Microsoft.AspNetCore.WebUtilities; -namespace Microsoft.AspNet.Antiforgery +namespace Microsoft.AspNetCore.Antiforgery { public class DefaultAntiforgeryTokenSerializer : IAntiforgeryTokenSerializer { - private static readonly string Purpose = "Microsoft.AspNet.Antiforgery.AntiforgeryToken.v1"; + private static readonly string Purpose = "Microsoft.AspNetCore.Antiforgery.AntiforgeryToken.v1"; private readonly IDataProtector _cryptoSystem; private const byte TokenVersion = 0x01; diff --git a/src/Microsoft.AspNetCore.Antiforgery/DefaultAntiforgeryTokenStore.cs b/src/Microsoft.AspNetCore.Antiforgery/DefaultAntiforgeryTokenStore.cs index ee677af059..5d9328f031 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/DefaultAntiforgeryTokenStore.cs +++ b/src/Microsoft.AspNetCore.Antiforgery/DefaultAntiforgeryTokenStore.cs @@ -4,12 +4,12 @@ using System; using System.Diagnostics; using System.Threading.Tasks; -using Microsoft.AspNet.Http; +using Microsoft.AspNetCore.Http; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Options; using Microsoft.Extensions.Primitives; -namespace Microsoft.AspNet.Antiforgery +namespace Microsoft.AspNetCore.Antiforgery { public class DefaultAntiforgeryTokenStore : IAntiforgeryTokenStore { diff --git a/src/Microsoft.AspNetCore.Antiforgery/DefaultClaimUidExtractor.cs b/src/Microsoft.AspNetCore.Antiforgery/DefaultClaimUidExtractor.cs index 7c033547cc..8220cbf166 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/DefaultClaimUidExtractor.cs +++ b/src/Microsoft.AspNetCore.Antiforgery/DefaultClaimUidExtractor.cs @@ -8,7 +8,7 @@ using System.Linq; using System.Security.Claims; using System.Security.Cryptography; -namespace Microsoft.AspNet.Antiforgery +namespace Microsoft.AspNetCore.Antiforgery { /// /// Default implementation of . diff --git a/src/Microsoft.AspNetCore.Antiforgery/IAntiforgery.cs b/src/Microsoft.AspNetCore.Antiforgery/IAntiforgery.cs index 1944b02622..ca2d8341ae 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/IAntiforgery.cs +++ b/src/Microsoft.AspNetCore.Antiforgery/IAntiforgery.cs @@ -2,10 +2,10 @@ // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Threading.Tasks; -using Microsoft.AspNet.Html; -using Microsoft.AspNet.Http; +using Microsoft.AspNetCore.Html; +using Microsoft.AspNetCore.Http; -namespace Microsoft.AspNet.Antiforgery +namespace Microsoft.AspNetCore.Antiforgery { /// /// Provides access to the antiforgery system, which provides protection against diff --git a/src/Microsoft.AspNetCore.Antiforgery/IAntiforgeryAdditionalDataProvider.cs b/src/Microsoft.AspNetCore.Antiforgery/IAntiforgeryAdditionalDataProvider.cs index b652619dd9..d66b6245db 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/IAntiforgeryAdditionalDataProvider.cs +++ b/src/Microsoft.AspNetCore.Antiforgery/IAntiforgeryAdditionalDataProvider.cs @@ -1,9 +1,9 @@ // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. -using Microsoft.AspNet.Http; +using Microsoft.AspNetCore.Http; -namespace Microsoft.AspNet.Antiforgery +namespace Microsoft.AspNetCore.Antiforgery { /// /// Allows providing or validating additional custom data for antiforgery tokens. diff --git a/src/Microsoft.AspNetCore.Antiforgery/IAntiforgeryContextAccessor.cs b/src/Microsoft.AspNetCore.Antiforgery/IAntiforgeryContextAccessor.cs index ac2c5e023f..7b0146dbd9 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/IAntiforgeryContextAccessor.cs +++ b/src/Microsoft.AspNetCore.Antiforgery/IAntiforgeryContextAccessor.cs @@ -1,7 +1,7 @@ -// Copyright (c) .NET Foundation. All rights reserved. +// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. -namespace Microsoft.AspNet.Antiforgery +namespace Microsoft.AspNetCore.Antiforgery { public interface IAntiforgeryContextAccessor { diff --git a/src/Microsoft.AspNetCore.Antiforgery/IAntiforgeryTokenGenerator.cs b/src/Microsoft.AspNetCore.Antiforgery/IAntiforgeryTokenGenerator.cs index 47b701817c..79fc447a45 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/IAntiforgeryTokenGenerator.cs +++ b/src/Microsoft.AspNetCore.Antiforgery/IAntiforgeryTokenGenerator.cs @@ -1,9 +1,9 @@ // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. -using Microsoft.AspNet.Http; +using Microsoft.AspNetCore.Http; -namespace Microsoft.AspNet.Antiforgery +namespace Microsoft.AspNetCore.Antiforgery { /// /// Generates and validates antiforgery tokens. diff --git a/src/Microsoft.AspNetCore.Antiforgery/IAntiforgeryTokenSerializer.cs b/src/Microsoft.AspNetCore.Antiforgery/IAntiforgeryTokenSerializer.cs index 1864906983..badc897309 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/IAntiforgeryTokenSerializer.cs +++ b/src/Microsoft.AspNetCore.Antiforgery/IAntiforgeryTokenSerializer.cs @@ -1,7 +1,7 @@ // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. -namespace Microsoft.AspNet.Antiforgery +namespace Microsoft.AspNetCore.Antiforgery { // Abstracts out the serialization process for an antiforgery token public interface IAntiforgeryTokenSerializer diff --git a/src/Microsoft.AspNetCore.Antiforgery/IAntiforgeryTokenStore.cs b/src/Microsoft.AspNetCore.Antiforgery/IAntiforgeryTokenStore.cs index 15ea992cb8..9d14ac79b3 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/IAntiforgeryTokenStore.cs +++ b/src/Microsoft.AspNetCore.Antiforgery/IAntiforgeryTokenStore.cs @@ -2,9 +2,9 @@ // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Threading.Tasks; -using Microsoft.AspNet.Http; +using Microsoft.AspNetCore.Http; -namespace Microsoft.AspNet.Antiforgery +namespace Microsoft.AspNetCore.Antiforgery { // Provides an abstraction around how tokens are persisted and retrieved for a request public interface IAntiforgeryTokenStore diff --git a/src/Microsoft.AspNetCore.Antiforgery/IClaimUidExtractor.cs b/src/Microsoft.AspNetCore.Antiforgery/IClaimUidExtractor.cs index c7b0af04c9..b78cbc863a 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/IClaimUidExtractor.cs +++ b/src/Microsoft.AspNetCore.Antiforgery/IClaimUidExtractor.cs @@ -3,7 +3,7 @@ using System.Security.Claims; -namespace Microsoft.AspNet.Antiforgery +namespace Microsoft.AspNetCore.Antiforgery { /// /// This interface can extract unique identifers for a claims-based identity. diff --git a/src/Microsoft.AspNetCore.Antiforgery/Microsoft.AspNetCore.Antiforgery.xproj b/src/Microsoft.AspNetCore.Antiforgery/Microsoft.AspNetCore.Antiforgery.xproj index b920ab0e7b..c616520381 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/Microsoft.AspNetCore.Antiforgery.xproj +++ b/src/Microsoft.AspNetCore.Antiforgery/Microsoft.AspNetCore.Antiforgery.xproj @@ -1,4 +1,4 @@ - + 14.0 @@ -8,7 +8,7 @@ 46fb03fb-7a44-4106-bdde-d6f5417544ab - Microsoft.AspNet.Antiforgery + Microsoft.AspNetCore.Antiforgery ..\..\artifacts\obj\$(MSBuildProjectName) ..\..\artifacts\bin\$(MSBuildProjectName)\ diff --git a/src/Microsoft.AspNetCore.Antiforgery/Properties/AssemblyInfo.cs b/src/Microsoft.AspNetCore.Antiforgery/Properties/AssemblyInfo.cs index 20d72d904c..e30b53b634 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/Properties/AssemblyInfo.cs +++ b/src/Microsoft.AspNetCore.Antiforgery/Properties/AssemblyInfo.cs @@ -1,4 +1,4 @@ -// Copyright (c) .NET Foundation. All rights reserved. +// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Reflection; @@ -6,6 +6,6 @@ using System.Resources; using System.Runtime.CompilerServices; [assembly: InternalsVisibleTo("DynamicProxyGenAssembly2, PublicKey=0024000004800000940000000602000000240000525341310004000001000100c547cac37abd99c8db225ef2f6c8a3602f3b3606cc9891605d02baa56104f4cfc0734aa39b93bf7852f7d9266654753cc297e7d2edfe0bac1cdcf9f717241550e0a7b191195b7667bb4f64bcb8e2121380fd1d9d46ad2d92d2d15605093924cceaf74c4861eff62abf69b9291ed0a340e113be11e6a7d3113e92484cf7045cc7")] -[assembly: InternalsVisibleTo("Microsoft.AspNet.Antiforgery.Test, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f33a29044fa9d740c9b3213a93e57c84b472c84e0b8a0e1ae48e67a9f8f6de9d5f7f3d52ac23e48ac51801f1dc950abe901da34d2a9e3baadb141a17c77ef3c565dd5ee5054b91cf63bb3c6ab83f72ab3aafe93d0fc3c2348b764fafb0b1c0733de51459aeab46580384bf9d74c4e28164b7cde247f891ba07891c9d872ad2bb")] +[assembly: InternalsVisibleTo("Microsoft.AspNetCore.Antiforgery.Test, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f33a29044fa9d740c9b3213a93e57c84b472c84e0b8a0e1ae48e67a9f8f6de9d5f7f3d52ac23e48ac51801f1dc950abe901da34d2a9e3baadb141a17c77ef3c565dd5ee5054b91cf63bb3c6ab83f72ab3aafe93d0fc3c2348b764fafb0b1c0733de51459aeab46580384bf9d74c4e28164b7cde247f891ba07891c9d872ad2bb")] [assembly: AssemblyMetadata("Serviceable", "True")] [assembly: NeutralResourcesLanguage("en-us")] diff --git a/src/Microsoft.AspNetCore.Antiforgery/Properties/Resources.Designer.cs b/src/Microsoft.AspNetCore.Antiforgery/Properties/Resources.Designer.cs index df958a3454..87e05dabab 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/Properties/Resources.Designer.cs +++ b/src/Microsoft.AspNetCore.Antiforgery/Properties/Resources.Designer.cs @@ -1,5 +1,5 @@ // -namespace Microsoft.AspNet.Antiforgery +namespace Microsoft.AspNetCore.Antiforgery { using System.Globalization; using System.Reflection; @@ -8,7 +8,7 @@ namespace Microsoft.AspNet.Antiforgery internal static class Resources { private static readonly ResourceManager _resourceManager - = new ResourceManager("Microsoft.AspNet.Antiforgery.Resources", typeof(Resources).GetTypeInfo().Assembly); + = new ResourceManager("Microsoft.AspNetCore.Antiforgery.Resources", typeof(Resources).GetTypeInfo().Assembly); /// /// The provided identity of type '{0}' is marked {1} = {2} but does not have a value for {3}. By default, the antiforgery system requires that all authenticated identities have a unique {3}. If it is not possible to provide a unique {3} for this identity, consider extending {4} by overriding the {5} or a custom type that can provide some form of unique identifier for the current user. diff --git a/src/Microsoft.AspNetCore.Antiforgery/ServiceCollectionExtensions.cs b/src/Microsoft.AspNetCore.Antiforgery/ServiceCollectionExtensions.cs index 556647b56a..26839b935f 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/ServiceCollectionExtensions.cs +++ b/src/Microsoft.AspNetCore.Antiforgery/ServiceCollectionExtensions.cs @@ -2,7 +2,7 @@ // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; -using Microsoft.AspNet.Antiforgery; +using Microsoft.AspNetCore.Antiforgery; using Microsoft.Extensions.DependencyInjection.Extensions; using Microsoft.Extensions.Options; diff --git a/src/Microsoft.AspNetCore.Antiforgery/project.json b/src/Microsoft.AspNetCore.Antiforgery/project.json index 9222a0c515..37585292cb 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/project.json +++ b/src/Microsoft.AspNetCore.Antiforgery/project.json @@ -10,10 +10,10 @@ "url": "git://github.com/aspnet/antiforgery" }, "dependencies": { - "Microsoft.AspNet.DataProtection": "1.0.0-*", - "Microsoft.AspNet.Html.Abstractions": "1.0.0-*", - "Microsoft.AspNet.Http.Abstractions": "1.0.0-*", - "Microsoft.AspNet.WebUtilities": "1.0.0-*" + "Microsoft.AspNetCore.DataProtection": "1.0.0-*", + "Microsoft.AspNetCore.Html.Abstractions": "1.0.0-*", + "Microsoft.AspNetCore.Http.Abstractions": "1.0.0-*", + "Microsoft.AspNetCore.WebUtilities": "1.0.0-*" }, "frameworks": { "dotnet5.4": { }, diff --git a/test/Microsoft.AspNetCore.Antiforgery.FunctionalTests/AntiForgerySampleTestFixture.cs b/test/Microsoft.AspNetCore.Antiforgery.FunctionalTests/AntiForgerySampleTestFixture.cs index fbdb3e0ea9..ad4514519e 100644 --- a/test/Microsoft.AspNetCore.Antiforgery.FunctionalTests/AntiForgerySampleTestFixture.cs +++ b/test/Microsoft.AspNetCore.Antiforgery.FunctionalTests/AntiForgerySampleTestFixture.cs @@ -4,11 +4,11 @@ using System; using System.Collections.Generic; using System.Net.Http; -using Microsoft.AspNet.Hosting; -using Microsoft.AspNet.TestHost; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.TestHost; using Microsoft.Extensions.Configuration; -namespace Microsoft.AspNet.Antiforgery.FunctionalTests +namespace Microsoft.AspNetCore.Antiforgery.FunctionalTests { public class AntiForgerySampleTestFixture : IDisposable { diff --git a/test/Microsoft.AspNetCore.Antiforgery.FunctionalTests/AntiforgerySampleTest.cs b/test/Microsoft.AspNetCore.Antiforgery.FunctionalTests/AntiforgerySampleTest.cs index 72926809ad..9fd2a497b9 100644 --- a/test/Microsoft.AspNetCore.Antiforgery.FunctionalTests/AntiforgerySampleTest.cs +++ b/test/Microsoft.AspNetCore.Antiforgery.FunctionalTests/AntiforgerySampleTest.cs @@ -9,7 +9,7 @@ using System.Net.Http; using System.Threading.Tasks; using Xunit; -namespace Microsoft.AspNet.Antiforgery.FunctionalTests +namespace Microsoft.AspNetCore.Antiforgery.FunctionalTests { public class AntiforgerySampleTests : IClassFixture { diff --git a/test/Microsoft.AspNetCore.Antiforgery.FunctionalTests/project.json b/test/Microsoft.AspNetCore.Antiforgery.FunctionalTests/project.json index 572352d718..705dc877d8 100644 --- a/test/Microsoft.AspNetCore.Antiforgery.FunctionalTests/project.json +++ b/test/Microsoft.AspNetCore.Antiforgery.FunctionalTests/project.json @@ -1,8 +1,8 @@ { "dependencies": { "AntiforgerySample": "1.0.0-*", - "Microsoft.AspNet.TestHost": "1.0.0-*", - "Microsoft.AspNet.Testing": "1.0.0-*" + "Microsoft.AspNetCore.TestHost": "1.0.0-*", + "Microsoft.AspNetCore.Testing": "1.0.0-*" }, "testRunner": "xunit", "commands": { diff --git a/test/Microsoft.AspNetCore.Antiforgery.Test/AntiforgeryOptionsSetupTest.cs b/test/Microsoft.AspNetCore.Antiforgery.Test/AntiforgeryOptionsSetupTest.cs index 5211a6b383..7822afb4d3 100644 --- a/test/Microsoft.AspNetCore.Antiforgery.Test/AntiforgeryOptionsSetupTest.cs +++ b/test/Microsoft.AspNetCore.Antiforgery.Test/AntiforgeryOptionsSetupTest.cs @@ -5,7 +5,7 @@ using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Options; using Xunit; -namespace Microsoft.AspNet.Antiforgery +namespace Microsoft.AspNetCore.Antiforgery { public class AntiforgeryOptionsSetupTest { diff --git a/test/Microsoft.AspNetCore.Antiforgery.Test/AntiforgeryTokenTest.cs b/test/Microsoft.AspNetCore.Antiforgery.Test/AntiforgeryTokenTest.cs index c56055bee7..1980043b8b 100644 --- a/test/Microsoft.AspNetCore.Antiforgery.Test/AntiforgeryTokenTest.cs +++ b/test/Microsoft.AspNetCore.Antiforgery.Test/AntiforgeryTokenTest.cs @@ -3,7 +3,7 @@ using Xunit; -namespace Microsoft.AspNet.Antiforgery +namespace Microsoft.AspNetCore.Antiforgery { public class AntiforgeryTokenTest { diff --git a/test/Microsoft.AspNetCore.Antiforgery.Test/BinaryBlobTest.cs b/test/Microsoft.AspNetCore.Antiforgery.Test/BinaryBlobTest.cs index c27b12986d..c49a055724 100644 --- a/test/Microsoft.AspNetCore.Antiforgery.Test/BinaryBlobTest.cs +++ b/test/Microsoft.AspNetCore.Antiforgery.Test/BinaryBlobTest.cs @@ -4,7 +4,7 @@ using System; using Xunit; -namespace Microsoft.AspNet.Antiforgery +namespace Microsoft.AspNetCore.Antiforgery { public class BinaryBlobTest { diff --git a/test/Microsoft.AspNetCore.Antiforgery.Test/DefaultAntiforgeryTest.cs b/test/Microsoft.AspNetCore.Antiforgery.Test/DefaultAntiforgeryTest.cs index b5283bef2e..ddb190a256 100644 --- a/test/Microsoft.AspNetCore.Antiforgery.Test/DefaultAntiforgeryTest.cs +++ b/test/Microsoft.AspNetCore.Antiforgery.Test/DefaultAntiforgeryTest.cs @@ -5,15 +5,15 @@ using System; using System.IO; using System.Security.Claims; using System.Threading.Tasks; -using Microsoft.AspNet.Html; -using Microsoft.AspNet.Http; -using Microsoft.AspNet.Http.Internal; +using Microsoft.AspNetCore.Html; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.Internal; using Microsoft.Extensions.Options; using Microsoft.Extensions.WebEncoders.Testing; using Moq; using Xunit; -namespace Microsoft.AspNet.Antiforgery +namespace Microsoft.AspNetCore.Antiforgery { public class DefaultAntiforgeryTest { diff --git a/test/Microsoft.AspNetCore.Antiforgery.Test/DefaultAntiforgeryTokenGeneratorTest.cs b/test/Microsoft.AspNetCore.Antiforgery.Test/DefaultAntiforgeryTokenGeneratorTest.cs index 005f00f10c..fbbd6a50e4 100644 --- a/test/Microsoft.AspNetCore.Antiforgery.Test/DefaultAntiforgeryTokenGeneratorTest.cs +++ b/test/Microsoft.AspNetCore.Antiforgery.Test/DefaultAntiforgeryTokenGeneratorTest.cs @@ -4,11 +4,11 @@ using System; using System.Security.Claims; using System.Security.Cryptography; -using Microsoft.AspNet.Http.Internal; +using Microsoft.AspNetCore.Http.Internal; using Moq; using Xunit; -namespace Microsoft.AspNet.Antiforgery +namespace Microsoft.AspNetCore.Antiforgery { public class DefaultAntiforgeryTokenGeneratorProviderTest { diff --git a/test/Microsoft.AspNetCore.Antiforgery.Test/DefaultAntiforgeryTokenSerializerTest.cs b/test/Microsoft.AspNetCore.Antiforgery.Test/DefaultAntiforgeryTokenSerializerTest.cs index a6012bcbe7..519bc85f8b 100644 --- a/test/Microsoft.AspNetCore.Antiforgery.Test/DefaultAntiforgeryTokenSerializerTest.cs +++ b/test/Microsoft.AspNetCore.Antiforgery.Test/DefaultAntiforgeryTokenSerializerTest.cs @@ -4,11 +4,11 @@ using System; using System.Collections.Generic; using System.Linq; -using Microsoft.AspNet.DataProtection; +using Microsoft.AspNetCore.DataProtection; using Moq; using Xunit; -namespace Microsoft.AspNet.Antiforgery +namespace Microsoft.AspNetCore.Antiforgery { public class DefaultAntiforgeryTokenSerializerTest { diff --git a/test/Microsoft.AspNetCore.Antiforgery.Test/DefaultAntiforgeryTokenStoreTest.cs b/test/Microsoft.AspNetCore.Antiforgery.Test/DefaultAntiforgeryTokenStoreTest.cs index 61660652ab..de71ea9cf1 100644 --- a/test/Microsoft.AspNetCore.Antiforgery.Test/DefaultAntiforgeryTokenStoreTest.cs +++ b/test/Microsoft.AspNetCore.Antiforgery.Test/DefaultAntiforgeryTokenStoreTest.cs @@ -4,15 +4,15 @@ using System; using System.Collections.Generic; using System.Threading.Tasks; -using Microsoft.AspNet.DataProtection; -using Microsoft.AspNet.Http; -using Microsoft.AspNet.Http.Internal; +using Microsoft.AspNetCore.DataProtection; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.Internal; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Primitives; using Moq; using Xunit; -namespace Microsoft.AspNet.Antiforgery +namespace Microsoft.AspNetCore.Antiforgery { public class DefaultAntiforgeryTokenStoreTest { diff --git a/test/Microsoft.AspNetCore.Antiforgery.Test/DefaultClaimUidExtractorTest.cs b/test/Microsoft.AspNetCore.Antiforgery.Test/DefaultClaimUidExtractorTest.cs index 25704e4b96..1516ed86f5 100644 --- a/test/Microsoft.AspNetCore.Antiforgery.Test/DefaultClaimUidExtractorTest.cs +++ b/test/Microsoft.AspNetCore.Antiforgery.Test/DefaultClaimUidExtractorTest.cs @@ -7,7 +7,7 @@ using System.Security.Claims; using Moq; using Xunit; -namespace Microsoft.AspNet.Antiforgery +namespace Microsoft.AspNetCore.Antiforgery { public class DefaultClaimUidExtractorTest { diff --git a/test/Microsoft.AspNetCore.Antiforgery.Test/Microsoft.AspNetCore.Antiforgery.Test.xproj b/test/Microsoft.AspNetCore.Antiforgery.Test/Microsoft.AspNetCore.Antiforgery.Test.xproj index efe8ba14f1..d97cfa0d9e 100644 --- a/test/Microsoft.AspNetCore.Antiforgery.Test/Microsoft.AspNetCore.Antiforgery.Test.xproj +++ b/test/Microsoft.AspNetCore.Antiforgery.Test/Microsoft.AspNetCore.Antiforgery.Test.xproj @@ -1,4 +1,4 @@ - + 14.0 @@ -7,7 +7,7 @@ 415e83f8-6002-47e4-aa8e-cd5169c06f28 - Microsoft.AspNet.Antiforgery.Test + Microsoft.AspNetCore.Antiforgery.Test ..\..\artifacts\obj\$(MSBuildProjectName) ..\..\artifacts\bin\$(MSBuildProjectName)\ diff --git a/test/Microsoft.AspNetCore.Antiforgery.Test/TestOptionsManager.cs b/test/Microsoft.AspNetCore.Antiforgery.Test/TestOptionsManager.cs index 0aea27a9d9..7a6b3d7739 100644 --- a/test/Microsoft.AspNetCore.Antiforgery.Test/TestOptionsManager.cs +++ b/test/Microsoft.AspNetCore.Antiforgery.Test/TestOptionsManager.cs @@ -3,7 +3,7 @@ using Microsoft.Extensions.Options; -namespace Microsoft.AspNet.Antiforgery +namespace Microsoft.AspNetCore.Antiforgery { public class TestOptionsManager : IOptions { diff --git a/test/Microsoft.AspNetCore.Antiforgery.Test/project.json b/test/Microsoft.AspNetCore.Antiforgery.Test/project.json index 2669aae1e5..a8e16f08a1 100644 --- a/test/Microsoft.AspNetCore.Antiforgery.Test/project.json +++ b/test/Microsoft.AspNetCore.Antiforgery.Test/project.json @@ -4,8 +4,8 @@ "keyFile": "../../tools/Key.snk" }, "dependencies": { - "Microsoft.AspNet.Antiforgery": "1.0.0-*", - "Microsoft.AspNet.Http": "1.0.0-*", + "Microsoft.AspNetCore.Antiforgery": "1.0.0-*", + "Microsoft.AspNetCore.Http": "1.0.0-*", "Microsoft.Extensions.DependencyInjection": "1.0.0-*", "Microsoft.Extensions.WebEncoders": "1.0.0-*", "xunit": "2.1.0-*" From 7c7a4a905e2d1677a55c306b1b3047d413965526 Mon Sep 17 00:00:00 2001 From: Doug Bunting Date: Mon, 1 Feb 2016 10:52:23 -0800 Subject: [PATCH 069/296] Correct project dependencies - use latest `System.Net.Http`, not hard-coded version - add imports for the latest CLI - see aspnet/FileSystem@4a9a0fd for the inspiration --- samples/AntiforgerySample/project.json | 5 ++++- .../project.json | 11 ++++++++--- .../project.json | 4 +++- 3 files changed, 15 insertions(+), 5 deletions(-) diff --git a/samples/AntiforgerySample/project.json b/samples/AntiforgerySample/project.json index dc978175bc..516b8f4f9f 100644 --- a/samples/AntiforgerySample/project.json +++ b/samples/AntiforgerySample/project.json @@ -9,6 +9,7 @@ "Microsoft.AspNetCore.Routing.Extensions": "1.0.0-*", "Microsoft.AspNetCore.Server.Kestrel": "1.0.0-*", "Microsoft.AspNetCore.StaticFiles": "1.0.0-*", + "Microsoft.NETCore.Platforms": "1.0.1-*", "Newtonsoft.Json": "7.0.1" }, @@ -22,7 +23,9 @@ "frameworks": { "dnx451": { }, - "dnxcore50": { } + "dnxcore50": { + "imports": "portable-net451+win8" + } }, "publishExclude": [ diff --git a/test/Microsoft.AspNetCore.Antiforgery.FunctionalTests/project.json b/test/Microsoft.AspNetCore.Antiforgery.FunctionalTests/project.json index 705dc877d8..b6125bd758 100644 --- a/test/Microsoft.AspNetCore.Antiforgery.FunctionalTests/project.json +++ b/test/Microsoft.AspNetCore.Antiforgery.FunctionalTests/project.json @@ -2,7 +2,8 @@ "dependencies": { "AntiforgerySample": "1.0.0-*", "Microsoft.AspNetCore.TestHost": "1.0.0-*", - "Microsoft.AspNetCore.Testing": "1.0.0-*" + "Microsoft.AspNetCore.Testing": "1.0.0-*", + "Microsoft.NETCore.Platforms": "1.0.1-*" }, "testRunner": "xunit", "commands": { @@ -12,15 +13,19 @@ "dnx451": { "dependencies": { "Moq": "4.2.1312.1622", - "System.Net.Http": "4.0.1-rc2-23621", "xunit.runner.console": "2.1.0" + }, + "frameworkAssemblies": { + "System.Net.Http": "" } }, "dnxcore50": { "dependencies": { "moq.netcore": "4.4.0-beta8", + "System.Net.Http": "4.0.1-*", "xunit.runner.aspnet": "2.0.0-aspnet-*" - } + }, + "imports": "portable-net451+win8" } } } diff --git a/test/Microsoft.AspNetCore.Antiforgery.Test/project.json b/test/Microsoft.AspNetCore.Antiforgery.Test/project.json index a8e16f08a1..fee3adecdb 100644 --- a/test/Microsoft.AspNetCore.Antiforgery.Test/project.json +++ b/test/Microsoft.AspNetCore.Antiforgery.Test/project.json @@ -8,6 +8,7 @@ "Microsoft.AspNetCore.Http": "1.0.0-*", "Microsoft.Extensions.DependencyInjection": "1.0.0-*", "Microsoft.Extensions.WebEncoders": "1.0.0-*", + "Microsoft.NETCore.Platforms": "1.0.1-*", "xunit": "2.1.0-*" }, "testRunner": "xunit", @@ -28,7 +29,8 @@ "dependencies": { "moq.netcore": "4.4.0-beta8", "xunit.runner.aspnet": "2.0.0-aspnet-*" - } + }, + "imports": "portable-net451+win8" } } } From 492c0798b100d3854d0855bf4913ea0349067b37 Mon Sep 17 00:00:00 2001 From: Doug Bunting Date: Tue, 26 Jan 2016 23:32:26 -0800 Subject: [PATCH 070/296] Anything but `HtmlContentBuilder` - #23 part 1 --- .../DefaultAntiforgery.cs | 52 ++++++++++++++----- 1 file changed, 40 insertions(+), 12 deletions(-) diff --git a/src/Microsoft.AspNetCore.Antiforgery/DefaultAntiforgery.cs b/src/Microsoft.AspNetCore.Antiforgery/DefaultAntiforgery.cs index 9239609498..c4a10c2955 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/DefaultAntiforgery.cs +++ b/src/Microsoft.AspNetCore.Antiforgery/DefaultAntiforgery.cs @@ -3,6 +3,8 @@ using System; using System.Diagnostics; +using System.IO; +using System.Text.Encodings.Web; using System.Threading.Tasks; using Microsoft.AspNetCore.Html; using Microsoft.AspNetCore.Http; @@ -44,18 +46,7 @@ namespace Microsoft.AspNetCore.Antiforgery CheckSSLConfig(context); var tokenSet = GetAndStoreTokens(context); - - // Though RequestToken normally contains only US-ASCII letters, numbers, '-', and '_', must assume the - // IAntiforgeryTokenSerializer implementation has been overridden. Similarly, users may choose a - // FormFieldName containing almost any character. - var content = new HtmlContentBuilder() - .AppendHtml(""); - - return content; + return new InputContent(_options.FormFieldName, tokenSet.RequestToken); } /// @@ -253,5 +244,42 @@ namespace Microsoft.AspNetCore.Antiforgery public bool IsNewCookieToken { get; set; } } + + private class InputContent : IHtmlContent + { + private readonly string _fieldName; + private readonly string _requestToken; + + public InputContent(string fieldName, string requestToken) + { + _fieldName = fieldName; + _requestToken = requestToken; + } + + // Though _requestToken normally contains only US-ASCII letters, numbers, '-', and '_', must assume the + // IAntiforgeryTokenSerializer implementation has been overridden. Similarly, users may choose a + // _fieldName containing almost any character. + public void WriteTo(TextWriter writer, HtmlEncoder encoder) + { + var builder = writer as IHtmlContentBuilder; + if (builder != null) + { + // If possible, defer encoding until we're writing to the response. + // But there's little reason to keep this IHtmlContent instance around. + builder + .AppendHtml(""); + } + + writer.Write(""); + } + } } } \ No newline at end of file From 96063e2476396fab141da8301c48ae379e72711f Mon Sep 17 00:00:00 2001 From: Ryan Nowak Date: Tue, 2 Feb 2016 09:03:53 -0800 Subject: [PATCH 071/296] Remove dependency on routing in sample Removing the routing dependency since this is moving lower in the stack. --- samples/AntiforgerySample/Startup.cs | 39 +++++++++++--------------- samples/AntiforgerySample/project.json | 1 - 2 files changed, 17 insertions(+), 23 deletions(-) diff --git a/samples/AntiforgerySample/Startup.cs b/samples/AntiforgerySample/Startup.cs index 171fe66e81..05c2026906 100644 --- a/samples/AntiforgerySample/Startup.cs +++ b/samples/AntiforgerySample/Startup.cs @@ -7,7 +7,6 @@ using Microsoft.AspNetCore.Antiforgery; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; -using Microsoft.AspNetCore.Routing; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Options; using Newtonsoft.Json; @@ -18,8 +17,6 @@ namespace AntiforgerySample { public void ConfigureServices(IServiceCollection services) { - services.AddRouting(); - // Angular's default header name for sending the XSRF token. services.AddAntiforgery(options => options.HeaderName = "X-XSRF-TOKEN"); @@ -45,30 +42,28 @@ namespace AntiforgerySample app.UseDefaultFiles(); app.UseStaticFiles(); - var routes = new RouteBuilder(app); - - routes.MapGet("api/items", (HttpContext context) => + app.Map("/api/items", a => a.Run(async context => { - var items = repository.GetItems(); - return context.Response.WriteAsync(JsonConvert.SerializeObject(items)); - }); - - routes.MapPost("api/items", async (HttpContext context) => - { - // This will throw if the token is invalid. - await antiforgery.ValidateRequestAsync(context); - - var serializer = new JsonSerializer(); - using (var reader = new JsonTextReader(new StreamReader(context.Request.Body))) + if (string.Equals("GET", context.Request.Method, StringComparison.OrdinalIgnoreCase)) { - var item = serializer.Deserialize(reader); - repository.Add(item); + var items = repository.GetItems(); + await context.Response.WriteAsync(JsonConvert.SerializeObject(items)); } + else if (string.Equals("POST", context.Request.Method, StringComparison.OrdinalIgnoreCase)) + { + // This will throw if the token is invalid. + await antiforgery.ValidateRequestAsync(context); - context.Response.StatusCode = 204; - }); + var serializer = new JsonSerializer(); + using (var reader = new JsonTextReader(new StreamReader(context.Request.Body))) + { + var item = serializer.Deserialize(reader); + repository.Add(item); + } - app.UseRouter(routes.Build()); + context.Response.StatusCode = 204; + } + })); } public static void Main(string[] args) diff --git a/samples/AntiforgerySample/project.json b/samples/AntiforgerySample/project.json index 516b8f4f9f..a02c73b3aa 100644 --- a/samples/AntiforgerySample/project.json +++ b/samples/AntiforgerySample/project.json @@ -6,7 +6,6 @@ "Microsoft.AspNetCore.Http.Abstractions": "1.0.0-*", "Microsoft.AspNetCore.Http.Extensions": "1.0.0-*", "Microsoft.AspNetCore.IISPlatformHandler": "1.0.0-*", - "Microsoft.AspNetCore.Routing.Extensions": "1.0.0-*", "Microsoft.AspNetCore.Server.Kestrel": "1.0.0-*", "Microsoft.AspNetCore.StaticFiles": "1.0.0-*", "Microsoft.NETCore.Platforms": "1.0.1-*", From 0ddfa5f0d8fed3742ab7a5f4adbb6cf0c3fe8915 Mon Sep 17 00:00:00 2001 From: Doug Bunting Date: Tue, 2 Feb 2016 14:16:30 -0800 Subject: [PATCH 072/296] Pool `MemoryStream`, `BinaryReader`, `BinaryWriter`, and `SHA256` instances - #23 part 2 - reduce `byte[]` and `char[]` allocations because all have internal buffers - fortunately, only `MemoryStream` has an unbounded buffer --- .../AntiforgerySerializationContext.cs | 109 ++++++++++++++++++ .../BinaryBlob.cs | 4 +- .../DefaultAntiforgeryTokenSerializer.cs | 89 ++++++++------ .../DefaultClaimUidExtractor.cs | 54 +++++---- ...ySerializationContextPooledObjectPolicy.cs | 23 ++++ .../ServiceCollectionExtensions.cs | 11 ++ .../project.json | 3 +- .../DefaultAntiforgeryTokenSerializerTest.cs | 12 +- .../DefaultAntiforgeryTokenStoreTest.cs | 18 +-- .../DefaultClaimUidExtractorTest.cs | 11 +- 10 files changed, 261 insertions(+), 73 deletions(-) create mode 100644 src/Microsoft.AspNetCore.Antiforgery/AntiforgerySerializationContext.cs create mode 100644 src/Microsoft.AspNetCore.Antiforgery/Internal/AntiforgerySerializationContextPooledObjectPolicy.cs diff --git a/src/Microsoft.AspNetCore.Antiforgery/AntiforgerySerializationContext.cs b/src/Microsoft.AspNetCore.Antiforgery/AntiforgerySerializationContext.cs new file mode 100644 index 0000000000..969df3428e --- /dev/null +++ b/src/Microsoft.AspNetCore.Antiforgery/AntiforgerySerializationContext.cs @@ -0,0 +1,109 @@ +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System.IO; +using System.Security.Cryptography; +using System.Text; + +namespace Microsoft.AspNetCore.Antiforgery +{ + public class AntiforgerySerializationContext + { + // Avoid allocating 256 bytes (the default) and using 18 (the AntiforgeryToken minimum). 64 bytes is enough for + // a short username or claim UID and some additional data. MemoryStream bumps capacity to 256 if exceeded. + private const int InitialStreamSize = 64; + + // Don't let the MemoryStream grow beyond 1 MB. + private const int MaximumStreamSize = 0x100000; + + private MemoryStream _memory; + private BinaryReader _reader; + private BinaryWriter _writer; + private SHA256 _sha256; + + public MemoryStream Stream + { + get + { + if (_memory == null) + { + _memory = new MemoryStream(InitialStreamSize); + } + + return _memory; + } + private set + { + _memory = value; + } + } + + public BinaryReader Reader + { + get + { + if (_reader == null) + { + // Leave open to clean up correctly even if only one of the reader or writer has been created. + _reader = new BinaryReader(Stream, Encoding.UTF8, leaveOpen: true); + } + + return _reader; + } + private set + { + _reader = value; + } + } + + public BinaryWriter Writer + { + get + { + if (_writer == null) + { + // Leave open to clean up correctly even if only one of the reader or writer has been created. + _writer = new BinaryWriter(Stream, Encoding.UTF8, leaveOpen: true); + } + + return _writer; + } + private set + { + _writer = value; + } + } + + public SHA256 Sha256 + { + get + { + if (_sha256 == null) + { + _sha256 = SHA256.Create(); + } + + return _sha256; + } + private set + { + _sha256 = value; + } + } + + public void Reset() + { + if (Stream.Capacity > MaximumStreamSize) + { + Stream = null; + Reader = null; + Writer = null; + } + else + { + Stream.Position = 0L; + Stream.SetLength(0L); + } + } + } +} diff --git a/src/Microsoft.AspNetCore.Antiforgery/BinaryBlob.cs b/src/Microsoft.AspNetCore.Antiforgery/BinaryBlob.cs index 9cb78296b5..140317ef27 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/BinaryBlob.cs +++ b/src/Microsoft.AspNetCore.Antiforgery/BinaryBlob.cs @@ -72,8 +72,8 @@ namespace Microsoft.AspNetCore.Antiforgery return false; } - Debug.Assert(this._data.Length == other._data.Length); - return AreByteArraysEqual(this._data, other._data); + Debug.Assert(_data.Length == other._data.Length); + return AreByteArraysEqual(_data, other._data); } public byte[] GetData() diff --git a/src/Microsoft.AspNetCore.Antiforgery/DefaultAntiforgeryTokenSerializer.cs b/src/Microsoft.AspNetCore.Antiforgery/DefaultAntiforgeryTokenSerializer.cs index 7c48a9d3d3..c606c1cc9d 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/DefaultAntiforgeryTokenSerializer.cs +++ b/src/Microsoft.AspNetCore.Antiforgery/DefaultAntiforgeryTokenSerializer.cs @@ -5,42 +5,54 @@ using System; using System.IO; using Microsoft.AspNetCore.DataProtection; using Microsoft.AspNetCore.WebUtilities; +using Microsoft.Extensions.ObjectPool; namespace Microsoft.AspNetCore.Antiforgery { public class DefaultAntiforgeryTokenSerializer : IAntiforgeryTokenSerializer { private static readonly string Purpose = "Microsoft.AspNetCore.Antiforgery.AntiforgeryToken.v1"; - - private readonly IDataProtector _cryptoSystem; private const byte TokenVersion = 0x01; - public DefaultAntiforgeryTokenSerializer(IDataProtectionProvider provider) + private readonly IDataProtector _cryptoSystem; + private readonly ObjectPool _pool; + + public DefaultAntiforgeryTokenSerializer( + IDataProtectionProvider provider, + ObjectPool pool) { if (provider == null) { throw new ArgumentNullException(nameof(provider)); } + if (pool == null) + { + throw new ArgumentNullException(nameof(pool)); + } + _cryptoSystem = provider.CreateProtector(Purpose); + _pool = pool; } public AntiforgeryToken Deserialize(string serializedToken) { + var serializationContext = _pool.Get(); + Exception innerException = null; try { var tokenBytes = WebEncoders.Base64UrlDecode(serializedToken); - using (var stream = new MemoryStream(_cryptoSystem.Unprotect(tokenBytes))) + var unprotectedBytes = _cryptoSystem.Unprotect(tokenBytes); + var stream = serializationContext.Stream; + stream.Write(unprotectedBytes, 0, unprotectedBytes.Length); + stream.Position = 0L; + + var reader = serializationContext.Reader; + var token = Deserialize(reader); + if (token != null) { - using (var reader = new BinaryReader(stream)) - { - var token = DeserializeImpl(reader); - if (token != null) - { - return token; - } - } + return token; } } catch (Exception ex) @@ -48,6 +60,10 @@ namespace Microsoft.AspNetCore.Antiforgery // swallow all exceptions - homogenize error if something went wrong innerException = ex; } + finally + { + _pool.Return(serializationContext); + } // if we reached this point, something went wrong deserializing throw new InvalidOperationException(Resources.AntiforgeryToken_DeserializationFailed, innerException); @@ -65,7 +81,7 @@ namespace Microsoft.AspNetCore.Antiforgery * | `- Username: UTF-8 string with 7-bit integer length prefix * `- AdditionalData: UTF-8 string with 7-bit integer length prefix */ - private static AntiforgeryToken DeserializeImpl(BinaryReader reader) + private static AntiforgeryToken Deserialize(BinaryReader reader) { // we can only consume tokens of the same serialized version that we generate var embeddedVersion = reader.ReadByte(); @@ -113,33 +129,38 @@ namespace Microsoft.AspNetCore.Antiforgery throw new ArgumentNullException(nameof(token)); } - using (var stream = new MemoryStream()) + var serializationContext = _pool.Get(); + + try { - using (var writer = new BinaryWriter(stream)) + var writer = serializationContext.Writer; + writer.Write(TokenVersion); + writer.Write(token.SecurityToken.GetData()); + writer.Write(token.IsCookieToken); + + if (!token.IsCookieToken) { - writer.Write(TokenVersion); - writer.Write(token.SecurityToken.GetData()); - writer.Write(token.IsCookieToken); - - if (!token.IsCookieToken) + if (token.ClaimUid != null) { - if (token.ClaimUid != null) - { - writer.Write(true /* isClaimsBased */); - writer.Write(token.ClaimUid.GetData()); - } - else - { - writer.Write(false /* isClaimsBased */); - writer.Write(token.Username); - } - - writer.Write(token.AdditionalData); + writer.Write(true /* isClaimsBased */); + writer.Write(token.ClaimUid.GetData()); + } + else + { + writer.Write(false /* isClaimsBased */); + writer.Write(token.Username); } - writer.Flush(); - return WebEncoders.Base64UrlEncode(_cryptoSystem.Protect(stream.ToArray())); + writer.Write(token.AdditionalData); } + + writer.Flush(); + var stream = serializationContext.Stream; + return WebEncoders.Base64UrlEncode(_cryptoSystem.Protect(stream.ToArray())); + } + finally + { + _pool.Return(serializationContext); } } } diff --git a/src/Microsoft.AspNetCore.Antiforgery/DefaultClaimUidExtractor.cs b/src/Microsoft.AspNetCore.Antiforgery/DefaultClaimUidExtractor.cs index 8220cbf166..66ddf13743 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/DefaultClaimUidExtractor.cs +++ b/src/Microsoft.AspNetCore.Antiforgery/DefaultClaimUidExtractor.cs @@ -3,10 +3,9 @@ using System; using System.Collections.Generic; -using System.IO; using System.Linq; using System.Security.Claims; -using System.Security.Cryptography; +using Microsoft.Extensions.ObjectPool; namespace Microsoft.AspNetCore.Antiforgery { @@ -15,6 +14,13 @@ namespace Microsoft.AspNetCore.Antiforgery /// public class DefaultClaimUidExtractor : IClaimUidExtractor { + private readonly ObjectPool _pool; + + public DefaultClaimUidExtractor(ObjectPool pool) + { + _pool = pool; + } + /// public string ExtractClaimUid(ClaimsIdentity claimsIdentity) { @@ -25,16 +31,15 @@ namespace Microsoft.AspNetCore.Antiforgery } var uniqueIdentifierParameters = GetUniqueIdentifierParameters(claimsIdentity); - var claimUidBytes = ComputeSHA256(uniqueIdentifierParameters); + var claimUidBytes = ComputeSha256(uniqueIdentifierParameters); return Convert.ToBase64String(claimUidBytes); } // Internal for testing internal static IEnumerable GetUniqueIdentifierParameters(ClaimsIdentity claimsIdentity) { - var nameIdentifierClaim = claimsIdentity.FindFirst(claim => - String.Equals(ClaimTypes.NameIdentifier, - claim.Type, StringComparison.Ordinal)); + var nameIdentifierClaim = claimsIdentity.FindFirst( + claim => string.Equals(ClaimTypes.NameIdentifier, claim.Type, StringComparison.Ordinal)); if (nameIdentifierClaim != null && !string.IsNullOrEmpty(nameIdentifierClaim.Value)) { return new string[] @@ -47,7 +52,8 @@ namespace Microsoft.AspNetCore.Antiforgery // We do not understand this ClaimsIdentity, fallback on serializing the entire claims Identity. var claims = claimsIdentity.Claims.ToList(); claims.Sort((a, b) => string.Compare(a.Type, b.Type, StringComparison.Ordinal)); - var identifierParameters = new List(); + + var identifierParameters = new List(claims.Count * 2); foreach (var claim in claims) { identifierParameters.Add(claim.Type); @@ -57,25 +63,29 @@ namespace Microsoft.AspNetCore.Antiforgery return identifierParameters; } - private static byte[] ComputeSHA256(IEnumerable parameters) + private byte[] ComputeSha256(IEnumerable parameters) { - using (var stream = new MemoryStream()) + var serializationContext = _pool.Get(); + + try { - using (var writer = new BinaryWriter(stream)) + var writer = serializationContext.Writer; + foreach (string parameter in parameters) { - foreach (string parameter in parameters) - { - writer.Write(parameter); // also writes the length as a prefix; unambiguous - } - - writer.Flush(); - - using (var sha256 = SHA256.Create()) - { - var bytes = sha256.ComputeHash(stream.ToArray(), 0, checked((int)stream.Length)); - return bytes; - } + writer.Write(parameter); // also writes the length as a prefix; unambiguous } + + writer.Flush(); + + var sha256 = serializationContext.Sha256; + var stream = serializationContext.Stream; + var bytes = sha256.ComputeHash(stream.ToArray(), 0, checked((int)stream.Length)); + + return bytes; + } + finally + { + _pool.Return(serializationContext); } } } diff --git a/src/Microsoft.AspNetCore.Antiforgery/Internal/AntiforgerySerializationContextPooledObjectPolicy.cs b/src/Microsoft.AspNetCore.Antiforgery/Internal/AntiforgerySerializationContextPooledObjectPolicy.cs new file mode 100644 index 0000000000..0a6163141b --- /dev/null +++ b/src/Microsoft.AspNetCore.Antiforgery/Internal/AntiforgerySerializationContextPooledObjectPolicy.cs @@ -0,0 +1,23 @@ +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using Microsoft.Extensions.ObjectPool; + +namespace Microsoft.AspNetCore.Antiforgery.Internal +{ + public class AntiforgerySerializationContextPooledObjectPolicy + : IPooledObjectPolicy + { + public AntiforgerySerializationContext Create() + { + return new AntiforgerySerializationContext(); + } + + public bool Return(AntiforgerySerializationContext obj) + { + obj.Reset(); + + return true; + } + } +} diff --git a/src/Microsoft.AspNetCore.Antiforgery/ServiceCollectionExtensions.cs b/src/Microsoft.AspNetCore.Antiforgery/ServiceCollectionExtensions.cs index 26839b935f..4a8fe1cf58 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/ServiceCollectionExtensions.cs +++ b/src/Microsoft.AspNetCore.Antiforgery/ServiceCollectionExtensions.cs @@ -3,7 +3,9 @@ using System; using Microsoft.AspNetCore.Antiforgery; +using Microsoft.AspNetCore.Antiforgery.Internal; using Microsoft.Extensions.DependencyInjection.Extensions; +using Microsoft.Extensions.ObjectPool; using Microsoft.Extensions.Options; namespace Microsoft.Extensions.DependencyInjection @@ -30,6 +32,15 @@ namespace Microsoft.Extensions.DependencyInjection services.TryAddSingleton(); services.TryAddScoped(); services.TryAddSingleton(); + + services.TryAddSingleton(new DefaultObjectPoolProvider()); + services.TryAddSingleton>(serviceProvider => + { + var provider = serviceProvider.GetRequiredService(); + var policy = new AntiforgerySerializationContextPooledObjectPolicy(); + return provider.Create(policy); + }); + return services; } diff --git a/src/Microsoft.AspNetCore.Antiforgery/project.json b/src/Microsoft.AspNetCore.Antiforgery/project.json index 37585292cb..1499e577c7 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/project.json +++ b/src/Microsoft.AspNetCore.Antiforgery/project.json @@ -13,7 +13,8 @@ "Microsoft.AspNetCore.DataProtection": "1.0.0-*", "Microsoft.AspNetCore.Html.Abstractions": "1.0.0-*", "Microsoft.AspNetCore.Http.Abstractions": "1.0.0-*", - "Microsoft.AspNetCore.WebUtilities": "1.0.0-*" + "Microsoft.AspNetCore.WebUtilities": "1.0.0-*", + "Microsoft.Extensions.ObjectPool": "1.0.0-*" }, "frameworks": { "dotnet5.4": { }, diff --git a/test/Microsoft.AspNetCore.Antiforgery.Test/DefaultAntiforgeryTokenSerializerTest.cs b/test/Microsoft.AspNetCore.Antiforgery.Test/DefaultAntiforgeryTokenSerializerTest.cs index 519bc85f8b..97193e59e6 100644 --- a/test/Microsoft.AspNetCore.Antiforgery.Test/DefaultAntiforgeryTokenSerializerTest.cs +++ b/test/Microsoft.AspNetCore.Antiforgery.Test/DefaultAntiforgeryTokenSerializerTest.cs @@ -4,7 +4,9 @@ using System; using System.Collections.Generic; using System.Linq; +using Microsoft.AspNetCore.Antiforgery.Internal; using Microsoft.AspNetCore.DataProtection; +using Microsoft.Extensions.ObjectPool; using Moq; using Xunit; @@ -15,6 +17,8 @@ namespace Microsoft.AspNetCore.Antiforgery private static readonly Mock _dataProtector = GetDataProtector(); private static readonly BinaryBlob _claimUid = new BinaryBlob(256, new byte[] { 0x6F, 0x16, 0x48, 0xE9, 0x72, 0x49, 0xAA, 0x58, 0x75, 0x40, 0x36, 0xA6, 0x7E, 0x24, 0x8C, 0xF0, 0x44, 0xF0, 0x7E, 0xCF, 0xB0, 0xED, 0x38, 0x75, 0x56, 0xCE, 0x02, 0x9A, 0x4F, 0x9A, 0x40, 0xE0 }); private static readonly BinaryBlob _securityToken = new BinaryBlob(128, new byte[] { 0x70, 0x5E, 0xED, 0xCC, 0x7D, 0x42, 0xF1, 0xD6, 0xB3, 0xB9, 0x8A, 0x59, 0x36, 0x25, 0xBB, 0x4C }); + private static readonly ObjectPool _pool = + new DefaultObjectPoolProvider().Create(new AntiforgerySerializationContextPooledObjectPolicy()); private const byte _salt = 0x05; [Theory] @@ -45,7 +49,7 @@ namespace Microsoft.AspNetCore.Antiforgery public void Deserialize_BadToken_Throws(string serializedToken) { // Arrange - var testSerializer = new DefaultAntiforgeryTokenSerializer(_dataProtector.Object); + var testSerializer = new DefaultAntiforgeryTokenSerializer(_dataProtector.Object, _pool); // Act & assert var ex = Assert.Throws(() => testSerializer.Deserialize(serializedToken)); @@ -56,7 +60,7 @@ namespace Microsoft.AspNetCore.Antiforgery public void Serialize_FieldToken_WithClaimUid_TokenRoundTripSuccessful() { // Arrange - var testSerializer = new DefaultAntiforgeryTokenSerializer(_dataProtector.Object); + var testSerializer = new DefaultAntiforgeryTokenSerializer(_dataProtector.Object, _pool); //"01" // Version //+ "705EEDCC7D42F1D6B3B98A593625BB4C" // SecurityToken @@ -86,7 +90,7 @@ namespace Microsoft.AspNetCore.Antiforgery public void Serialize_FieldToken_WithUsername_TokenRoundTripSuccessful() { // Arrange - var testSerializer = new DefaultAntiforgeryTokenSerializer(_dataProtector.Object); + var testSerializer = new DefaultAntiforgeryTokenSerializer(_dataProtector.Object, _pool); //"01" // Version //+ "705EEDCC7D42F1D6B3B98A593625BB4C" // SecurityToken @@ -117,7 +121,7 @@ namespace Microsoft.AspNetCore.Antiforgery public void Serialize_CookieToken_TokenRoundTripSuccessful() { // Arrange - var testSerializer = new DefaultAntiforgeryTokenSerializer(_dataProtector.Object); + var testSerializer = new DefaultAntiforgeryTokenSerializer(_dataProtector.Object, _pool); //"01" // Version //+ "705EEDCC7D42F1D6B3B98A593625BB4C" // SecurityToken diff --git a/test/Microsoft.AspNetCore.Antiforgery.Test/DefaultAntiforgeryTokenStoreTest.cs b/test/Microsoft.AspNetCore.Antiforgery.Test/DefaultAntiforgeryTokenStoreTest.cs index de71ea9cf1..e1c566c77d 100644 --- a/test/Microsoft.AspNetCore.Antiforgery.Test/DefaultAntiforgeryTokenStoreTest.cs +++ b/test/Microsoft.AspNetCore.Antiforgery.Test/DefaultAntiforgeryTokenStoreTest.cs @@ -4,10 +4,12 @@ using System; using System.Collections.Generic; using System.Threading.Tasks; +using Microsoft.AspNetCore.Antiforgery.Internal; using Microsoft.AspNetCore.DataProtection; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.Internal; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.ObjectPool; using Microsoft.Extensions.Primitives; using Moq; using Xunit; @@ -16,6 +18,8 @@ namespace Microsoft.AspNetCore.Antiforgery { public class DefaultAntiforgeryTokenStoreTest { + private static readonly ObjectPool _pool = + new DefaultObjectPoolProvider().Create(new AntiforgerySerializationContextPooledObjectPolicy()); private readonly string _cookieName = "cookie-name"; [Fact] @@ -182,7 +186,7 @@ namespace Microsoft.AspNetCore.Antiforgery var exception = await Assert.ThrowsAsync( async () => await tokenStore.GetRequestTokensAsync(httpContext)); - // Assert + // Assert Assert.Equal("The required antiforgery cookie \"cookie-name\" is not present.", exception.Message); } @@ -209,13 +213,13 @@ namespace Microsoft.AspNetCore.Antiforgery var tokenStore = new DefaultAntiforgeryTokenStore( optionsAccessor: new TestOptionsManager(options), - tokenSerializer: new DefaultAntiforgeryTokenSerializer(new EphemeralDataProtectionProvider())); + tokenSerializer: new DefaultAntiforgeryTokenSerializer(new EphemeralDataProtectionProvider(), _pool)); // Act var exception = await Assert.ThrowsAsync( async () => await tokenStore.GetRequestTokensAsync(httpContext)); - // Assert + // Assert Assert.Equal("The required antiforgery form field \"form-field-name\" is not present.", exception.Message); } @@ -244,7 +248,7 @@ namespace Microsoft.AspNetCore.Antiforgery var tokenStore = new DefaultAntiforgeryTokenStore( optionsAccessor: new TestOptionsManager(options), - tokenSerializer: new DefaultAntiforgeryTokenSerializer(new EphemeralDataProtectionProvider())); + tokenSerializer: new DefaultAntiforgeryTokenSerializer(new EphemeralDataProtectionProvider(), _pool)); // Act var tokens = await tokenStore.GetRequestTokensAsync(httpContext); @@ -279,7 +283,7 @@ namespace Microsoft.AspNetCore.Antiforgery var tokenStore = new DefaultAntiforgeryTokenStore( optionsAccessor: new TestOptionsManager(options), - tokenSerializer: new DefaultAntiforgeryTokenSerializer(new EphemeralDataProtectionProvider())); + tokenSerializer: new DefaultAntiforgeryTokenSerializer(new EphemeralDataProtectionProvider(), _pool)); // Act var tokens = await tokenStore.GetRequestTokensAsync(httpContext); @@ -312,7 +316,7 @@ namespace Microsoft.AspNetCore.Antiforgery var tokenStore = new DefaultAntiforgeryTokenStore( optionsAccessor: new TestOptionsManager(options), - tokenSerializer: new DefaultAntiforgeryTokenSerializer(new EphemeralDataProtectionProvider())); + tokenSerializer: new DefaultAntiforgeryTokenSerializer(new EphemeralDataProtectionProvider(), _pool)); // Act var exception = await Assert.ThrowsAsync( @@ -349,7 +353,7 @@ namespace Microsoft.AspNetCore.Antiforgery var exception = await Assert.ThrowsAsync( async () => await tokenStore.GetRequestTokensAsync(httpContext)); - // Assert + // Assert Assert.Equal( "The required antiforgery request token was not provided in either form field \"form-field-name\" " + "or header value \"header-name\".", diff --git a/test/Microsoft.AspNetCore.Antiforgery.Test/DefaultClaimUidExtractorTest.cs b/test/Microsoft.AspNetCore.Antiforgery.Test/DefaultClaimUidExtractorTest.cs index 1516ed86f5..ebb28adbf6 100644 --- a/test/Microsoft.AspNetCore.Antiforgery.Test/DefaultClaimUidExtractorTest.cs +++ b/test/Microsoft.AspNetCore.Antiforgery.Test/DefaultClaimUidExtractorTest.cs @@ -4,6 +4,8 @@ using System; using System.Linq; using System.Security.Claims; +using Microsoft.AspNetCore.Antiforgery.Internal; +using Microsoft.Extensions.ObjectPool; using Moq; using Xunit; @@ -11,11 +13,14 @@ namespace Microsoft.AspNetCore.Antiforgery { public class DefaultClaimUidExtractorTest { + private static readonly ObjectPool _pool = + new DefaultObjectPoolProvider().Create(new AntiforgerySerializationContextPooledObjectPolicy()); + [Fact] public void ExtractClaimUid_NullIdentity() { // Arrange - IClaimUidExtractor extractor = new DefaultClaimUidExtractor(); + var extractor = new DefaultClaimUidExtractor(_pool); // Act var claimUid = extractor.ExtractClaimUid(null); @@ -28,7 +33,7 @@ namespace Microsoft.AspNetCore.Antiforgery public void ExtractClaimUid_Unauthenticated() { // Arrange - IClaimUidExtractor extractor = new DefaultClaimUidExtractor(); + var extractor = new DefaultClaimUidExtractor(_pool); var mockIdentity = new Mock(); mockIdentity.Setup(o => o.IsAuthenticated) @@ -49,7 +54,7 @@ namespace Microsoft.AspNetCore.Antiforgery mockIdentity.Setup(o => o.IsAuthenticated) .Returns(true); - IClaimUidExtractor extractor = new DefaultClaimUidExtractor(); + var extractor = new DefaultClaimUidExtractor(_pool); // Act var claimUid = extractor.ExtractClaimUid(mockIdentity.Object); From 20140c4c152cf25b1d71a6991bf8fb6f3d022ac6 Mon Sep 17 00:00:00 2001 From: Ryan Nowak Date: Tue, 2 Feb 2016 10:37:39 -0800 Subject: [PATCH 073/296] Adds a IsRequestValidAsync method Some other misc cleanup - docs for IAntiforgeryTokenGenerator - Add HttpContext parameter where to all IAntiforgeryGenerator methods - rename parameters on DefaultAntiforgery --- .../DefaultAntiforgery.cs | 106 +++--- .../DefaultAntiforgeryTokenGenerator.cs | 43 ++- .../IAntiforgery.cs | 37 ++- .../IAntiforgeryTokenGenerator.cs | 40 ++- .../Properties/Resources.Designer.cs | 8 + .../Resources.resx | 3 + .../DefaultAntiforgeryTest.cs | 194 ++++++++--- .../DefaultAntiforgeryTokenGeneratorTest.cs | 308 +++++++++++------- .../project.json | 1 + 9 files changed, 510 insertions(+), 230 deletions(-) diff --git a/src/Microsoft.AspNetCore.Antiforgery/DefaultAntiforgery.cs b/src/Microsoft.AspNetCore.Antiforgery/DefaultAntiforgery.cs index c4a10c2955..2f602fb077 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/DefaultAntiforgery.cs +++ b/src/Microsoft.AspNetCore.Antiforgery/DefaultAntiforgery.cs @@ -36,75 +36,100 @@ namespace Microsoft.AspNetCore.Antiforgery } /// - public IHtmlContent GetHtml(HttpContext context) + public IHtmlContent GetHtml(HttpContext httpContext) { - if (context == null) + if (httpContext == null) { - throw new ArgumentNullException(nameof(context)); + throw new ArgumentNullException(nameof(httpContext)); } - CheckSSLConfig(context); + CheckSSLConfig(httpContext); - var tokenSet = GetAndStoreTokens(context); + var tokenSet = GetAndStoreTokens(httpContext); return new InputContent(_options.FormFieldName, tokenSet.RequestToken); } /// - public AntiforgeryTokenSet GetAndStoreTokens(HttpContext context) + public AntiforgeryTokenSet GetAndStoreTokens(HttpContext httpContext) { - if (context == null) + if (httpContext == null) { - throw new ArgumentNullException(nameof(context)); + throw new ArgumentNullException(nameof(httpContext)); } - CheckSSLConfig(context); + CheckSSLConfig(httpContext); - var tokenSet = GetTokensInternal(context); + var tokenSet = GetTokensInternal(httpContext); if (tokenSet.IsNewCookieToken) { - SaveCookieTokenAndHeader(context, tokenSet.CookieToken); + SaveCookieTokenAndHeader(httpContext, tokenSet.CookieToken); } return Serialize(tokenSet); } /// - public AntiforgeryTokenSet GetTokens(HttpContext context) + public AntiforgeryTokenSet GetTokens(HttpContext httpContext) { - if (context == null) + if (httpContext == null) { - throw new ArgumentNullException(nameof(context)); + throw new ArgumentNullException(nameof(httpContext)); } - CheckSSLConfig(context); + CheckSSLConfig(httpContext); - var tokenSet = GetTokensInternal(context); + var tokenSet = GetTokensInternal(httpContext); return Serialize(tokenSet); } /// - public async Task ValidateRequestAsync(HttpContext context) + public async Task IsRequestValidAsync(HttpContext httpContext) { - if (context == null) + if (httpContext == null) { - throw new ArgumentNullException(nameof(context)); + throw new ArgumentNullException(nameof(httpContext)); } - CheckSSLConfig(context); + CheckSSLConfig(httpContext); - var tokens = await _tokenStore.GetRequestTokensAsync(context); - ValidateTokens(context, tokens); + var tokens = await _tokenStore.GetRequestTokensAsync(httpContext); + + // Extract cookie & request tokens + var deserializedCookieToken = _tokenSerializer.Deserialize(tokens.CookieToken); + var deserializedRequestToken = _tokenSerializer.Deserialize(tokens.RequestToken); + + // Validate + string message; + return _tokenGenerator.TryValidateTokenSet( + httpContext, + deserializedCookieToken, + deserializedRequestToken, + out message); } /// - public void ValidateTokens(HttpContext context, AntiforgeryTokenSet antiforgeryTokenSet) + public async Task ValidateRequestAsync(HttpContext httpContext) { - if (context == null) + if (httpContext == null) { - throw new ArgumentNullException(nameof(context)); + throw new ArgumentNullException(nameof(httpContext)); } - CheckSSLConfig(context); + CheckSSLConfig(httpContext); + + var tokens = await _tokenStore.GetRequestTokensAsync(httpContext); + ValidateTokens(httpContext, tokens); + } + + /// + public void ValidateTokens(HttpContext httpContext, AntiforgeryTokenSet antiforgeryTokenSet) + { + if (httpContext == null) + { + throw new ArgumentNullException(nameof(httpContext)); + } + + CheckSSLConfig(httpContext); if (string.IsNullOrEmpty(antiforgeryTokenSet.CookieToken)) { @@ -125,25 +150,30 @@ namespace Microsoft.AspNetCore.Antiforgery var deserializedRequestToken = _tokenSerializer.Deserialize(antiforgeryTokenSet.RequestToken); // Validate - _tokenGenerator.ValidateTokens( - context, + string message; + if (!_tokenGenerator.TryValidateTokenSet( + httpContext, deserializedCookieToken, - deserializedRequestToken); + deserializedRequestToken, + out message)) + { + throw new AntiforgeryValidationException(message); + } } /// - public void SetCookieTokenAndHeader(HttpContext context) + public void SetCookieTokenAndHeader(HttpContext httpContext) { - if (context == null) + if (httpContext == null) { - throw new ArgumentNullException(nameof(context)); + throw new ArgumentNullException(nameof(httpContext)); } - CheckSSLConfig(context); + CheckSSLConfig(httpContext); - var cookieToken = GetCookieTokenDoesNotThrow(context); + var cookieToken = GetCookieTokenDoesNotThrow(httpContext); cookieToken = ValidateAndGenerateNewCookieToken(cookieToken); - SaveCookieTokenAndHeader(context, cookieToken); + SaveCookieTokenAndHeader(httpContext, cookieToken); } // This method returns null if oldCookieToken is valid. @@ -208,16 +238,16 @@ namespace Microsoft.AspNetCore.Antiforgery } } - private AntiforgeryTokenSetInternal GetTokensInternal(HttpContext context) + private AntiforgeryTokenSetInternal GetTokensInternal(HttpContext httpContext) { - var cookieToken = GetCookieTokenDoesNotThrow(context); + var cookieToken = GetCookieTokenDoesNotThrow(httpContext); var newCookieToken = ValidateAndGenerateNewCookieToken(cookieToken); if (newCookieToken != null) { cookieToken = newCookieToken; } var requestToken = _tokenGenerator.GenerateRequestToken( - context, + httpContext, cookieToken); return new AntiforgeryTokenSetInternal() diff --git a/src/Microsoft.AspNetCore.Antiforgery/DefaultAntiforgeryTokenGenerator.cs b/src/Microsoft.AspNetCore.Antiforgery/DefaultAntiforgeryTokenGenerator.cs index 27e82d9a96..36c01beff7 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/DefaultAntiforgeryTokenGenerator.cs +++ b/src/Microsoft.AspNetCore.Antiforgery/DefaultAntiforgeryTokenGenerator.cs @@ -2,7 +2,6 @@ // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; -using System.Diagnostics; using System.Security.Claims; using System.Security.Principal; using Microsoft.AspNetCore.Http; @@ -22,6 +21,7 @@ namespace Microsoft.AspNetCore.Antiforgery _additionalDataProvider = additionalDataProvider; } + /// public AntiforgeryToken GenerateCookieToken() { return new AntiforgeryToken() @@ -31,6 +31,7 @@ namespace Microsoft.AspNetCore.Antiforgery }; } + /// public AntiforgeryToken GenerateRequestToken( HttpContext httpContext, AntiforgeryToken cookieToken) @@ -40,7 +41,17 @@ namespace Microsoft.AspNetCore.Antiforgery throw new ArgumentNullException(nameof(httpContext)); } - Debug.Assert(IsCookieTokenValid(cookieToken)); + if (cookieToken == null) + { + throw new ArgumentNullException(nameof(cookieToken)); + } + + if (!IsCookieTokenValid(cookieToken)) + { + throw new ArgumentException( + Resources.Antiforgery_CookieToken_IsInvalid, + nameof(cookieToken)); + } var requestToken = new AntiforgeryToken() { @@ -87,15 +98,18 @@ namespace Microsoft.AspNetCore.Antiforgery return requestToken; } + /// public bool IsCookieTokenValid(AntiforgeryToken cookieToken) { - return (cookieToken != null && cookieToken.IsCookieToken); + return cookieToken != null && cookieToken.IsCookieToken; } - public void ValidateTokens( + /// + public bool TryValidateTokenSet( HttpContext httpContext, AntiforgeryToken cookieToken, - AntiforgeryToken requestToken) + AntiforgeryToken requestToken, + out string message) { if (httpContext == null) { @@ -119,13 +133,15 @@ namespace Microsoft.AspNetCore.Antiforgery // Do the tokens have the correct format? if (!cookieToken.IsCookieToken || requestToken.IsCookieToken) { - throw new AntiforgeryValidationException(Resources.AntiforgeryToken_TokensSwapped); + message = Resources.AntiforgeryToken_TokensSwapped; + return false; } // Are the security tokens embedded in each incoming token identical? if (!object.Equals(cookieToken.SecurityToken, requestToken.SecurityToken)) { - throw new AntiforgeryValidationException(Resources.AntiforgeryToken_SecurityTokenMismatch); + message = Resources.AntiforgeryToken_SecurityTokenMismatch; + return false; } // Is the incoming token meant for the current user? @@ -153,21 +169,26 @@ namespace Microsoft.AspNetCore.Antiforgery if (!comparer.Equals(requestToken.Username, currentUsername)) { - throw new AntiforgeryValidationException( - Resources.FormatAntiforgeryToken_UsernameMismatch(requestToken.Username, currentUsername)); + message = Resources.FormatAntiforgeryToken_UsernameMismatch(requestToken.Username, currentUsername); + return false; } if (!object.Equals(requestToken.ClaimUid, currentClaimUid)) { - throw new AntiforgeryValidationException(Resources.AntiforgeryToken_ClaimUidMismatch); + message = Resources.AntiforgeryToken_ClaimUidMismatch; + return false; } // Is the AdditionalData valid? if (_additionalDataProvider != null && !_additionalDataProvider.ValidateAdditionalData(httpContext, requestToken.AdditionalData)) { - throw new AntiforgeryValidationException(Resources.AntiforgeryToken_AdditionalDataCheckFailed); + message = Resources.AntiforgeryToken_AdditionalDataCheckFailed; + return false; } + + message = null; + return true; } private static BinaryBlob GetClaimUidBlob(string base64ClaimUid) diff --git a/src/Microsoft.AspNetCore.Antiforgery/IAntiforgery.cs b/src/Microsoft.AspNetCore.Antiforgery/IAntiforgery.cs index ca2d8341ae..d2eac4c95a 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/IAntiforgery.cs +++ b/src/Microsoft.AspNetCore.Antiforgery/IAntiforgery.cs @@ -16,7 +16,7 @@ namespace Microsoft.AspNetCore.Antiforgery /// /// Generates an <input type="hidden"> element for an antiforgery token. /// - /// The associated with the current request. + /// The associated with the current request. /// /// A containing an <input type="hidden"> element. This element should be put /// inside a <form>. @@ -25,50 +25,63 @@ namespace Microsoft.AspNetCore.Antiforgery /// This method has a side effect: /// A response cookie is set if there is no valid cookie associated with the request. /// - IHtmlContent GetHtml(HttpContext context); + IHtmlContent GetHtml(HttpContext httpContext); /// /// Generates an for this request and stores the cookie token /// in the response. /// - /// The associated with the current request. + /// The associated with the current request. /// An with tokens for the response. /// /// This method has a side effect: /// A response cookie is set if there is no valid cookie associated with the request. /// - AntiforgeryTokenSet GetAndStoreTokens(HttpContext context); + AntiforgeryTokenSet GetAndStoreTokens(HttpContext httpContext); /// /// Generates an for this request. /// - /// The associated with the current request. + /// The associated with the current request. /// /// Unlike , this method has no side effect. The caller /// is responsible for setting the response cookie and injecting the returned /// form token as appropriate. /// - AntiforgeryTokenSet GetTokens(HttpContext context); + AntiforgeryTokenSet GetTokens(HttpContext httpContext); + + /// + /// Asynchronously returns a value indicating whether the request contains a valid antiforgery token. + /// + /// The associated with the current request. + /// + /// A that, when completed, returns true if the request contains a + /// valid antiforgery token, otherwise returns false. + /// + Task IsRequestValidAsync(HttpContext httpContext); /// /// Validates an antiforgery token that was supplied as part of the request. /// - /// The associated with the current request. - Task ValidateRequestAsync(HttpContext context); + /// The associated with the current request. + /// + /// Thrown when the request does not include a valid antiforgery token. + /// + Task ValidateRequestAsync(HttpContext httpContext); /// /// Validates an for the current request. /// - /// The associated with the current request. + /// The associated with the current request. /// /// The (cookie and request token) for this request. /// - void ValidateTokens(HttpContext context, AntiforgeryTokenSet antiforgeryTokenSet); + void ValidateTokens(HttpContext httpContext, AntiforgeryTokenSet antiforgeryTokenSet); /// /// Generates and stores an antiforgery cookie token if one is not available or not valid. /// - /// The associated with the current request. - void SetCookieTokenAndHeader(HttpContext context); + /// The associated with the current request. + void SetCookieTokenAndHeader(HttpContext httpContext); } } diff --git a/src/Microsoft.AspNetCore.Antiforgery/IAntiforgeryTokenGenerator.cs b/src/Microsoft.AspNetCore.Antiforgery/IAntiforgeryTokenGenerator.cs index 79fc447a45..e615d8c933 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/IAntiforgeryTokenGenerator.cs +++ b/src/Microsoft.AspNetCore.Antiforgery/IAntiforgeryTokenGenerator.cs @@ -10,23 +10,41 @@ namespace Microsoft.AspNetCore.Antiforgery /// public interface IAntiforgeryTokenGenerator { - // Generates a new random cookie token. + /// + /// Generates a new random cookie token. + /// + /// An . AntiforgeryToken GenerateCookieToken(); - // Given a cookie token, generates a corresponding request token. - // The incoming cookie token must be valid. - AntiforgeryToken GenerateRequestToken( - HttpContext httpContext, - AntiforgeryToken cookieToken); + /// + /// Generates a request token corresponding to . + /// + /// The associated with the current request. + /// A valid cookie token. + /// An . + AntiforgeryToken GenerateRequestToken(HttpContext httpContext, AntiforgeryToken cookieToken); - // Determines whether an existing cookie token is valid (well-formed). - // If it is not, the caller must call GenerateCookieToken() before calling GenerateFormToken(). + /// + /// Attempts to validate a cookie token. + /// + /// A valid cookie token. + /// true if the cookie token is valid, otherwise false. bool IsCookieTokenValid(AntiforgeryToken cookieToken); - // Validates a (cookie, request) token pair. - void ValidateTokens( + /// + /// Attempts to validate a cookie and request token set for the given . + /// + /// The associated with the current request. + /// A cookie token. + /// A request token. + /// + /// Will be set to the validation message if the tokens are invalid, otherwise null. + /// + /// true if the tokens are valid, otherwise false. + bool TryValidateTokenSet( HttpContext httpContext, AntiforgeryToken cookieToken, - AntiforgeryToken requestToken); + AntiforgeryToken requestToken, + out string message); } } \ No newline at end of file diff --git a/src/Microsoft.AspNetCore.Antiforgery/Properties/Resources.Designer.cs b/src/Microsoft.AspNetCore.Antiforgery/Properties/Resources.Designer.cs index 87e05dabab..6b12221bd8 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/Properties/Resources.Designer.cs +++ b/src/Microsoft.AspNetCore.Antiforgery/Properties/Resources.Designer.cs @@ -138,6 +138,14 @@ namespace Microsoft.AspNetCore.Antiforgery return string.Format(CultureInfo.CurrentCulture, GetString("AntiforgeryWorker_RequireSSL"), p0, p1, p2); } + /// + /// The required antiforgery cookie "{0}" is not present. + /// + internal static string Antiforgery_CookieToken_IsInvalid + { + get { return GetString("Antiforgery_CookieToken_IsInvalid"); } + } + /// /// The required antiforgery cookie "{0}" is not present. /// diff --git a/src/Microsoft.AspNetCore.Antiforgery/Resources.resx b/src/Microsoft.AspNetCore.Antiforgery/Resources.resx index 8e84c4cac5..bda2f0f353 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/Resources.resx +++ b/src/Microsoft.AspNetCore.Antiforgery/Resources.resx @@ -143,6 +143,9 @@ The antiforgery system has the configuration value {0}.{1} = {2}, but the current request is not an SSL request. 0 = nameof(AntiforgeryOptions), 1 = nameof(RequireSsl), 2 = bool.TrueString + + The antiforgery cookie token is invalid. + The required antiforgery cookie "{0}" is not present. diff --git a/test/Microsoft.AspNetCore.Antiforgery.Test/DefaultAntiforgeryTest.cs b/test/Microsoft.AspNetCore.Antiforgery.Test/DefaultAntiforgeryTest.cs index ddb190a256..cba6a7dce4 100644 --- a/test/Microsoft.AspNetCore.Antiforgery.Test/DefaultAntiforgeryTest.cs +++ b/test/Microsoft.AspNetCore.Antiforgery.Test/DefaultAntiforgeryTest.cs @@ -8,6 +8,7 @@ using System.Threading.Tasks; using Microsoft.AspNetCore.Html; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.Internal; +using Microsoft.AspNetCore.Testing; using Microsoft.Extensions.Options; using Microsoft.Extensions.WebEncoders.Testing; using Moq; @@ -34,9 +35,31 @@ namespace Microsoft.AspNetCore.Antiforgery var exception = await Assert.ThrowsAsync( async () => await antiforgery.ValidateRequestAsync(httpContext)); Assert.Equal( - @"The antiforgery system has the configuration value AntiforgeryOptions.RequireSsl = true, " + - "but the current request is not an SSL request.", - exception.Message); + @"The antiforgery system has the configuration value AntiforgeryOptions.RequireSsl = true, " + + "but the current request is not an SSL request.", + exception.Message); + } + + [Fact] + public async Task ChecksSSL_IsRequestValidAsync_Throws() + { + // Arrange + var httpContext = new DefaultHttpContext(); + + var options = new AntiforgeryOptions() + { + RequireSsl = true + }; + + var antiforgery = GetAntiforgery(options); + + // Act & Assert + var exception = await Assert.ThrowsAsync( + async () => await antiforgery.IsRequestValidAsync(httpContext)); + Assert.Equal( + @"The antiforgery system has the configuration value AntiforgeryOptions.RequireSsl = true, " + + "but the current request is not an SSL request.", + exception.Message); } [Fact] @@ -56,9 +79,9 @@ namespace Microsoft.AspNetCore.Antiforgery var exception = Assert.Throws( () => antiforgery.ValidateTokens(httpContext, new AntiforgeryTokenSet("hello", "world"))); Assert.Equal( - @"The antiforgery system has the configuration value AntiforgeryOptions.RequireSsl = true, " + - "but the current request is not an SSL request.", - exception.Message); + @"The antiforgery system has the configuration value AntiforgeryOptions.RequireSsl = true, " + + "but the current request is not an SSL request.", + exception.Message); } [Fact] @@ -162,6 +185,11 @@ namespace Microsoft.AspNetCore.Antiforgery var antiforgery = GetAntiforgery(context); var encoder = new HtmlTestEncoder(); + // Setup so that the null cookie token returned is treated as invalid. + context.TokenGenerator + .Setup(o => o.IsCookieTokenValid(null)) + .Returns(false); + // Act var inputElement = antiforgery.GetHtml(context.HttpContext); @@ -197,7 +225,7 @@ namespace Microsoft.AspNetCore.Antiforgery .Setup(o => o.GetCookieToken(context.HttpContext)) .Throws(new Exception("should be swallowed")); - // Setup so that the null cookie token returned is treated as invalid. + // Setup so that the null cookie token returned is treated as invalid. context.TokenGenerator .Setup(o => o.IsCookieTokenValid(null)) .Returns(false); @@ -303,12 +331,10 @@ namespace Microsoft.AspNetCore.Antiforgery isOldCookieValid: false); // This will cause the cookieToken to be null. - context.TokenSerializer.Setup(o => o.Deserialize("serialized-old-cookie-token")) - .Throws(new Exception("should be swallowed")); + context.TokenSerializer + .Setup(o => o.Deserialize("serialized-old-cookie-token")) + .Throws(new Exception("should be swallowed")); - // Setup so that the null cookie token returned is treated as invalid. - context.TokenGenerator.Setup(o => o.IsCookieTokenValid(null)) - .Returns(false); var antiforgery = GetAntiforgery(context); // Act @@ -381,7 +407,7 @@ namespace Microsoft.AspNetCore.Antiforgery } [Fact] - public void ValidateTokens_FromInvalidStrings_Throws() + public void ValidateTokens_InvalidTokens_Throws() { // Arrange var context = CreateMockContext(new AntiforgeryOptions()); @@ -393,17 +419,20 @@ namespace Microsoft.AspNetCore.Antiforgery .Setup(o => o.Deserialize("form-token")) .Returns(context.TestTokenSet.RequestToken); - context.TokenGenerator - .Setup(o => o.ValidateTokens( - context.HttpContext, - context.TestTokenSet.OldCookieToken, - context.TestTokenSet.RequestToken)) - .Throws(new InvalidOperationException("my-message")); - context.TokenStore = null; - var antiforgery = GetAntiforgery(context); + // You can't really do Moq with out-parameters :( + var tokenGenerator = new TestTokenGenerator() + { + Message = "my-message", + }; - // Act & assert - var exception = Assert.Throws( + var antiforgery = new DefaultAntiforgery( + new TestOptionsManager(), + tokenGenerator, + context.TokenSerializer.Object, + tokenStore: null); + + // Act & Assert + var exception = Assert.Throws( () => antiforgery.ValidateTokens( context.HttpContext, new AntiforgeryTokenSet("form-token", "cookie-token"))); @@ -423,11 +452,14 @@ namespace Microsoft.AspNetCore.Antiforgery .Setup(o => o.Deserialize("form-token")) .Returns(context.TestTokenSet.RequestToken); + string message; context.TokenGenerator - .Setup(o => o.ValidateTokens( + .Setup(o => o.TryValidateTokenSet( context.HttpContext, context.TestTokenSet.OldCookieToken, - context.TestTokenSet.RequestToken)) + context.TestTokenSet.RequestToken, + out message)) + .Returns(true) .Verifiable(); context.TokenStore = null; var antiforgery = GetAntiforgery(context); @@ -450,12 +482,60 @@ namespace Microsoft.AspNetCore.Antiforgery // Act - var exception = Assert.Throws( - () => antiforgery.ValidateTokens(context.HttpContext, tokenSet)); + ExceptionAssert.ThrowsArgument( + () => antiforgery.ValidateTokens(context.HttpContext, tokenSet), + "antiforgeryTokenSet", + "The required antiforgery cookie token must be provided."); + } + + [Fact] + public async Task IsRequestValueAsync_FromStore_Failure() + { + // Arrange + var context = CreateMockContext(new AntiforgeryOptions()); + + string message; + context.TokenGenerator + .Setup(o => o.TryValidateTokenSet( + context.HttpContext, + context.TestTokenSet.OldCookieToken, + context.TestTokenSet.RequestToken, + out message)) + .Returns(false); + + var antiforgery = GetAntiforgery(context); + + // Act + var result = await antiforgery.IsRequestValidAsync(context.HttpContext); // Assert - var trimmed = exception.Message.Substring(0, exception.Message.IndexOf(Environment.NewLine)); - Assert.Equal("The required antiforgery cookie token must be provided.", trimmed); + Assert.False(result); + } + + [Fact] + public async Task IsRequestValidAsync_FromStore_Success() + { + // Arrange + var context = CreateMockContext(new AntiforgeryOptions()); + + string message; + context.TokenGenerator + .Setup(o => o.TryValidateTokenSet( + context.HttpContext, + context.TestTokenSet.OldCookieToken, + context.TestTokenSet.RequestToken, + out message)) + .Returns(true) + .Verifiable(); + + var antiforgery = GetAntiforgery(context); + + // Act + var result = await antiforgery.IsRequestValidAsync(context.HttpContext); + + // Assert + Assert.True(result); + context.TokenGenerator.Verify(); } [Fact] @@ -464,17 +544,20 @@ namespace Microsoft.AspNetCore.Antiforgery // Arrange var context = CreateMockContext(new AntiforgeryOptions()); - context.TokenGenerator - .Setup(o => o.ValidateTokens( - context.HttpContext, - context.TestTokenSet.OldCookieToken, - context.TestTokenSet.RequestToken)) - .Throws(new InvalidOperationException("my-message")); + // You can't really do Moq with out-parameters :( + var tokenGenerator = new TestTokenGenerator() + { + Message = "my-message", + }; - var antiforgery = GetAntiforgery(context); + var antiforgery = new DefaultAntiforgery( + new TestOptionsManager(), + tokenGenerator, + context.TokenSerializer.Object, + context.TokenStore.Object); // Act & assert - var exception = await Assert.ThrowsAsync( + var exception = await Assert.ThrowsAsync( async () => await antiforgery.ValidateRequestAsync(context.HttpContext)); Assert.Equal("my-message", exception.Message); } @@ -485,11 +568,14 @@ namespace Microsoft.AspNetCore.Antiforgery // Arrange var context = CreateMockContext(new AntiforgeryOptions()); + string message; context.TokenGenerator - .Setup(o => o.ValidateTokens( + .Setup(o => o.TryValidateTokenSet( context.HttpContext, context.TestTokenSet.OldCookieToken, - context.TestTokenSet.RequestToken)) + context.TestTokenSet.RequestToken, + out message)) + .Returns(true) .Verifiable(); var antiforgery = GetAntiforgery(context); @@ -696,5 +782,35 @@ namespace Microsoft.AspNetCore.Antiforgery { public AntiforgeryOptions Value { get; set; } = new AntiforgeryOptions(); } + + private class TestTokenGenerator : IAntiforgeryTokenGenerator + { + public string Message { get; set; } + + public AntiforgeryToken GenerateCookieToken() + { + throw new NotImplementedException(); + } + + public AntiforgeryToken GenerateRequestToken(HttpContext httpContext, AntiforgeryToken cookieToken) + { + throw new NotImplementedException(); + } + + public bool IsCookieTokenValid(AntiforgeryToken cookieToken) + { + throw new NotImplementedException(); + } + + public bool TryValidateTokenSet( + HttpContext httpContext, + AntiforgeryToken cookieToken, + AntiforgeryToken requestToken, + out string message) + { + message = Message; + return false; + } + } } } \ No newline at end of file diff --git a/test/Microsoft.AspNetCore.Antiforgery.Test/DefaultAntiforgeryTokenGeneratorTest.cs b/test/Microsoft.AspNetCore.Antiforgery.Test/DefaultAntiforgeryTokenGeneratorTest.cs index fbbd6a50e4..f277504d0b 100644 --- a/test/Microsoft.AspNetCore.Antiforgery.Test/DefaultAntiforgeryTokenGeneratorTest.cs +++ b/test/Microsoft.AspNetCore.Antiforgery.Test/DefaultAntiforgeryTokenGeneratorTest.cs @@ -5,6 +5,7 @@ using System; using System.Security.Claims; using System.Security.Cryptography; using Microsoft.AspNetCore.Http.Internal; +using Microsoft.AspNetCore.Testing; using Moq; using Xunit; @@ -28,7 +29,27 @@ namespace Microsoft.AspNetCore.Antiforgery } [Fact] - public void GenerateFormToken_AnonymousUser() + public void GenerateRequestToken_InvalidCookieToken() + { + // Arrange + var cookieToken = new AntiforgeryToken() { IsCookieToken = false }; + var httpContext = new DefaultHttpContext(); + httpContext.User = new ClaimsPrincipal(new ClaimsIdentity()); + Assert.False(httpContext.User.Identity.IsAuthenticated); + + var tokenProvider = new DefaultAntiforgeryTokenGenerator( + claimUidExtractor: null, + additionalDataProvider: null); + + // Act & Assert + ExceptionAssert.ThrowsArgument( + () => tokenProvider.GenerateRequestToken(httpContext, cookieToken), + "cookieToken", + "The antiforgery cookie token is invalid."); + } + + [Fact] + public void GenerateRequestToken_AnonymousUser() { // Arrange var cookieToken = new AntiforgeryToken() { IsCookieToken = true }; @@ -53,7 +74,7 @@ namespace Microsoft.AspNetCore.Antiforgery } [Fact] - public void GenerateFormToken_AuthenticatedWithoutUsernameAndNoAdditionalData_NoAdditionalData() + public void GenerateRequestToken_AuthenticatedWithoutUsernameAndNoAdditionalData_NoAdditionalData() { // Arrange var cookieToken = new AntiforgeryToken() @@ -87,7 +108,7 @@ namespace Microsoft.AspNetCore.Antiforgery } [Fact] - public void GenerateFormToken_AuthenticatedWithoutUsername_WithAdditionalData() + public void GenerateRequestToken_AuthenticatedWithoutUsername_WithAdditionalData() { // Arrange var cookieToken = new AntiforgeryToken() { IsCookieToken = true }; @@ -118,7 +139,7 @@ namespace Microsoft.AspNetCore.Antiforgery } [Fact] - public void GenerateFormToken_ClaimsBasedIdentity() + public void GenerateRequestToken_ClaimsBasedIdentity() { // Arrange var cookieToken = new AntiforgeryToken() { IsCookieToken = true }; @@ -156,7 +177,7 @@ namespace Microsoft.AspNetCore.Antiforgery } [Fact] - public void GenerateFormToken_RegularUserWithUsername() + public void GenerateRequestToken_RegularUserWithUsername() { // Arrange var cookieToken = new AntiforgeryToken() { IsCookieToken = true }; @@ -202,10 +223,10 @@ namespace Microsoft.AspNetCore.Antiforgery additionalDataProvider: null); // Act - bool retVal = tokenProvider.IsCookieTokenValid(cookieToken); + var isValid = tokenProvider.IsCookieTokenValid(cookieToken); // Assert - Assert.False(retVal); + Assert.False(isValid); } [Fact] @@ -246,7 +267,7 @@ namespace Microsoft.AspNetCore.Antiforgery [Fact] - public void ValidateTokens_CookieTokenMissing() + public void TryValidateTokenSet_CookieTokenMissing() { // Arrange var httpContext = new DefaultHttpContext(); @@ -254,98 +275,126 @@ namespace Microsoft.AspNetCore.Antiforgery var fieldtoken = new AntiforgeryToken() { IsCookieToken = false }; - var tokenProvider = new DefaultAntiforgeryTokenGenerator( - claimUidExtractor: null, - additionalDataProvider: null); - - // Act & assert - var ex = Assert.Throws( - () => tokenProvider.ValidateTokens(httpContext, null, fieldtoken)); - - var trimmed = ex.Message.Substring(0, ex.Message.IndexOf(Environment.NewLine)); - Assert.Equal(@"The required antiforgery cookie token must be provided.", trimmed); - } - - [Fact] - public void ValidateTokens_FieldTokenMissing() - { - // Arrange - var httpContext = new DefaultHttpContext(); - httpContext.User = new ClaimsPrincipal(new ClaimsIdentity()); - - var cookieToken = new AntiforgeryToken() { IsCookieToken = true }; - - var tokenProvider = new DefaultAntiforgeryTokenGenerator( - claimUidExtractor: null, - additionalDataProvider: null); - - // Act & assert - var ex = Assert.Throws( - () => tokenProvider.ValidateTokens(httpContext, cookieToken, null)); - - var trimmed = ex.Message.Substring(0, ex.Message.IndexOf(Environment.NewLine)); - Assert.Equal("The required antiforgery request token must be provided.", trimmed); - } - - [Fact] - public void ValidateTokens_FieldAndCookieTokensSwapped() - { - // Arrange - var httpContext = new DefaultHttpContext(); - httpContext.User = new ClaimsPrincipal(new ClaimsIdentity()); - - var cookieToken = new AntiforgeryToken() { IsCookieToken = true }; - var fieldtoken = new AntiforgeryToken() { IsCookieToken = false }; - - var tokenProvider = new DefaultAntiforgeryTokenGenerator( - claimUidExtractor: null, - additionalDataProvider: null); - - // Act & assert - var ex1 = - Assert.Throws( - () => tokenProvider.ValidateTokens(httpContext, fieldtoken, fieldtoken)); - Assert.Equal( - "Validation of the provided antiforgery token failed. " + - @"The cookie token and the request token were swapped.", - ex1.Message); - - var ex2 = - Assert.Throws( - () => tokenProvider.ValidateTokens(httpContext, cookieToken, cookieToken)); - Assert.Equal( - "Validation of the provided antiforgery token failed. " + - @"The cookie token and the request token were swapped.", - ex2.Message); - } - - [Fact] - public void ValidateTokens_FieldAndCookieTokensHaveDifferentSecurityKeys() - { - // Arrange - var httpContext = new DefaultHttpContext(); - httpContext.User = new ClaimsPrincipal(new ClaimsIdentity()); - - var cookieToken = new AntiforgeryToken() { IsCookieToken = true }; - var fieldtoken = new AntiforgeryToken() { IsCookieToken = false }; - var tokenProvider = new DefaultAntiforgeryTokenGenerator( claimUidExtractor: null, additionalDataProvider: null); // Act & Assert - var exception = Assert.Throws( - () => tokenProvider.ValidateTokens(httpContext, cookieToken, fieldtoken)); - Assert.Equal( - @"The antiforgery cookie token and request token do not match.", - exception.Message); + string message; + var ex = Assert.Throws( + () => tokenProvider.TryValidateTokenSet(httpContext, null, fieldtoken, out message)); + + var trimmed = ex.Message.Substring(0, ex.Message.IndexOf(Environment.NewLine)); + Assert.Equal(@"The required antiforgery cookie token must be provided.", trimmed); + } + + [Fact] + public void TryValidateTokenSet_FieldTokenMissing() + { + // Arrange + var httpContext = new DefaultHttpContext(); + httpContext.User = new ClaimsPrincipal(new ClaimsIdentity()); + + var cookieToken = new AntiforgeryToken() { IsCookieToken = true }; + + var tokenProvider = new DefaultAntiforgeryTokenGenerator( + claimUidExtractor: null, + additionalDataProvider: null); + + + // Act & Assert + string message; + var ex = Assert.Throws( + () => tokenProvider.TryValidateTokenSet(httpContext, cookieToken, null, out message)); + + var trimmed = ex.Message.Substring(0, ex.Message.IndexOf(Environment.NewLine)); + Assert.Equal("The required antiforgery request token must be provided.", trimmed); + } + + [Fact] + public void TryValidateTokenSet_FieldAndCookieTokensSwapped_FieldTokenDuplicated() + { + // Arrange + var httpContext = new DefaultHttpContext(); + httpContext.User = new ClaimsPrincipal(new ClaimsIdentity()); + + var cookieToken = new AntiforgeryToken() { IsCookieToken = true }; + var fieldtoken = new AntiforgeryToken() { IsCookieToken = false }; + + var tokenProvider = new DefaultAntiforgeryTokenGenerator( + claimUidExtractor: null, + additionalDataProvider: null); + + string expectedMessage = + "Validation of the provided antiforgery token failed. " + + "The cookie token and the request token were swapped."; + + // Act + string message; + var result = tokenProvider.TryValidateTokenSet(httpContext, fieldtoken, fieldtoken, out message); + + // Assert + Assert.False(result); + Assert.Equal(expectedMessage, message); + } + + [Fact] + public void TryValidateTokenSet_FieldAndCookieTokensSwapped_CookieDuplicated() + { + // Arrange + var httpContext = new DefaultHttpContext(); + httpContext.User = new ClaimsPrincipal(new ClaimsIdentity()); + + var cookieToken = new AntiforgeryToken() { IsCookieToken = true }; + var fieldtoken = new AntiforgeryToken() { IsCookieToken = false }; + + var tokenProvider = new DefaultAntiforgeryTokenGenerator( + claimUidExtractor: null, + additionalDataProvider: null); + + string expectedMessage = + "Validation of the provided antiforgery token failed. " + + "The cookie token and the request token were swapped."; + + // Act + string message; + var result = tokenProvider.TryValidateTokenSet(httpContext, cookieToken, cookieToken, out message); + + // Assert + Assert.False(result); + Assert.Equal(expectedMessage, message); + } + + [Fact] + public void TryValidateTokenSet_FieldAndCookieTokensHaveDifferentSecurityKeys() + { + // Arrange + var httpContext = new DefaultHttpContext(); + httpContext.User = new ClaimsPrincipal(new ClaimsIdentity()); + + var cookieToken = new AntiforgeryToken() { IsCookieToken = true }; + var fieldtoken = new AntiforgeryToken() { IsCookieToken = false }; + + var tokenProvider = new DefaultAntiforgeryTokenGenerator( + claimUidExtractor: null, + additionalDataProvider: null); + + string expectedMessage = "The antiforgery cookie token and request token do not match."; + + // Act + string message; + var result = tokenProvider.TryValidateTokenSet(httpContext, cookieToken, fieldtoken, out message); + + // Assert + Assert.False(result); + Assert.Equal(expectedMessage, message); } [Theory] [InlineData("the-user", "the-other-user")] [InlineData("http://example.com/uri-casing", "http://example.com/URI-casing")] [InlineData("https://example.com/secure-uri-casing", "https://example.com/secure-URI-casing")] - public void ValidateTokens_UsernameMismatch(string identityUsername, string embeddedUsername) + public void TryValidateTokenSet_UsernameMismatch(string identityUsername, string embeddedUsername) { // Arrange var httpContext = new DefaultHttpContext(); @@ -368,17 +417,21 @@ namespace Microsoft.AspNetCore.Antiforgery claimUidExtractor: mockClaimUidExtractor.Object, additionalDataProvider: null); - // Act & Assert - var exception = Assert.Throws( - () => tokenProvider.ValidateTokens(httpContext, cookieToken, fieldtoken)); - Assert.Equal( - @"The provided antiforgery token was meant for user """ + embeddedUsername + - @""", but the current user is """ + identityUsername + @""".", - exception.Message); + string expectedMessage = + $"The provided antiforgery token was meant for user \"{embeddedUsername}\", " + + $"but the current user is \"{identityUsername}\"."; + + // Act + string message; + var result = tokenProvider.TryValidateTokenSet(httpContext, cookieToken, fieldtoken, out message); + + // Assert + Assert.False(result); + Assert.Equal(expectedMessage, message); } [Fact] - public void ValidateTokens_ClaimUidMismatch() + public void TryValidateTokenSet_ClaimUidMismatch() { // Arrange var httpContext = new DefaultHttpContext(); @@ -402,16 +455,21 @@ namespace Microsoft.AspNetCore.Antiforgery claimUidExtractor: mockClaimUidExtractor.Object, additionalDataProvider: null); - // Act & assert - var exception = Assert.Throws( - () => tokenProvider.ValidateTokens(httpContext, cookieToken, fieldtoken)); - Assert.Equal( - @"The provided antiforgery token was meant for a different claims-based user than the current user.", - exception.Message); + string expectedMessage = + "The provided antiforgery token was meant for a different " + + "claims-based user than the current user."; + + // Act + string message; + var result = tokenProvider.TryValidateTokenSet(httpContext, cookieToken, fieldtoken, out message); + + // Assert + Assert.False(result); + Assert.Equal(expectedMessage, message); } [Fact] - public void ValidateTokens_AdditionalDataRejected() + public void TryValidateTokenSet_AdditionalDataRejected() { // Arrange var httpContext = new DefaultHttpContext(); @@ -428,21 +486,27 @@ namespace Microsoft.AspNetCore.Antiforgery }; var mockAdditionalDataProvider = new Mock(); - mockAdditionalDataProvider.Setup(o => o.ValidateAdditionalData(httpContext, "some-additional-data")) - .Returns(false); + mockAdditionalDataProvider + .Setup(o => o.ValidateAdditionalData(httpContext, "some-additional-data")) + .Returns(false); var tokenProvider = new DefaultAntiforgeryTokenGenerator( claimUidExtractor: null, additionalDataProvider: mockAdditionalDataProvider.Object); - // Act & assert - var exception = Assert.Throws( - () => tokenProvider.ValidateTokens(httpContext, cookieToken, fieldtoken)); - Assert.Equal(@"The provided antiforgery token failed a custom data check.", exception.Message); + string expectedMessage = "The provided antiforgery token failed a custom data check."; + + // Act + string message; + var result = tokenProvider.TryValidateTokenSet(httpContext, cookieToken, fieldtoken, out message); + + // Assert + Assert.False(result); + Assert.Equal(expectedMessage, message); } [Fact] - public void ValidateTokens_Success_AnonymousUser() + public void TryValidateTokenSet_Success_AnonymousUser() { // Arrange var httpContext = new DefaultHttpContext(); @@ -467,14 +531,16 @@ namespace Microsoft.AspNetCore.Antiforgery additionalDataProvider: mockAdditionalDataProvider.Object); // Act - tokenProvider.ValidateTokens(httpContext, cookieToken, fieldtoken); + string message; + var result = tokenProvider.TryValidateTokenSet(httpContext, cookieToken, fieldtoken, out message); // Assert - // Nothing to assert - if we got this far, success! + Assert.True(result); + Assert.Null(message); } [Fact] - public void ValidateTokens_Success_AuthenticatedUserWithUsername() + public void TryValidateTokenSet_Success_AuthenticatedUserWithUsername() { // Arrange var httpContext = new DefaultHttpContext(); @@ -499,14 +565,16 @@ namespace Microsoft.AspNetCore.Antiforgery additionalDataProvider: mockAdditionalDataProvider.Object); // Act - tokenProvider.ValidateTokens(httpContext, cookieToken, fieldtoken); + string message; + var result = tokenProvider.TryValidateTokenSet(httpContext, cookieToken, fieldtoken, out message); // Assert - // Nothing to assert - if we got this far, success! + Assert.True(result); + Assert.Null(message); } [Fact] - public void ValidateTokens_Success_ClaimsBasedUser() + public void TryValidateTokenSet_Success_ClaimsBasedUser() { // Arrange var httpContext = new DefaultHttpContext(); @@ -530,10 +598,12 @@ namespace Microsoft.AspNetCore.Antiforgery additionalDataProvider: null); // Act - tokenProvider.ValidateTokens(httpContext, cookieToken, fieldtoken); + string message; + var result = tokenProvider.TryValidateTokenSet(httpContext, cookieToken, fieldtoken, out message); // Assert - // Nothing to assert - if we got this far, success! + Assert.True(result); + Assert.Null(message); } private static ClaimsIdentity GetAuthenticatedIdentity(string identityUsername) diff --git a/test/Microsoft.AspNetCore.Antiforgery.Test/project.json b/test/Microsoft.AspNetCore.Antiforgery.Test/project.json index fee3adecdb..caabfc7fd0 100644 --- a/test/Microsoft.AspNetCore.Antiforgery.Test/project.json +++ b/test/Microsoft.AspNetCore.Antiforgery.Test/project.json @@ -6,6 +6,7 @@ "dependencies": { "Microsoft.AspNetCore.Antiforgery": "1.0.0-*", "Microsoft.AspNetCore.Http": "1.0.0-*", + "Microsoft.AspNetCore.Testing": "1.0.0-*", "Microsoft.Extensions.DependencyInjection": "1.0.0-*", "Microsoft.Extensions.WebEncoders": "1.0.0-*", "Microsoft.NETCore.Platforms": "1.0.1-*", From 48ee35202271490042eea7122adf63a369928698 Mon Sep 17 00:00:00 2001 From: Ryan Nowak Date: Wed, 3 Feb 2016 14:05:40 -0800 Subject: [PATCH 074/296] Add form and header name to token set --- .../AntiforgeryTokenSet.cs | 38 +++++++++++++++---- .../DefaultAntiforgery.cs | 4 +- .../DefaultAntiforgeryTokenStore.cs | 2 +- .../DefaultAntiforgeryTest.cs | 20 ++++++---- 4 files changed, 48 insertions(+), 16 deletions(-) diff --git a/src/Microsoft.AspNetCore.Antiforgery/AntiforgeryTokenSet.cs b/src/Microsoft.AspNetCore.Antiforgery/AntiforgeryTokenSet.cs index 9446cba3c6..2b99141894 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/AntiforgeryTokenSet.cs +++ b/src/Microsoft.AspNetCore.Antiforgery/AntiforgeryTokenSet.cs @@ -15,28 +15,52 @@ namespace Microsoft.AspNetCore.Antiforgery /// /// The token that is supplied in the request. /// The token that is supplied in the request cookie. - public AntiforgeryTokenSet(string requestToken, string cookieToken) + /// The name of the form field used for the request token. + /// The name of the header used for the request token. + public AntiforgeryTokenSet( + string requestToken, + string cookieToken, + string formFieldName, + string headerName) { if (string.IsNullOrEmpty(requestToken)) { throw new ArgumentException(Resources.ArgumentCannotBeNullOrEmpty, nameof(requestToken)); } + if (formFieldName == null) + { + throw new ArgumentNullException(nameof(formFieldName)); + } + RequestToken = requestToken; // Cookie Token is allowed to be null in the case when the old cookie is valid // and there is no new cookieToken generated. CookieToken = cookieToken; + + FormFieldName = formFieldName; + HeaderName = headerName; } /// - /// The token that is supplied in the request. + /// Gets the request token. /// - public string RequestToken { get; private set; } + public string RequestToken { get; } - /// The cookie token is allowed to be null. - /// This would be the case when the old cookie token is still valid. - /// In such cases a call to GetTokens would return a token set with null cookie token. - public string CookieToken { get; private set; } + /// + /// Gets the name of the form field used for the request token. + /// + public string FormFieldName { get; } + + /// + /// Gets the name of the header used for the request token. + /// + public string HeaderName { get; } + + /// + /// Gets the cookie token. + /// + public string CookieToken { get; } } } \ No newline at end of file diff --git a/src/Microsoft.AspNetCore.Antiforgery/DefaultAntiforgery.cs b/src/Microsoft.AspNetCore.Antiforgery/DefaultAntiforgery.cs index 2f602fb077..e0cbe2ada6 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/DefaultAntiforgery.cs +++ b/src/Microsoft.AspNetCore.Antiforgery/DefaultAntiforgery.cs @@ -263,7 +263,9 @@ namespace Microsoft.AspNetCore.Antiforgery { return new AntiforgeryTokenSet( tokenSet.RequestToken != null ? _tokenSerializer.Serialize(tokenSet.RequestToken) : null, - tokenSet.CookieToken != null ? _tokenSerializer.Serialize(tokenSet.CookieToken) : null); + tokenSet.CookieToken != null ? _tokenSerializer.Serialize(tokenSet.CookieToken) : null, + _options.FormFieldName, + _options.HeaderName); } private class AntiforgeryTokenSetInternal diff --git a/src/Microsoft.AspNetCore.Antiforgery/DefaultAntiforgeryTokenStore.cs b/src/Microsoft.AspNetCore.Antiforgery/DefaultAntiforgeryTokenStore.cs index 5d9328f031..72b6eee169 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/DefaultAntiforgeryTokenStore.cs +++ b/src/Microsoft.AspNetCore.Antiforgery/DefaultAntiforgeryTokenStore.cs @@ -108,7 +108,7 @@ namespace Microsoft.AspNetCore.Antiforgery } } - return new AntiforgeryTokenSet(requestToken, requestCookie); + return new AntiforgeryTokenSet(requestToken, requestCookie, _options.FormFieldName, _options.HeaderName); } public void SaveCookieToken(HttpContext httpContext, AntiforgeryToken token) diff --git a/test/Microsoft.AspNetCore.Antiforgery.Test/DefaultAntiforgeryTest.cs b/test/Microsoft.AspNetCore.Antiforgery.Test/DefaultAntiforgeryTest.cs index cba6a7dce4..dedcac76ee 100644 --- a/test/Microsoft.AspNetCore.Antiforgery.Test/DefaultAntiforgeryTest.cs +++ b/test/Microsoft.AspNetCore.Antiforgery.Test/DefaultAntiforgeryTest.cs @@ -5,7 +5,6 @@ using System; using System.IO; using System.Security.Claims; using System.Threading.Tasks; -using Microsoft.AspNetCore.Html; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.Internal; using Microsoft.AspNetCore.Testing; @@ -75,9 +74,11 @@ namespace Microsoft.AspNetCore.Antiforgery var antiforgery = GetAntiforgery(options); + var tokenSet = new AntiforgeryTokenSet("hello", "world", "form", "header"); + // Act & Assert var exception = Assert.Throws( - () => antiforgery.ValidateTokens(httpContext, new AntiforgeryTokenSet("hello", "world"))); + () => antiforgery.ValidateTokens(httpContext, tokenSet)); Assert.Equal( @"The antiforgery system has the configuration value AntiforgeryOptions.RequireSsl = true, " + "but the current request is not an SSL request.", @@ -431,11 +432,13 @@ namespace Microsoft.AspNetCore.Antiforgery context.TokenSerializer.Object, tokenStore: null); + var tokenSet = new AntiforgeryTokenSet("form-token", "cookie-token", "form", "header"); + // Act & Assert var exception = Assert.Throws( () => antiforgery.ValidateTokens( context.HttpContext, - new AntiforgeryTokenSet("form-token", "cookie-token"))); + tokenSet)); Assert.Equal("my-message", exception.Message); } @@ -464,8 +467,10 @@ namespace Microsoft.AspNetCore.Antiforgery context.TokenStore = null; var antiforgery = GetAntiforgery(context); + var tokenSet = new AntiforgeryTokenSet("form-token", "cookie-token", "form", "header"); + // Act - antiforgery.ValidateTokens(context.HttpContext, new AntiforgeryTokenSet("form-token", "cookie-token")); + antiforgery.ValidateTokens(context.HttpContext, tokenSet); // Assert context.TokenGenerator.Verify(); @@ -478,8 +483,7 @@ namespace Microsoft.AspNetCore.Antiforgery var context = CreateMockContext(new AntiforgeryOptions()); var antiforgery = GetAntiforgery(context); - var tokenSet = new AntiforgeryTokenSet("hi", cookieToken: null); - + var tokenSet = new AntiforgeryTokenSet("form-token", null, "form", "header"); // Act ExceptionAssert.ThrowsArgument( @@ -661,7 +665,9 @@ namespace Microsoft.AspNetCore.Antiforgery mockTokenStore.Setup(o => o.GetRequestTokensAsync(context)) .Returns(() => Task.FromResult(new AntiforgeryTokenSet( testTokenSet.FormTokenString, - testTokenSet.OldCookieTokenString))); + testTokenSet.OldCookieTokenString, + "form", + "header"))); if (saveNewCookie) { From 705c080d3b2f2cead94e39e6fa7af2f37ee6608c Mon Sep 17 00:00:00 2001 From: Doug Bunting Date: Wed, 3 Feb 2016 14:42:19 -0800 Subject: [PATCH 075/296] Move Antiforgery implementation details to `.Internal` - leave `IAntiforgery`, `IAntiforgeryAdditionalDataProvider` and related bits behind --- .../{ => Internal}/AntiforgeryContext.cs | 2 +- .../{ => Internal}/AntiforgeryOptionsSetup.cs | 2 +- .../{ => Internal}/AntiforgerySerializationContext.cs | 2 +- .../{ => Internal}/AntiforgeryToken.cs | 2 +- .../{ => Internal}/BinaryBlob.cs | 2 +- .../{ => Internal}/DefaultAntiforgery.cs | 2 +- .../DefaultAntiforgeryAdditionalDataProvider.cs | 2 +- .../{ => Internal}/DefaultAntiforgeryContextAccessor.cs | 2 +- .../{ => Internal}/DefaultAntiforgeryTokenGenerator.cs | 2 +- .../{ => Internal}/DefaultAntiforgeryTokenSerializer.cs | 2 +- .../{ => Internal}/DefaultAntiforgeryTokenStore.cs | 2 +- .../{ => Internal}/DefaultClaimUidExtractor.cs | 2 +- .../{ => Internal}/IAntiforgeryContextAccessor.cs | 2 +- .../{ => Internal}/IAntiforgeryTokenGenerator.cs | 2 +- .../{ => Internal}/IAntiforgeryTokenSerializer.cs | 2 +- .../{ => Internal}/IAntiforgeryTokenStore.cs | 2 +- .../{ => Internal}/IClaimUidExtractor.cs | 2 +- .../{ => Internal}/AntiforgeryOptionsSetupTest.cs | 2 +- .../{ => Internal}/AntiforgeryTokenTest.cs | 2 +- .../{ => Internal}/BinaryBlobTest.cs | 2 +- .../{ => Internal}/DefaultAntiforgeryTest.cs | 6 +++--- .../{ => Internal}/DefaultAntiforgeryTokenGeneratorTest.cs | 6 +++--- .../{ => Internal}/DefaultAntiforgeryTokenSerializerTest.cs | 3 +-- .../{ => Internal}/DefaultAntiforgeryTokenStoreTest.cs | 3 +-- .../{ => Internal}/DefaultClaimUidExtractorTest.cs | 3 +-- 25 files changed, 29 insertions(+), 32 deletions(-) rename src/Microsoft.AspNetCore.Antiforgery/{ => Internal}/AntiforgeryContext.cs (86%) rename src/Microsoft.AspNetCore.Antiforgery/{ => Internal}/AntiforgeryOptionsSetup.cs (96%) rename src/Microsoft.AspNetCore.Antiforgery/{ => Internal}/AntiforgerySerializationContext.cs (98%) rename src/Microsoft.AspNetCore.Antiforgery/{ => Internal}/AntiforgeryToken.cs (96%) rename src/Microsoft.AspNetCore.Antiforgery/{ => Internal}/BinaryBlob.cs (98%) rename src/Microsoft.AspNetCore.Antiforgery/{ => Internal}/DefaultAntiforgery.cs (99%) rename src/Microsoft.AspNetCore.Antiforgery/{ => Internal}/DefaultAntiforgeryAdditionalDataProvider.cs (94%) rename src/Microsoft.AspNetCore.Antiforgery/{ => Internal}/DefaultAntiforgeryContextAccessor.cs (85%) rename src/Microsoft.AspNetCore.Antiforgery/{ => Internal}/DefaultAntiforgeryTokenGenerator.cs (99%) rename src/Microsoft.AspNetCore.Antiforgery/{ => Internal}/DefaultAntiforgeryTokenSerializer.cs (99%) rename src/Microsoft.AspNetCore.Antiforgery/{ => Internal}/DefaultAntiforgeryTokenStore.cs (99%) rename src/Microsoft.AspNetCore.Antiforgery/{ => Internal}/DefaultClaimUidExtractor.cs (98%) rename src/Microsoft.AspNetCore.Antiforgery/{ => Internal}/IAntiforgeryContextAccessor.cs (84%) rename src/Microsoft.AspNetCore.Antiforgery/{ => Internal}/IAntiforgeryTokenGenerator.cs (97%) rename src/Microsoft.AspNetCore.Antiforgery/{ => Internal}/IAntiforgeryTokenSerializer.cs (88%) rename src/Microsoft.AspNetCore.Antiforgery/{ => Internal}/IAntiforgeryTokenStore.cs (94%) rename src/Microsoft.AspNetCore.Antiforgery/{ => Internal}/IClaimUidExtractor.cs (92%) rename test/Microsoft.AspNetCore.Antiforgery.Test/{ => Internal}/AntiforgeryOptionsSetupTest.cs (97%) rename test/Microsoft.AspNetCore.Antiforgery.Test/{ => Internal}/AntiforgeryTokenTest.cs (98%) rename test/Microsoft.AspNetCore.Antiforgery.Test/{ => Internal}/BinaryBlobTest.cs (98%) rename test/Microsoft.AspNetCore.Antiforgery.Test/{ => Internal}/DefaultAntiforgeryTest.cs (99%) rename test/Microsoft.AspNetCore.Antiforgery.Test/{ => Internal}/DefaultAntiforgeryTokenGeneratorTest.cs (99%) rename test/Microsoft.AspNetCore.Antiforgery.Test/{ => Internal}/DefaultAntiforgeryTokenSerializerTest.cs (98%) rename test/Microsoft.AspNetCore.Antiforgery.Test/{ => Internal}/DefaultAntiforgeryTokenStoreTest.cs (99%) rename test/Microsoft.AspNetCore.Antiforgery.Test/{ => Internal}/DefaultClaimUidExtractorTest.cs (97%) diff --git a/src/Microsoft.AspNetCore.Antiforgery/AntiforgeryContext.cs b/src/Microsoft.AspNetCore.Antiforgery/Internal/AntiforgeryContext.cs similarity index 86% rename from src/Microsoft.AspNetCore.Antiforgery/AntiforgeryContext.cs rename to src/Microsoft.AspNetCore.Antiforgery/Internal/AntiforgeryContext.cs index 3615fc25b1..f1abeefe92 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/AntiforgeryContext.cs +++ b/src/Microsoft.AspNetCore.Antiforgery/Internal/AntiforgeryContext.cs @@ -1,7 +1,7 @@ // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. -namespace Microsoft.AspNetCore.Antiforgery +namespace Microsoft.AspNetCore.Antiforgery.Internal { /// /// Used as a per request state. diff --git a/src/Microsoft.AspNetCore.Antiforgery/AntiforgeryOptionsSetup.cs b/src/Microsoft.AspNetCore.Antiforgery/Internal/AntiforgeryOptionsSetup.cs similarity index 96% rename from src/Microsoft.AspNetCore.Antiforgery/AntiforgeryOptionsSetup.cs rename to src/Microsoft.AspNetCore.Antiforgery/Internal/AntiforgeryOptionsSetup.cs index c397845599..f1f7dc612a 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/AntiforgeryOptionsSetup.cs +++ b/src/Microsoft.AspNetCore.Antiforgery/Internal/AntiforgeryOptionsSetup.cs @@ -8,7 +8,7 @@ using Microsoft.AspNetCore.DataProtection; using Microsoft.AspNetCore.WebUtilities; using Microsoft.Extensions.Options; -namespace Microsoft.AspNetCore.Antiforgery +namespace Microsoft.AspNetCore.Antiforgery.Internal { public class AntiforgeryOptionsSetup : ConfigureOptions { diff --git a/src/Microsoft.AspNetCore.Antiforgery/AntiforgerySerializationContext.cs b/src/Microsoft.AspNetCore.Antiforgery/Internal/AntiforgerySerializationContext.cs similarity index 98% rename from src/Microsoft.AspNetCore.Antiforgery/AntiforgerySerializationContext.cs rename to src/Microsoft.AspNetCore.Antiforgery/Internal/AntiforgerySerializationContext.cs index 969df3428e..27f7fa3725 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/AntiforgerySerializationContext.cs +++ b/src/Microsoft.AspNetCore.Antiforgery/Internal/AntiforgerySerializationContext.cs @@ -5,7 +5,7 @@ using System.IO; using System.Security.Cryptography; using System.Text; -namespace Microsoft.AspNetCore.Antiforgery +namespace Microsoft.AspNetCore.Antiforgery.Internal { public class AntiforgerySerializationContext { diff --git a/src/Microsoft.AspNetCore.Antiforgery/AntiforgeryToken.cs b/src/Microsoft.AspNetCore.Antiforgery/Internal/AntiforgeryToken.cs similarity index 96% rename from src/Microsoft.AspNetCore.Antiforgery/AntiforgeryToken.cs rename to src/Microsoft.AspNetCore.Antiforgery/Internal/AntiforgeryToken.cs index bf9ba5e9bf..78294f730c 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/AntiforgeryToken.cs +++ b/src/Microsoft.AspNetCore.Antiforgery/Internal/AntiforgeryToken.cs @@ -1,7 +1,7 @@ // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. -namespace Microsoft.AspNetCore.Antiforgery +namespace Microsoft.AspNetCore.Antiforgery.Internal { public sealed class AntiforgeryToken { diff --git a/src/Microsoft.AspNetCore.Antiforgery/BinaryBlob.cs b/src/Microsoft.AspNetCore.Antiforgery/Internal/BinaryBlob.cs similarity index 98% rename from src/Microsoft.AspNetCore.Antiforgery/BinaryBlob.cs rename to src/Microsoft.AspNetCore.Antiforgery/Internal/BinaryBlob.cs index 140317ef27..88c34571c0 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/BinaryBlob.cs +++ b/src/Microsoft.AspNetCore.Antiforgery/Internal/BinaryBlob.cs @@ -8,7 +8,7 @@ using System.Runtime.CompilerServices; using System.Security.Cryptography; using System.Text; -namespace Microsoft.AspNetCore.Antiforgery +namespace Microsoft.AspNetCore.Antiforgery.Internal { // Represents a binary blob (token) that contains random data. // Useful for binary data inside a serialized stream. diff --git a/src/Microsoft.AspNetCore.Antiforgery/DefaultAntiforgery.cs b/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgery.cs similarity index 99% rename from src/Microsoft.AspNetCore.Antiforgery/DefaultAntiforgery.cs rename to src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgery.cs index e0cbe2ada6..6d52cfa4da 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/DefaultAntiforgery.cs +++ b/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgery.cs @@ -10,7 +10,7 @@ using Microsoft.AspNetCore.Html; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Options; -namespace Microsoft.AspNetCore.Antiforgery +namespace Microsoft.AspNetCore.Antiforgery.Internal { /// /// Provides access to the antiforgery system, which provides protection against diff --git a/src/Microsoft.AspNetCore.Antiforgery/DefaultAntiforgeryAdditionalDataProvider.cs b/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgeryAdditionalDataProvider.cs similarity index 94% rename from src/Microsoft.AspNetCore.Antiforgery/DefaultAntiforgeryAdditionalDataProvider.cs rename to src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgeryAdditionalDataProvider.cs index e0797d2696..ad28453495 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/DefaultAntiforgeryAdditionalDataProvider.cs +++ b/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgeryAdditionalDataProvider.cs @@ -3,7 +3,7 @@ using Microsoft.AspNetCore.Http; -namespace Microsoft.AspNetCore.Antiforgery +namespace Microsoft.AspNetCore.Antiforgery.Internal { /// /// A default implementation. diff --git a/src/Microsoft.AspNetCore.Antiforgery/DefaultAntiforgeryContextAccessor.cs b/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgeryContextAccessor.cs similarity index 85% rename from src/Microsoft.AspNetCore.Antiforgery/DefaultAntiforgeryContextAccessor.cs rename to src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgeryContextAccessor.cs index 7dd27634e6..ab2df64fa1 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/DefaultAntiforgeryContextAccessor.cs +++ b/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgeryContextAccessor.cs @@ -1,7 +1,7 @@ // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. -namespace Microsoft.AspNetCore.Antiforgery +namespace Microsoft.AspNetCore.Antiforgery.Internal { public class DefaultAntiforgeryContextAccessor : IAntiforgeryContextAccessor { diff --git a/src/Microsoft.AspNetCore.Antiforgery/DefaultAntiforgeryTokenGenerator.cs b/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgeryTokenGenerator.cs similarity index 99% rename from src/Microsoft.AspNetCore.Antiforgery/DefaultAntiforgeryTokenGenerator.cs rename to src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgeryTokenGenerator.cs index 36c01beff7..390a39cab8 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/DefaultAntiforgeryTokenGenerator.cs +++ b/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgeryTokenGenerator.cs @@ -6,7 +6,7 @@ using System.Security.Claims; using System.Security.Principal; using Microsoft.AspNetCore.Http; -namespace Microsoft.AspNetCore.Antiforgery +namespace Microsoft.AspNetCore.Antiforgery.Internal { public class DefaultAntiforgeryTokenGenerator : IAntiforgeryTokenGenerator { diff --git a/src/Microsoft.AspNetCore.Antiforgery/DefaultAntiforgeryTokenSerializer.cs b/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgeryTokenSerializer.cs similarity index 99% rename from src/Microsoft.AspNetCore.Antiforgery/DefaultAntiforgeryTokenSerializer.cs rename to src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgeryTokenSerializer.cs index c606c1cc9d..216f79ae09 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/DefaultAntiforgeryTokenSerializer.cs +++ b/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgeryTokenSerializer.cs @@ -7,7 +7,7 @@ using Microsoft.AspNetCore.DataProtection; using Microsoft.AspNetCore.WebUtilities; using Microsoft.Extensions.ObjectPool; -namespace Microsoft.AspNetCore.Antiforgery +namespace Microsoft.AspNetCore.Antiforgery.Internal { public class DefaultAntiforgeryTokenSerializer : IAntiforgeryTokenSerializer { diff --git a/src/Microsoft.AspNetCore.Antiforgery/DefaultAntiforgeryTokenStore.cs b/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgeryTokenStore.cs similarity index 99% rename from src/Microsoft.AspNetCore.Antiforgery/DefaultAntiforgeryTokenStore.cs rename to src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgeryTokenStore.cs index 72b6eee169..52d852a27c 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/DefaultAntiforgeryTokenStore.cs +++ b/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgeryTokenStore.cs @@ -9,7 +9,7 @@ using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Options; using Microsoft.Extensions.Primitives; -namespace Microsoft.AspNetCore.Antiforgery +namespace Microsoft.AspNetCore.Antiforgery.Internal { public class DefaultAntiforgeryTokenStore : IAntiforgeryTokenStore { diff --git a/src/Microsoft.AspNetCore.Antiforgery/DefaultClaimUidExtractor.cs b/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultClaimUidExtractor.cs similarity index 98% rename from src/Microsoft.AspNetCore.Antiforgery/DefaultClaimUidExtractor.cs rename to src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultClaimUidExtractor.cs index 66ddf13743..7f089073bc 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/DefaultClaimUidExtractor.cs +++ b/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultClaimUidExtractor.cs @@ -7,7 +7,7 @@ using System.Linq; using System.Security.Claims; using Microsoft.Extensions.ObjectPool; -namespace Microsoft.AspNetCore.Antiforgery +namespace Microsoft.AspNetCore.Antiforgery.Internal { /// /// Default implementation of . diff --git a/src/Microsoft.AspNetCore.Antiforgery/IAntiforgeryContextAccessor.cs b/src/Microsoft.AspNetCore.Antiforgery/Internal/IAntiforgeryContextAccessor.cs similarity index 84% rename from src/Microsoft.AspNetCore.Antiforgery/IAntiforgeryContextAccessor.cs rename to src/Microsoft.AspNetCore.Antiforgery/Internal/IAntiforgeryContextAccessor.cs index 7b0146dbd9..238f2a082e 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/IAntiforgeryContextAccessor.cs +++ b/src/Microsoft.AspNetCore.Antiforgery/Internal/IAntiforgeryContextAccessor.cs @@ -1,7 +1,7 @@ // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. -namespace Microsoft.AspNetCore.Antiforgery +namespace Microsoft.AspNetCore.Antiforgery.Internal { public interface IAntiforgeryContextAccessor { diff --git a/src/Microsoft.AspNetCore.Antiforgery/IAntiforgeryTokenGenerator.cs b/src/Microsoft.AspNetCore.Antiforgery/Internal/IAntiforgeryTokenGenerator.cs similarity index 97% rename from src/Microsoft.AspNetCore.Antiforgery/IAntiforgeryTokenGenerator.cs rename to src/Microsoft.AspNetCore.Antiforgery/Internal/IAntiforgeryTokenGenerator.cs index e615d8c933..c0dff86047 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/IAntiforgeryTokenGenerator.cs +++ b/src/Microsoft.AspNetCore.Antiforgery/Internal/IAntiforgeryTokenGenerator.cs @@ -3,7 +3,7 @@ using Microsoft.AspNetCore.Http; -namespace Microsoft.AspNetCore.Antiforgery +namespace Microsoft.AspNetCore.Antiforgery.Internal { /// /// Generates and validates antiforgery tokens. diff --git a/src/Microsoft.AspNetCore.Antiforgery/IAntiforgeryTokenSerializer.cs b/src/Microsoft.AspNetCore.Antiforgery/Internal/IAntiforgeryTokenSerializer.cs similarity index 88% rename from src/Microsoft.AspNetCore.Antiforgery/IAntiforgeryTokenSerializer.cs rename to src/Microsoft.AspNetCore.Antiforgery/Internal/IAntiforgeryTokenSerializer.cs index badc897309..134516e8c9 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/IAntiforgeryTokenSerializer.cs +++ b/src/Microsoft.AspNetCore.Antiforgery/Internal/IAntiforgeryTokenSerializer.cs @@ -1,7 +1,7 @@ // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. -namespace Microsoft.AspNetCore.Antiforgery +namespace Microsoft.AspNetCore.Antiforgery.Internal { // Abstracts out the serialization process for an antiforgery token public interface IAntiforgeryTokenSerializer diff --git a/src/Microsoft.AspNetCore.Antiforgery/IAntiforgeryTokenStore.cs b/src/Microsoft.AspNetCore.Antiforgery/Internal/IAntiforgeryTokenStore.cs similarity index 94% rename from src/Microsoft.AspNetCore.Antiforgery/IAntiforgeryTokenStore.cs rename to src/Microsoft.AspNetCore.Antiforgery/Internal/IAntiforgeryTokenStore.cs index 9d14ac79b3..bff9360ff9 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/IAntiforgeryTokenStore.cs +++ b/src/Microsoft.AspNetCore.Antiforgery/Internal/IAntiforgeryTokenStore.cs @@ -4,7 +4,7 @@ using System.Threading.Tasks; using Microsoft.AspNetCore.Http; -namespace Microsoft.AspNetCore.Antiforgery +namespace Microsoft.AspNetCore.Antiforgery.Internal { // Provides an abstraction around how tokens are persisted and retrieved for a request public interface IAntiforgeryTokenStore diff --git a/src/Microsoft.AspNetCore.Antiforgery/IClaimUidExtractor.cs b/src/Microsoft.AspNetCore.Antiforgery/Internal/IClaimUidExtractor.cs similarity index 92% rename from src/Microsoft.AspNetCore.Antiforgery/IClaimUidExtractor.cs rename to src/Microsoft.AspNetCore.Antiforgery/Internal/IClaimUidExtractor.cs index b78cbc863a..d4a888dec5 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/IClaimUidExtractor.cs +++ b/src/Microsoft.AspNetCore.Antiforgery/Internal/IClaimUidExtractor.cs @@ -3,7 +3,7 @@ using System.Security.Claims; -namespace Microsoft.AspNetCore.Antiforgery +namespace Microsoft.AspNetCore.Antiforgery.Internal { /// /// This interface can extract unique identifers for a claims-based identity. diff --git a/test/Microsoft.AspNetCore.Antiforgery.Test/AntiforgeryOptionsSetupTest.cs b/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/AntiforgeryOptionsSetupTest.cs similarity index 97% rename from test/Microsoft.AspNetCore.Antiforgery.Test/AntiforgeryOptionsSetupTest.cs rename to test/Microsoft.AspNetCore.Antiforgery.Test/Internal/AntiforgeryOptionsSetupTest.cs index 7822afb4d3..a981339793 100644 --- a/test/Microsoft.AspNetCore.Antiforgery.Test/AntiforgeryOptionsSetupTest.cs +++ b/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/AntiforgeryOptionsSetupTest.cs @@ -5,7 +5,7 @@ using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Options; using Xunit; -namespace Microsoft.AspNetCore.Antiforgery +namespace Microsoft.AspNetCore.Antiforgery.Internal { public class AntiforgeryOptionsSetupTest { diff --git a/test/Microsoft.AspNetCore.Antiforgery.Test/AntiforgeryTokenTest.cs b/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/AntiforgeryTokenTest.cs similarity index 98% rename from test/Microsoft.AspNetCore.Antiforgery.Test/AntiforgeryTokenTest.cs rename to test/Microsoft.AspNetCore.Antiforgery.Test/Internal/AntiforgeryTokenTest.cs index 1980043b8b..9cafd306b0 100644 --- a/test/Microsoft.AspNetCore.Antiforgery.Test/AntiforgeryTokenTest.cs +++ b/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/AntiforgeryTokenTest.cs @@ -3,7 +3,7 @@ using Xunit; -namespace Microsoft.AspNetCore.Antiforgery +namespace Microsoft.AspNetCore.Antiforgery.Internal { public class AntiforgeryTokenTest { diff --git a/test/Microsoft.AspNetCore.Antiforgery.Test/BinaryBlobTest.cs b/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/BinaryBlobTest.cs similarity index 98% rename from test/Microsoft.AspNetCore.Antiforgery.Test/BinaryBlobTest.cs rename to test/Microsoft.AspNetCore.Antiforgery.Test/Internal/BinaryBlobTest.cs index c49a055724..2ab5b12fc1 100644 --- a/test/Microsoft.AspNetCore.Antiforgery.Test/BinaryBlobTest.cs +++ b/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/BinaryBlobTest.cs @@ -4,7 +4,7 @@ using System; using Xunit; -namespace Microsoft.AspNetCore.Antiforgery +namespace Microsoft.AspNetCore.Antiforgery.Internal { public class BinaryBlobTest { diff --git a/test/Microsoft.AspNetCore.Antiforgery.Test/DefaultAntiforgeryTest.cs b/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTest.cs similarity index 99% rename from test/Microsoft.AspNetCore.Antiforgery.Test/DefaultAntiforgeryTest.cs rename to test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTest.cs index dedcac76ee..19f14fc6af 100644 --- a/test/Microsoft.AspNetCore.Antiforgery.Test/DefaultAntiforgeryTest.cs +++ b/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTest.cs @@ -13,7 +13,7 @@ using Microsoft.Extensions.WebEncoders.Testing; using Moq; using Xunit; -namespace Microsoft.AspNetCore.Antiforgery +namespace Microsoft.AspNetCore.Antiforgery.Internal { public class DefaultAntiforgeryTest { @@ -186,7 +186,7 @@ namespace Microsoft.AspNetCore.Antiforgery var antiforgery = GetAntiforgery(context); var encoder = new HtmlTestEncoder(); - // Setup so that the null cookie token returned is treated as invalid. + // Setup so that the null cookie token returned is treated as invalid. context.TokenGenerator .Setup(o => o.IsCookieTokenValid(null)) .Returns(false); @@ -226,7 +226,7 @@ namespace Microsoft.AspNetCore.Antiforgery .Setup(o => o.GetCookieToken(context.HttpContext)) .Throws(new Exception("should be swallowed")); - // Setup so that the null cookie token returned is treated as invalid. + // Setup so that the null cookie token returned is treated as invalid. context.TokenGenerator .Setup(o => o.IsCookieTokenValid(null)) .Returns(false); diff --git a/test/Microsoft.AspNetCore.Antiforgery.Test/DefaultAntiforgeryTokenGeneratorTest.cs b/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTokenGeneratorTest.cs similarity index 99% rename from test/Microsoft.AspNetCore.Antiforgery.Test/DefaultAntiforgeryTokenGeneratorTest.cs rename to test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTokenGeneratorTest.cs index f277504d0b..0e4a2a3d02 100644 --- a/test/Microsoft.AspNetCore.Antiforgery.Test/DefaultAntiforgeryTokenGeneratorTest.cs +++ b/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTokenGeneratorTest.cs @@ -9,7 +9,7 @@ using Microsoft.AspNetCore.Testing; using Moq; using Xunit; -namespace Microsoft.AspNetCore.Antiforgery +namespace Microsoft.AspNetCore.Antiforgery.Internal { public class DefaultAntiforgeryTokenGeneratorProviderTest { @@ -190,7 +190,7 @@ namespace Microsoft.AspNetCore.Antiforgery .Returns("my-username"); httpContext.User = new ClaimsPrincipal(mockIdentity.Object); - + var claimUidExtractor = new Mock().Object; var tokenProvider = new DefaultAntiforgeryTokenGenerator( @@ -325,7 +325,7 @@ namespace Microsoft.AspNetCore.Antiforgery claimUidExtractor: null, additionalDataProvider: null); - string expectedMessage = + string expectedMessage = "Validation of the provided antiforgery token failed. " + "The cookie token and the request token were swapped."; diff --git a/test/Microsoft.AspNetCore.Antiforgery.Test/DefaultAntiforgeryTokenSerializerTest.cs b/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTokenSerializerTest.cs similarity index 98% rename from test/Microsoft.AspNetCore.Antiforgery.Test/DefaultAntiforgeryTokenSerializerTest.cs rename to test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTokenSerializerTest.cs index 97193e59e6..80280de4f3 100644 --- a/test/Microsoft.AspNetCore.Antiforgery.Test/DefaultAntiforgeryTokenSerializerTest.cs +++ b/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTokenSerializerTest.cs @@ -4,13 +4,12 @@ using System; using System.Collections.Generic; using System.Linq; -using Microsoft.AspNetCore.Antiforgery.Internal; using Microsoft.AspNetCore.DataProtection; using Microsoft.Extensions.ObjectPool; using Moq; using Xunit; -namespace Microsoft.AspNetCore.Antiforgery +namespace Microsoft.AspNetCore.Antiforgery.Internal { public class DefaultAntiforgeryTokenSerializerTest { diff --git a/test/Microsoft.AspNetCore.Antiforgery.Test/DefaultAntiforgeryTokenStoreTest.cs b/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTokenStoreTest.cs similarity index 99% rename from test/Microsoft.AspNetCore.Antiforgery.Test/DefaultAntiforgeryTokenStoreTest.cs rename to test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTokenStoreTest.cs index e1c566c77d..599e851871 100644 --- a/test/Microsoft.AspNetCore.Antiforgery.Test/DefaultAntiforgeryTokenStoreTest.cs +++ b/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTokenStoreTest.cs @@ -4,7 +4,6 @@ using System; using System.Collections.Generic; using System.Threading.Tasks; -using Microsoft.AspNetCore.Antiforgery.Internal; using Microsoft.AspNetCore.DataProtection; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.Internal; @@ -14,7 +13,7 @@ using Microsoft.Extensions.Primitives; using Moq; using Xunit; -namespace Microsoft.AspNetCore.Antiforgery +namespace Microsoft.AspNetCore.Antiforgery.Internal { public class DefaultAntiforgeryTokenStoreTest { diff --git a/test/Microsoft.AspNetCore.Antiforgery.Test/DefaultClaimUidExtractorTest.cs b/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultClaimUidExtractorTest.cs similarity index 97% rename from test/Microsoft.AspNetCore.Antiforgery.Test/DefaultClaimUidExtractorTest.cs rename to test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultClaimUidExtractorTest.cs index ebb28adbf6..2968358be2 100644 --- a/test/Microsoft.AspNetCore.Antiforgery.Test/DefaultClaimUidExtractorTest.cs +++ b/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultClaimUidExtractorTest.cs @@ -4,12 +4,11 @@ using System; using System.Linq; using System.Security.Claims; -using Microsoft.AspNetCore.Antiforgery.Internal; using Microsoft.Extensions.ObjectPool; using Moq; using Xunit; -namespace Microsoft.AspNetCore.Antiforgery +namespace Microsoft.AspNetCore.Antiforgery.Internal { public class DefaultClaimUidExtractorTest { From b1df299ec396f4e0164cb8ca61e15fc5730d5f33 Mon Sep 17 00:00:00 2001 From: Hisham Bin Ateya Date: Thu, 4 Feb 2016 13:37:04 +0300 Subject: [PATCH 076/296] Add 'UseServer' --- samples/AntiforgerySample/Startup.cs | 1 + samples/AntiforgerySample/hosting.json | 3 --- 2 files changed, 1 insertion(+), 3 deletions(-) delete mode 100644 samples/AntiforgerySample/hosting.json diff --git a/samples/AntiforgerySample/Startup.cs b/samples/AntiforgerySample/Startup.cs index 05c2026906..c8f6263b7b 100644 --- a/samples/AntiforgerySample/Startup.cs +++ b/samples/AntiforgerySample/Startup.cs @@ -70,6 +70,7 @@ namespace AntiforgerySample { var host = new WebHostBuilder() .UseDefaultConfiguration(args) + .UseServer("Microsoft.AspNetCore.Server.Kestrel") .UseIISPlatformHandlerUrl() .UseStartup() .Build(); diff --git a/samples/AntiforgerySample/hosting.json b/samples/AntiforgerySample/hosting.json deleted file mode 100644 index 6a93dbafa8..0000000000 --- a/samples/AntiforgerySample/hosting.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "server": "Microsoft.AspNetCore.Server.Kestrel" -} From c91f0ee667dfca00fdf66d76ef2dce0345a62fbf Mon Sep 17 00:00:00 2001 From: Doug Bunting Date: Thu, 4 Feb 2016 10:11:05 -0800 Subject: [PATCH 077/296] Clean up some tests - avoid mocking `HttpContext` - change `DefaultAntiforgeryTest` to mock token generators consistently --- .../Internal/DefaultAntiforgeryTest.cs | 78 ++----- .../DefaultAntiforgeryTokenStoreTest.cs | 209 +++++------------- 2 files changed, 79 insertions(+), 208 deletions(-) diff --git a/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTest.cs b/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTest.cs index 19f14fc6af..0e8dfeb8dd 100644 --- a/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTest.cs +++ b/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTest.cs @@ -22,7 +22,6 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal { // Arrange var httpContext = new DefaultHttpContext(); - var options = new AntiforgeryOptions() { RequireSsl = true @@ -32,7 +31,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal // Act & Assert var exception = await Assert.ThrowsAsync( - async () => await antiforgery.ValidateRequestAsync(httpContext)); + () => antiforgery.ValidateRequestAsync(httpContext)); Assert.Equal( @"The antiforgery system has the configuration value AntiforgeryOptions.RequireSsl = true, " + "but the current request is not an SSL request.", @@ -44,7 +43,6 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal { // Arrange var httpContext = new DefaultHttpContext(); - var options = new AntiforgeryOptions() { RequireSsl = true @@ -54,7 +52,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal // Act & Assert var exception = await Assert.ThrowsAsync( - async () => await antiforgery.IsRequestValidAsync(httpContext)); + () => antiforgery.IsRequestValidAsync(httpContext)); Assert.Equal( @"The antiforgery system has the configuration value AntiforgeryOptions.RequireSsl = true, " + "but the current request is not an SSL request.", @@ -66,14 +64,12 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal { // Arrange var httpContext = new DefaultHttpContext(); - var options = new AntiforgeryOptions() { RequireSsl = true }; var antiforgery = GetAntiforgery(options); - var tokenSet = new AntiforgeryTokenSet("hello", "world", "form", "header"); // Act & Assert @@ -90,7 +86,6 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal { // Arrange var httpContext = new DefaultHttpContext(); - var options = new AntiforgeryOptions() { RequireSsl = true @@ -111,7 +106,6 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal { // Arrange var httpContext = new DefaultHttpContext(); - var options = new AntiforgeryOptions() { RequireSsl = true @@ -133,7 +127,6 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal { // Arrange var httpContext = new DefaultHttpContext(); - var options = new AntiforgeryOptions() { RequireSsl = true @@ -155,7 +148,6 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal { // Arrange var httpContext = new DefaultHttpContext(); - var options = new AntiforgeryOptions() { RequireSsl = true @@ -420,15 +412,19 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal .Setup(o => o.Deserialize("form-token")) .Returns(context.TestTokenSet.RequestToken); - // You can't really do Moq with out-parameters :( - var tokenGenerator = new TestTokenGenerator() - { - Message = "my-message", - }; + var message = "my-message"; + context.TokenGenerator + .Setup(o => o.TryValidateTokenSet( + context.HttpContext, + context.TestTokenSet.OldCookieToken, + context.TestTokenSet.RequestToken, + out message)) + .Returns(false) + .Verifiable(); var antiforgery = new DefaultAntiforgery( new TestOptionsManager(), - tokenGenerator, + context.TokenGenerator.Object, context.TokenSerializer.Object, tokenStore: null); @@ -440,6 +436,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal context.HttpContext, tokenSet)); Assert.Equal("my-message", exception.Message); + context.TokenGenerator.Verify(); } [Fact] @@ -447,7 +444,6 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal { // Arrange var context = CreateMockContext(new AntiforgeryOptions()); - context.TokenSerializer .Setup(o => o.Deserialize("cookie-token")) .Returns(context.TestTokenSet.OldCookieToken); @@ -482,7 +478,6 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal // Arrange var context = CreateMockContext(new AntiforgeryOptions()); var antiforgery = GetAntiforgery(context); - var tokenSet = new AntiforgeryTokenSet("form-token", null, "form", "header"); // Act @@ -548,15 +543,19 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal // Arrange var context = CreateMockContext(new AntiforgeryOptions()); - // You can't really do Moq with out-parameters :( - var tokenGenerator = new TestTokenGenerator() - { - Message = "my-message", - }; + var message = "my-message"; + context.TokenGenerator + .Setup(o => o.TryValidateTokenSet( + context.HttpContext, + context.TestTokenSet.OldCookieToken, + context.TestTokenSet.RequestToken, + out message)) + .Returns(false) + .Verifiable(); var antiforgery = new DefaultAntiforgery( new TestOptionsManager(), - tokenGenerator, + context.TokenGenerator.Object, context.TokenSerializer.Object, context.TokenStore.Object); @@ -564,6 +563,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal var exception = await Assert.ThrowsAsync( async () => await antiforgery.ValidateRequestAsync(context.HttpContext)); Assert.Equal("my-message", exception.Message); + context.TokenGenerator.Verify(); } [Fact] @@ -788,35 +788,5 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal { public AntiforgeryOptions Value { get; set; } = new AntiforgeryOptions(); } - - private class TestTokenGenerator : IAntiforgeryTokenGenerator - { - public string Message { get; set; } - - public AntiforgeryToken GenerateCookieToken() - { - throw new NotImplementedException(); - } - - public AntiforgeryToken GenerateRequestToken(HttpContext httpContext, AntiforgeryToken cookieToken) - { - throw new NotImplementedException(); - } - - public bool IsCookieTokenValid(AntiforgeryToken cookieToken) - { - throw new NotImplementedException(); - } - - public bool TryValidateTokenSet( - HttpContext httpContext, - AntiforgeryToken cookieToken, - AntiforgeryToken requestToken, - out string message) - { - message = Message; - return false; - } - } } } \ No newline at end of file diff --git a/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTokenStoreTest.cs b/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTokenStoreTest.cs index 599e851871..13f3ff7082 100644 --- a/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTokenStoreTest.cs +++ b/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTokenStoreTest.cs @@ -25,17 +25,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal public void GetCookieToken_CookieDoesNotExist_ReturnsNull() { // Arrange - var requestCookies = new Mock(); - requestCookies - .Setup(o => o[It.IsAny()]) - .Returns(string.Empty); - var mockHttpContext = new Mock(); - mockHttpContext - .Setup(o => o.Request.Cookies) - .Returns(requestCookies.Object); - var contextAccessor = new DefaultAntiforgeryContextAccessor(); - mockHttpContext.SetupGet(o => o.RequestServices) - .Returns(GetServiceProvider(contextAccessor)); + var httpContext = GetHttpContext(new RequestCookieCollection()); var options = new AntiforgeryOptions() { CookieName = _cookieName @@ -46,7 +36,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal tokenSerializer: Mock.Of()); // Act - var token = tokenStore.GetCookieToken(mockHttpContext.Object); + var token = tokenStore.GetCookieToken(httpContext); // Assert Assert.Null(token); @@ -56,22 +46,14 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal public void GetCookieToken_CookieIsMissingInRequest_LooksUpCookieInAntiforgeryContext() { // Arrange - var requestCookies = new Mock(); - requestCookies - .Setup(o => o[It.IsAny()]) - .Returns(string.Empty); - var mockHttpContext = new Mock(); - mockHttpContext - .Setup(o => o.Request.Cookies) - .Returns(requestCookies.Object); var contextAccessor = new DefaultAntiforgeryContextAccessor(); - mockHttpContext.SetupGet(o => o.RequestServices) - .Returns(GetServiceProvider(contextAccessor)); + var httpContext = GetHttpContext(_cookieName, string.Empty, contextAccessor); // add a cookie explicitly. var cookie = new AntiforgeryToken(); contextAccessor.Value = new AntiforgeryContext() { CookieToken = cookie }; - var options = new AntiforgeryOptions() + + var options = new AntiforgeryOptions { CookieName = _cookieName }; @@ -81,7 +63,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal tokenSerializer: Mock.Of()); // Act - var token = tokenStore.GetCookieToken(mockHttpContext.Object); + var token = tokenStore.GetCookieToken(httpContext); // Assert Assert.Equal(cookie, token); @@ -91,8 +73,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal public void GetCookieToken_CookieIsEmpty_ReturnsNull() { // Arrange - var mockHttpContext = GetMockHttpContext(_cookieName, string.Empty); - + var httpContext = GetHttpContext(_cookieName, string.Empty); var options = new AntiforgeryOptions() { CookieName = _cookieName @@ -103,7 +84,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal tokenSerializer: Mock.Of()); // Act - var token = tokenStore.GetCookieToken(mockHttpContext); + var token = tokenStore.GetCookieToken(httpContext); // Assert Assert.Null(token); @@ -113,7 +94,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal public void GetCookieToken_CookieIsInvalid_PropagatesException() { // Arrange - var mockHttpContext = GetMockHttpContext(_cookieName, "invalid-value"); + var httpContext = GetHttpContext(_cookieName, "invalid-value"); var expectedException = new AntiforgeryValidationException("some exception"); var mockSerializer = new Mock(); @@ -131,7 +112,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal tokenSerializer: mockSerializer.Object); // Act & assert - var ex = Assert.Throws(() => tokenStore.GetCookieToken(mockHttpContext)); + var ex = Assert.Throws(() => tokenStore.GetCookieToken(httpContext)); Assert.Same(expectedException, ex); } @@ -140,7 +121,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal { // Arrange var expectedToken = new AntiforgeryToken(); - var mockHttpContext = GetMockHttpContext(_cookieName, "valid-value"); + var httpContext = GetHttpContext(_cookieName, "valid-value"); var mockSerializer = new Mock(); mockSerializer @@ -157,19 +138,18 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal tokenSerializer: mockSerializer.Object); // Act - AntiforgeryToken retVal = tokenStore.GetCookieToken(mockHttpContext); + var token = tokenStore.GetCookieToken(httpContext); // Assert - Assert.Same(expectedToken, retVal); + Assert.Same(expectedToken, token); } [Fact] public async Task GetRequestTokens_CookieIsEmpty_Throws() { // Arrange - var httpContext = new DefaultHttpContext(); - httpContext.Request.Form = new FormCollection(new Dictionary()); - httpContext.Request.Cookies = new RequestCookieCollection(new Dictionary()); + var httpContext = GetHttpContext(new RequestCookieCollection()); + httpContext.Request.Form = FormCollection.Empty; var options = new AntiforgeryOptions() { @@ -193,15 +173,11 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal public async Task GetRequestTokens_NonFormContentType_HeaderDisabled_Throws() { // Arrange - var httpContext = new DefaultHttpContext(); + var httpContext = GetHttpContext("cookie-name", "cookie-value"); httpContext.Request.ContentType = "application/json"; // Will not be accessed httpContext.Request.Form = null; - httpContext.Request.Cookies = new RequestCookieCollection(new Dictionary() - { - { "cookie-name", "cookie-value" }, - }); var options = new AntiforgeryOptions() { @@ -226,16 +202,9 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal public async Task GetRequestTokens_FormContentType_FallbackHeaderToken() { // Arrange - var httpContext = new DefaultHttpContext(); - httpContext.Request.ContentType = "application/json"; - - // Will not be accessed + var httpContext = GetHttpContext("cookie-name", "cookie-value"); httpContext.Request.ContentType = "application/x-www-form-urlencoded"; - httpContext.Request.Form = new FormCollection(new Dictionary()); - httpContext.Request.Cookies = new RequestCookieCollection(new Dictionary() - { - { "cookie-name", "cookie-value" }, - }); + httpContext.Request.Form = FormCollection.Empty; httpContext.Request.Headers.Add("header-name", "header-value"); var options = new AntiforgeryOptions() @@ -261,17 +230,12 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal public async Task GetRequestTokens_NonFormContentType_UsesHeaderToken() { // Arrange - var httpContext = new DefaultHttpContext(); + var httpContext = GetHttpContext("cookie-name", "cookie-value"); httpContext.Request.ContentType = "application/json"; + httpContext.Request.Headers.Add("header-name", "header-value"); // Will not be accessed httpContext.Request.Form = null; - httpContext.Request.Cookies = new RequestCookieCollection(new Dictionary() - { - { "cookie-name", "cookie-value" }, - }); - - httpContext.Request.Headers.Add("header-name", "header-value"); var options = new AntiforgeryOptions() { @@ -296,15 +260,11 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal public async Task GetRequestTokens_NonFormContentType_UsesHeaderToken_ThrowsOnMissingValue() { // Arrange - var httpContext = new DefaultHttpContext(); + var httpContext = GetHttpContext("cookie-name", "cookie-value"); httpContext.Request.ContentType = "application/json"; // Will not be accessed httpContext.Request.Form = null; - httpContext.Request.Cookies = new RequestCookieCollection(new Dictionary() - { - { "cookie-name", "cookie-value" }, - }); var options = new AntiforgeryOptions() { @@ -329,13 +289,9 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal public async Task GetRequestTokens_BothFieldsEmpty_Throws() { // Arrange - var httpContext = new DefaultHttpContext(); + var httpContext = GetHttpContext("cookie-name", "cookie-value"); httpContext.Request.ContentType = "application/x-www-form-urlencoded"; - httpContext.Request.Form = new FormCollection(new Dictionary()); - httpContext.Request.Cookies = new RequestCookieCollection(new Dictionary() - { - { "cookie-name", "cookie-value" }, - }); + httpContext.Request.Form = FormCollection.Empty; var options = new AntiforgeryOptions() { @@ -363,16 +319,12 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal public async Task GetFormToken_FormFieldIsValid_ReturnsToken() { // Arrange - var httpContext = new DefaultHttpContext(); + var httpContext = GetHttpContext("cookie-name", "cookie-value"); httpContext.Request.ContentType = "application/x-www-form-urlencoded"; - httpContext.Request.Form = new FormCollection(new Dictionary() + httpContext.Request.Form = new FormCollection(new Dictionary { { "form-field-name", "form-value" }, }); - httpContext.Request.Cookies = new RequestCookieCollection(new Dictionary() - { - { "cookie-name", "cookie-value" }, - }); httpContext.Request.Headers.Add("header-name", "header-value"); // form value has priority. var options = new AntiforgeryOptions() @@ -401,22 +353,23 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal { // Arrange var token = new AntiforgeryToken(); - var mockCookies = new Mock(); - bool defaultCookieSecureValue = expectedCookieSecureFlag ?? false; // pulled from config; set by ctor var cookies = new MockResponseCookieCollection(); - cookies.Count = 0; var mockHttpContext = new Mock(); - mockHttpContext.Setup(o => o.Response.Cookies) - .Returns(cookies); + mockHttpContext + .Setup(o => o.Response.Cookies) + .Returns(cookies); + var contextAccessor = new DefaultAntiforgeryContextAccessor(); - mockHttpContext.SetupGet(o => o.RequestServices) - .Returns(GetServiceProvider(contextAccessor)); + mockHttpContext + .SetupGet(o => o.RequestServices) + .Returns(GetServiceProvider(contextAccessor)); var mockSerializer = new Mock(); - mockSerializer.Setup(o => o.Serialize(token)) - .Returns("serialized-value"); + mockSerializer + .Setup(o => o.Serialize(token)) + .Returns("serialized-value"); var options = new AntiforgeryOptions() { @@ -441,22 +394,30 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal Assert.Equal(defaultCookieSecureValue, cookies.Options.Secure); } - private HttpContext GetMockHttpContext(string cookieName, string cookieValue) + private HttpContext GetHttpContext( + string cookieName, + string cookieValue, + IAntiforgeryContextAccessor contextAccessor = null) { - var requestCookies = new MockCookieCollection(new Dictionary() { { cookieName, cookieValue } }); + var cookies = new RequestCookieCollection(new Dictionary + { + { cookieName, cookieValue }, + }); - var request = new Mock(); - request.Setup(o => o.Cookies) - .Returns(requestCookies); - var mockHttpContext = new Mock(); - mockHttpContext.Setup(o => o.Request) - .Returns(request.Object); + return GetHttpContext(cookies, contextAccessor); + } - var contextAccessor = new DefaultAntiforgeryContextAccessor(); - mockHttpContext.SetupGet(o => o.RequestServices) - .Returns(GetServiceProvider(contextAccessor)); + private HttpContext GetHttpContext( + IRequestCookieCollection cookies, + IAntiforgeryContextAccessor contextAccessor = null) + { + var httpContext = new DefaultHttpContext(); + httpContext.Request.Cookies = cookies; - return mockHttpContext.Object; + contextAccessor = contextAccessor ?? new DefaultAntiforgeryContextAccessor(); + httpContext.RequestServices = GetServiceProvider(contextAccessor); + + return httpContext; } private static IServiceProvider GetServiceProvider(IAntiforgeryContextAccessor contextAccessor) @@ -496,65 +457,5 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal throw new NotImplementedException(); } } - - private class MockCookieCollection : IRequestCookieCollection - { - private Dictionary _dictionary; - - public int Count - { - get - { - return _dictionary.Count; - } - } - - public ICollection Keys - { - get - { - return _dictionary.Keys; - } - } - - public MockCookieCollection(Dictionary dictionary) - { - _dictionary = dictionary; - } - - public static MockCookieCollection GetDummyInstance(string key, string value) - { - return new MockCookieCollection(new Dictionary() { { key, value } }); - } - - public bool ContainsKey(string key) - { - return _dictionary.ContainsKey(key); - } - - public string this[string key] - { - get - { - string value; - return _dictionary.TryGetValue(key, out value) ? value : null; - } - } - - public bool TryGetValue(string key, out string value) - { - return _dictionary.TryGetValue(key, out value); - } - - public IEnumerator> GetEnumerator() - { - throw new NotImplementedException(); - } - - System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() - { - throw new NotImplementedException(); - } - } } } From 3a2d09b0662709c99b1f26168b00d0067b3f6c1b Mon Sep 17 00:00:00 2001 From: Ryan Nowak Date: Thu, 4 Feb 2016 08:36:35 -0800 Subject: [PATCH 078/296] Move exceptions from the store to the facade My earlier change to add TryValidateRequestAsync didn't go far enough, because the store will still throw when the tokens aren't present. This change is to make the store just return null tokens in these cases, and move the exceptions to DefaultAntiforgery. --- .../AntiforgeryTokenSet.cs | 9 -- .../Internal/DefaultAntiforgery.cs | 35 +++++- .../Internal/DefaultAntiforgeryTokenStore.cs | 32 +----- .../Internal/IAntiforgeryTokenStore.cs | 4 +- .../Internal/DefaultAntiforgeryTest.cs | 103 ++++++++++++++++++ .../DefaultAntiforgeryTokenStoreTest.cs | 35 +++--- 6 files changed, 156 insertions(+), 62 deletions(-) diff --git a/src/Microsoft.AspNetCore.Antiforgery/AntiforgeryTokenSet.cs b/src/Microsoft.AspNetCore.Antiforgery/AntiforgeryTokenSet.cs index 2b99141894..033e5e0731 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/AntiforgeryTokenSet.cs +++ b/src/Microsoft.AspNetCore.Antiforgery/AntiforgeryTokenSet.cs @@ -23,22 +23,13 @@ namespace Microsoft.AspNetCore.Antiforgery string formFieldName, string headerName) { - if (string.IsNullOrEmpty(requestToken)) - { - throw new ArgumentException(Resources.ArgumentCannotBeNullOrEmpty, nameof(requestToken)); - } - if (formFieldName == null) { throw new ArgumentNullException(nameof(formFieldName)); } RequestToken = requestToken; - - // Cookie Token is allowed to be null in the case when the old cookie is valid - // and there is no new cookieToken generated. CookieToken = cookieToken; - FormFieldName = formFieldName; HeaderName = headerName; } diff --git a/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgery.cs b/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgery.cs index 6d52cfa4da..1a581a5f54 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgery.cs +++ b/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgery.cs @@ -93,6 +93,10 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal CheckSSLConfig(httpContext); var tokens = await _tokenStore.GetRequestTokensAsync(httpContext); + if (tokens.CookieToken == null || tokens.RequestToken == null) + { + return false; + } // Extract cookie & request tokens var deserializedCookieToken = _tokenSerializer.Deserialize(tokens.CookieToken); @@ -118,6 +122,33 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal CheckSSLConfig(httpContext); var tokens = await _tokenStore.GetRequestTokensAsync(httpContext); + if (tokens.CookieToken == null) + { + throw new AntiforgeryValidationException( + Resources.FormatAntiforgery_CookieToken_MustBeProvided(_options.CookieName)); + } + + if (tokens.RequestToken == null) + { + if (_options.HeaderName == null) + { + var message = Resources.FormatAntiforgery_FormToken_MustBeProvided(_options.FormFieldName); + throw new AntiforgeryValidationException(message); + } + else if (!httpContext.Request.HasFormContentType) + { + var message = Resources.FormatAntiforgery_HeaderToken_MustBeProvided(_options.HeaderName); + throw new AntiforgeryValidationException(message); + } + else + { + var message = Resources.FormatAntiforgery_RequestToken_MustBeProvided( + _options.FormFieldName, + _options.HeaderName); + throw new AntiforgeryValidationException(message); + } + } + ValidateTokens(httpContext, tokens); } @@ -262,8 +293,8 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal private AntiforgeryTokenSet Serialize(AntiforgeryTokenSetInternal tokenSet) { return new AntiforgeryTokenSet( - tokenSet.RequestToken != null ? _tokenSerializer.Serialize(tokenSet.RequestToken) : null, - tokenSet.CookieToken != null ? _tokenSerializer.Serialize(tokenSet.CookieToken) : null, + _tokenSerializer.Serialize(tokenSet.RequestToken), + _tokenSerializer.Serialize(tokenSet.CookieToken), _options.FormFieldName, _options.HeaderName); } diff --git a/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgeryTokenStore.cs b/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgeryTokenStore.cs index 52d852a27c..5b0f41426a 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgeryTokenStore.cs +++ b/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgeryTokenStore.cs @@ -65,18 +65,13 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal throw new ArgumentNullException(nameof(httpContext)); } - var requestCookie = httpContext.Request.Cookies[_options.CookieName]; - if (string.IsNullOrEmpty(requestCookie)) - { - throw new AntiforgeryValidationException( - Resources.FormatAntiforgery_CookieToken_MustBeProvided(_options.CookieName)); - } + var cookieToken = httpContext.Request.Cookies[_options.CookieName]; StringValues requestToken; if (httpContext.Request.HasFormContentType) { // Check the content-type before accessing the form collection to make sure - // we throw gracefully. + // we report errors gracefully. var form = await httpContext.Request.ReadFormAsync(); requestToken = form[_options.FormFieldName]; } @@ -87,28 +82,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal requestToken = httpContext.Request.Headers[_options.HeaderName]; } - if (requestToken.Count == 0) - { - if (_options.HeaderName == null) - { - var message = Resources.FormatAntiforgery_FormToken_MustBeProvided(_options.FormFieldName); - throw new AntiforgeryValidationException(message); - } - else if (!httpContext.Request.HasFormContentType) - { - var message = Resources.FormatAntiforgery_HeaderToken_MustBeProvided(_options.HeaderName); - throw new AntiforgeryValidationException(message); - } - else - { - var message = Resources.FormatAntiforgery_RequestToken_MustBeProvided( - _options.FormFieldName, - _options.HeaderName); - throw new AntiforgeryValidationException(message); - } - } - - return new AntiforgeryTokenSet(requestToken, requestCookie, _options.FormFieldName, _options.HeaderName); + return new AntiforgeryTokenSet(requestToken, cookieToken, _options.FormFieldName, _options.HeaderName); } public void SaveCookieToken(HttpContext httpContext, AntiforgeryToken token) diff --git a/src/Microsoft.AspNetCore.Antiforgery/Internal/IAntiforgeryTokenStore.cs b/src/Microsoft.AspNetCore.Antiforgery/Internal/IAntiforgeryTokenStore.cs index bff9360ff9..967887a44f 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/Internal/IAntiforgeryTokenStore.cs +++ b/src/Microsoft.AspNetCore.Antiforgery/Internal/IAntiforgeryTokenStore.cs @@ -6,14 +6,12 @@ using Microsoft.AspNetCore.Http; namespace Microsoft.AspNetCore.Antiforgery.Internal { - // Provides an abstraction around how tokens are persisted and retrieved for a request public interface IAntiforgeryTokenStore { AntiforgeryToken GetCookieToken(HttpContext httpContext); /// - /// Gets the cookie and request tokens from the request. Will throw an exception if either token is - /// not present. + /// Gets the cookie and request tokens from the request. /// /// The for the current request. /// The . diff --git a/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTest.cs b/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTest.cs index 0e8dfeb8dd..040cf866a4 100644 --- a/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTest.cs +++ b/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTest.cs @@ -591,6 +591,109 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal context.TokenGenerator.Verify(); } + [Fact] + public async Task ValidateRequestAsync_NoCookieToken_Throws() + { + // Arrange + var context = CreateMockContext(new AntiforgeryOptions() + { + CookieName = "cookie-name", + FormFieldName = "form-field-name", + HeaderName = null, + }); + + var tokenSet = new AntiforgeryTokenSet(null, null, "form-field-name", null); + context.TokenStore + .Setup(s => s.GetRequestTokensAsync(context.HttpContext)) + .Returns(Task.FromResult(tokenSet)); + + var antiforgery = GetAntiforgery(context); + + // Act & Assert + var exception = await Assert.ThrowsAsync( + () => antiforgery.ValidateRequestAsync(context.HttpContext)); + Assert.Equal("The required antiforgery cookie \"cookie-name\" is not present.", exception.Message); + } + + [Fact] + public async Task ValidateRequestAsync_NonFormRequest_HeaderDisabled_Throws() + { + // Arrange + var context = CreateMockContext(new AntiforgeryOptions() + { + CookieName = "cookie-name", + FormFieldName = "form-field-name", + HeaderName = null, + }); + + var tokenSet = new AntiforgeryTokenSet(null, "cookie-token", "form-field-name", null); + context.TokenStore + .Setup(s => s.GetRequestTokensAsync(context.HttpContext)) + .Returns(Task.FromResult(tokenSet)); + + var antiforgery = GetAntiforgery(context); + + // Act & Assert + var exception = await Assert.ThrowsAsync( + () => antiforgery.ValidateRequestAsync(context.HttpContext)); + Assert.Equal("The required antiforgery form field \"form-field-name\" is not present.", exception.Message); + } + + [Fact] + public async Task ValidateRequestAsync_NonFormRequest_NoHeaderValue_Throws() + { + // Arrange + var context = CreateMockContext(new AntiforgeryOptions() + { + CookieName = "cookie-name", + FormFieldName = "form-field-name", + HeaderName = "header-name", + }); + + context.HttpContext.Request.ContentType = "application/json"; + + var tokenSet = new AntiforgeryTokenSet(null, "cookie-token", "form-field-name", "header-name"); + context.TokenStore + .Setup(s => s.GetRequestTokensAsync(context.HttpContext)) + .Returns(Task.FromResult(tokenSet)); + + var antiforgery = GetAntiforgery(context); + + // Act & Assert + var exception = await Assert.ThrowsAsync( + () => antiforgery.ValidateRequestAsync(context.HttpContext)); + Assert.Equal("The required antiforgery header value \"header-name\" is not present.", exception.Message); + } + + [Fact] + public async Task ValidateRequestAsync_FormRequest_NoRequestTokenValue_Throws() + { + // Arrange + var context = CreateMockContext(new AntiforgeryOptions() + { + CookieName = "cookie-name", + FormFieldName = "form-field-name", + HeaderName = "header-name", + }); + + context.HttpContext.Request.ContentType = "application/x-www-form-urlencoded"; + + var tokenSet = new AntiforgeryTokenSet(null, "cookie-token", "form-field-name", "header-name"); + context.TokenStore + .Setup(s => s.GetRequestTokensAsync(context.HttpContext)) + .Returns(Task.FromResult(tokenSet)); + + var antiforgery = GetAntiforgery(context); + + // Act & Assert + var exception = await Assert.ThrowsAsync( + () => antiforgery.ValidateRequestAsync(context.HttpContext)); + Assert.Equal( + "The required antiforgery request token was not provided in either form field \"form-field-name\" " + + "or header value \"header-name\".", + exception.Message); + } + [Theory] [InlineData(false, "SAMEORIGIN")] [InlineData(true, null)] diff --git a/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTokenStoreTest.cs b/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTokenStoreTest.cs index 13f3ff7082..16ad4857a1 100644 --- a/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTokenStoreTest.cs +++ b/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTokenStoreTest.cs @@ -145,7 +145,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal } [Fact] - public async Task GetRequestTokens_CookieIsEmpty_Throws() + public async Task GetRequestTokens_CookieIsEmpty_ReturnsNullTokens() { // Arrange var httpContext = GetHttpContext(new RequestCookieCollection()); @@ -162,15 +162,15 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal tokenSerializer: Mock.Of()); // Act - var exception = await Assert.ThrowsAsync( - async () => await tokenStore.GetRequestTokensAsync(httpContext)); + var tokenSet = await tokenStore.GetRequestTokensAsync(httpContext); // Assert - Assert.Equal("The required antiforgery cookie \"cookie-name\" is not present.", exception.Message); + Assert.Null(tokenSet.CookieToken); + Assert.Null(tokenSet.RequestToken); } [Fact] - public async Task GetRequestTokens_NonFormContentType_HeaderDisabled_Throws() + public async Task GetRequestTokens_NonFormContentType_HeaderDisabled_ReturnsNullToken() { // Arrange var httpContext = GetHttpContext("cookie-name", "cookie-value"); @@ -191,11 +191,11 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal tokenSerializer: new DefaultAntiforgeryTokenSerializer(new EphemeralDataProtectionProvider(), _pool)); // Act - var exception = await Assert.ThrowsAsync( - async () => await tokenStore.GetRequestTokensAsync(httpContext)); + var tokenSet = await tokenStore.GetRequestTokensAsync(httpContext); // Assert - Assert.Equal("The required antiforgery form field \"form-field-name\" is not present.", exception.Message); + Assert.Equal("cookie-value", tokenSet.CookieToken); + Assert.Null(tokenSet.RequestToken); } [Fact] @@ -257,7 +257,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal } [Fact] - public async Task GetRequestTokens_NonFormContentType_UsesHeaderToken_ThrowsOnMissingValue() + public async Task GetRequestTokens_NonFormContentType_NoHeaderToken_ReturnsNullToken() { // Arrange var httpContext = GetHttpContext("cookie-name", "cookie-value"); @@ -278,15 +278,15 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal tokenSerializer: new DefaultAntiforgeryTokenSerializer(new EphemeralDataProtectionProvider(), _pool)); // Act - var exception = await Assert.ThrowsAsync( - async () => await tokenStore.GetRequestTokensAsync(httpContext)); + var tokenSet = await tokenStore.GetRequestTokensAsync(httpContext); // Assert - Assert.Equal("The required antiforgery header value \"header-name\" is not present.", exception.Message); + Assert.Equal("cookie-value", tokenSet.CookieToken); + Assert.Null(tokenSet.RequestToken); } [Fact] - public async Task GetRequestTokens_BothFieldsEmpty_Throws() + public async Task GetRequestTokens_BothFieldsEmpty_ReturnsNullTokens() { // Arrange var httpContext = GetHttpContext("cookie-name", "cookie-value"); @@ -305,14 +305,11 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal tokenSerializer: Mock.Of()); // Act - var exception = await Assert.ThrowsAsync( - async () => await tokenStore.GetRequestTokensAsync(httpContext)); + var tokenSet = await tokenStore.GetRequestTokensAsync(httpContext); // Assert - Assert.Equal( - "The required antiforgery request token was not provided in either form field \"form-field-name\" " + - "or header value \"header-name\".", - exception.Message); + Assert.Equal("cookie-value", tokenSet.CookieToken); + Assert.Null(tokenSet.RequestToken); } [Fact] From 33e3001d5367638930341179feaaadd7d8bf0543 Mon Sep 17 00:00:00 2001 From: Ryan Nowak Date: Thu, 4 Feb 2016 11:22:26 -0800 Subject: [PATCH 079/296] Remove GetHtml It's being moved to MVC --- .../IAntiforgery.cs | 15 -- .../Internal/DefaultAntiforgery.cs | 54 ------- .../project.json | 1 - .../Internal/DefaultAntiforgeryTest.cs | 152 ------------------ 4 files changed, 222 deletions(-) diff --git a/src/Microsoft.AspNetCore.Antiforgery/IAntiforgery.cs b/src/Microsoft.AspNetCore.Antiforgery/IAntiforgery.cs index d2eac4c95a..583a71ffea 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/IAntiforgery.cs +++ b/src/Microsoft.AspNetCore.Antiforgery/IAntiforgery.cs @@ -2,7 +2,6 @@ // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Threading.Tasks; -using Microsoft.AspNetCore.Html; using Microsoft.AspNetCore.Http; namespace Microsoft.AspNetCore.Antiforgery @@ -13,20 +12,6 @@ namespace Microsoft.AspNetCore.Antiforgery /// public interface IAntiforgery { - /// - /// Generates an <input type="hidden"> element for an antiforgery token. - /// - /// The associated with the current request. - /// - /// A containing an <input type="hidden"> element. This element should be put - /// inside a <form>. - /// - /// - /// This method has a side effect: - /// A response cookie is set if there is no valid cookie associated with the request. - /// - IHtmlContent GetHtml(HttpContext httpContext); - /// /// Generates an for this request and stores the cookie token /// in the response. diff --git a/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgery.cs b/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgery.cs index 1a581a5f54..76a5ff8f30 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgery.cs +++ b/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgery.cs @@ -3,10 +3,7 @@ using System; using System.Diagnostics; -using System.IO; -using System.Text.Encodings.Web; using System.Threading.Tasks; -using Microsoft.AspNetCore.Html; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Options; @@ -35,20 +32,6 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal _tokenStore = tokenStore; } - /// - public IHtmlContent GetHtml(HttpContext httpContext) - { - if (httpContext == null) - { - throw new ArgumentNullException(nameof(httpContext)); - } - - CheckSSLConfig(httpContext); - - var tokenSet = GetAndStoreTokens(httpContext); - return new InputContent(_options.FormFieldName, tokenSet.RequestToken); - } - /// public AntiforgeryTokenSet GetAndStoreTokens(HttpContext httpContext) { @@ -307,42 +290,5 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal public bool IsNewCookieToken { get; set; } } - - private class InputContent : IHtmlContent - { - private readonly string _fieldName; - private readonly string _requestToken; - - public InputContent(string fieldName, string requestToken) - { - _fieldName = fieldName; - _requestToken = requestToken; - } - - // Though _requestToken normally contains only US-ASCII letters, numbers, '-', and '_', must assume the - // IAntiforgeryTokenSerializer implementation has been overridden. Similarly, users may choose a - // _fieldName containing almost any character. - public void WriteTo(TextWriter writer, HtmlEncoder encoder) - { - var builder = writer as IHtmlContentBuilder; - if (builder != null) - { - // If possible, defer encoding until we're writing to the response. - // But there's little reason to keep this IHtmlContent instance around. - builder - .AppendHtml(""); - } - - writer.Write(""); - } - } } } \ No newline at end of file diff --git a/src/Microsoft.AspNetCore.Antiforgery/project.json b/src/Microsoft.AspNetCore.Antiforgery/project.json index 1499e577c7..bcd5357d8d 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/project.json +++ b/src/Microsoft.AspNetCore.Antiforgery/project.json @@ -11,7 +11,6 @@ }, "dependencies": { "Microsoft.AspNetCore.DataProtection": "1.0.0-*", - "Microsoft.AspNetCore.Html.Abstractions": "1.0.0-*", "Microsoft.AspNetCore.Http.Abstractions": "1.0.0-*", "Microsoft.AspNetCore.WebUtilities": "1.0.0-*", "Microsoft.Extensions.ObjectPool": "1.0.0-*" diff --git a/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTest.cs b/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTest.cs index 040cf866a4..e1f64fcab2 100644 --- a/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTest.cs +++ b/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTest.cs @@ -2,14 +2,12 @@ // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; -using System.IO; using System.Security.Claims; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.Internal; using Microsoft.AspNetCore.Testing; using Microsoft.Extensions.Options; -using Microsoft.Extensions.WebEncoders.Testing; using Moq; using Xunit; @@ -81,26 +79,6 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal exception.Message); } - [Fact] - public void ChecksSSL_GetHtml_Throws() - { - // Arrange - var httpContext = new DefaultHttpContext(); - var options = new AntiforgeryOptions() - { - RequireSsl = true - }; - - var antiforgery = GetAntiforgery(options); - - // Act & Assert - var exception = Assert.Throws(() => antiforgery.GetHtml(httpContext)); - Assert.Equal( - @"The antiforgery system has the configuration value AntiforgeryOptions.RequireSsl = true, " + - "but the current request is not an SSL request.", - exception.Message); - } - [Fact] public void ChecksSSL_GetAndStoreTokens_Throws() { @@ -164,136 +142,6 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal exception.Message); } - [Fact] - public void GetHtml_ExistingInvalidCookieToken_GeneratesANewCookieAndAnAntiforgeryToken() - { - // Arrange - var options = new AntiforgeryOptions() - { - FormFieldName = "form-field-name" - }; - - // Make sure the existing cookie is invalid. - var context = CreateMockContext(options, isOldCookieValid: false); - var antiforgery = GetAntiforgery(context); - var encoder = new HtmlTestEncoder(); - - // Setup so that the null cookie token returned is treated as invalid. - context.TokenGenerator - .Setup(o => o.IsCookieTokenValid(null)) - .Returns(false); - - // Act - var inputElement = antiforgery.GetHtml(context.HttpContext); - - // Assert - using (var writer = new StringWriter()) - { - inputElement.WriteTo(writer, encoder); - - Assert.Equal( - @"", - writer.ToString()); - } - - context.TokenStore.Verify(); - } - - [Fact] - public void GetHtml_ExistingInvalidCookieToken_SwallowsExceptions() - { - // Arrange - var options = new AntiforgeryOptions() - { - FormFieldName = "form-field-name" - }; - - // Make sure the existing cookie is invalid. - var context = CreateMockContext(options, isOldCookieValid: false); - var antiforgery = GetAntiforgery(context); - - // This will cause the cookieToken to be null. - context.TokenStore - .Setup(o => o.GetCookieToken(context.HttpContext)) - .Throws(new Exception("should be swallowed")); - - // Setup so that the null cookie token returned is treated as invalid. - context.TokenGenerator - .Setup(o => o.IsCookieTokenValid(null)) - .Returns(false); - - var encoder = new HtmlTestEncoder(); - - // Act - var inputElement = antiforgery.GetHtml(context.HttpContext); - - // Assert - using (var writer = new StringWriter()) - { - inputElement.WriteTo(writer, encoder); - - Assert.Equal( - @"", - writer.ToString()); - } - - context.TokenStore.Verify(); - } - - [Fact] - public void GetHtml_ExistingValidCookieToken_GeneratesAnAntiforgeryToken() - { - // Arrange - var options = new AntiforgeryOptions() - { - FormFieldName = "form-field-name" - }; - - // Make sure the existing cookie is valid and use the same cookie for the mock Token Provider. - var context = CreateMockContext(options, useOldCookie: true, isOldCookieValid: true); - var antiforgery = GetAntiforgery(context); - var encoder = new HtmlTestEncoder(); - - // Act - var inputElement = antiforgery.GetHtml(context.HttpContext); - - // Assert - using (var writer = new StringWriter()) - { - inputElement.WriteTo(writer, encoder); - - Assert.Equal( - @"", - writer.ToString()); - } - } - - [Theory] - [InlineData(false, "SAMEORIGIN")] - [InlineData(true, null)] - public void GetHtml_AddsXFrameOptionsHeader(bool suppressXFrameOptions, string expectedHeaderValue) - { - // Arrange - var options = new AntiforgeryOptions() - { - SuppressXFrameOptionsHeader = suppressXFrameOptions - }; - - // Generate a new cookie. - var context = CreateMockContext(options, useOldCookie: false, isOldCookieValid: false); - var antiforgery = GetAntiforgery(context); - - // Act - antiforgery.GetHtml(context.HttpContext); - - // Assert - string xFrameOptions = context.HttpContext.Response.Headers["X-Frame-Options"]; - Assert.Equal(expectedHeaderValue, xFrameOptions); - } - [Fact] public void GetTokens_ExistingInvalidCookieToken_GeneratesANewCookieTokenAndANewFormToken() { From 9445574aa15a106d69c22773b4f49fdfacb19451 Mon Sep 17 00:00:00 2001 From: Ajay Bhargav Baaskaran Date: Thu, 4 Feb 2016 16:04:44 -0800 Subject: [PATCH 080/296] Updated Json.Net version --- samples/AntiforgerySample/project.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/samples/AntiforgerySample/project.json b/samples/AntiforgerySample/project.json index a02c73b3aa..761ce827e4 100644 --- a/samples/AntiforgerySample/project.json +++ b/samples/AntiforgerySample/project.json @@ -9,7 +9,7 @@ "Microsoft.AspNetCore.Server.Kestrel": "1.0.0-*", "Microsoft.AspNetCore.StaticFiles": "1.0.0-*", "Microsoft.NETCore.Platforms": "1.0.1-*", - "Newtonsoft.Json": "7.0.1" + "Newtonsoft.Json": "8.0.2" }, "compilationOptions": { From 08cf13b870dce046b1e0033dcbc251df6a63ebe5 Mon Sep 17 00:00:00 2001 From: Doug Bunting Date: Fri, 5 Feb 2016 10:54:20 -0800 Subject: [PATCH 081/296] Remove `ValidateTokens()` from `IAntiforgery` - `IAntiforgery` does not expose a way to get an invalid `AntiforgeryTokenSet` --- .../IAntiforgery.cs | 9 -- .../Internal/DefaultAntiforgery.cs | 3 +- .../Internal/DefaultAntiforgeryTest.cs | 116 +----------------- 3 files changed, 4 insertions(+), 124 deletions(-) diff --git a/src/Microsoft.AspNetCore.Antiforgery/IAntiforgery.cs b/src/Microsoft.AspNetCore.Antiforgery/IAntiforgery.cs index 583a71ffea..0cdcf35a8b 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/IAntiforgery.cs +++ b/src/Microsoft.AspNetCore.Antiforgery/IAntiforgery.cs @@ -54,15 +54,6 @@ namespace Microsoft.AspNetCore.Antiforgery /// Task ValidateRequestAsync(HttpContext httpContext); - /// - /// Validates an for the current request. - /// - /// The associated with the current request. - /// - /// The (cookie and request token) for this request. - /// - void ValidateTokens(HttpContext httpContext, AntiforgeryTokenSet antiforgeryTokenSet); - /// /// Generates and stores an antiforgery cookie token if one is not available or not valid. /// diff --git a/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgery.cs b/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgery.cs index 76a5ff8f30..d25909886d 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgery.cs +++ b/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgery.cs @@ -135,8 +135,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal ValidateTokens(httpContext, tokens); } - /// - public void ValidateTokens(HttpContext httpContext, AntiforgeryTokenSet antiforgeryTokenSet) + private void ValidateTokens(HttpContext httpContext, AntiforgeryTokenSet antiforgeryTokenSet) { if (httpContext == null) { diff --git a/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTest.cs b/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTest.cs index e1f64fcab2..4651a14d83 100644 --- a/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTest.cs +++ b/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTest.cs @@ -6,7 +6,6 @@ using System.Security.Claims; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.Internal; -using Microsoft.AspNetCore.Testing; using Microsoft.Extensions.Options; using Moq; using Xunit; @@ -57,28 +56,6 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal exception.Message); } - [Fact] - public void ChecksSSL_ValidateTokens_Throws() - { - // Arrange - var httpContext = new DefaultHttpContext(); - var options = new AntiforgeryOptions() - { - RequireSsl = true - }; - - var antiforgery = GetAntiforgery(options); - var tokenSet = new AntiforgeryTokenSet("hello", "world", "form", "header"); - - // Act & Assert - var exception = Assert.Throws( - () => antiforgery.ValidateTokens(httpContext, tokenSet)); - Assert.Equal( - @"The antiforgery system has the configuration value AntiforgeryOptions.RequireSsl = true, " + - "but the current request is not an SSL request.", - exception.Message); - } - [Fact] public void ChecksSSL_GetAndStoreTokens_Throws() { @@ -248,95 +225,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal } [Fact] - public void ValidateTokens_InvalidTokens_Throws() - { - // Arrange - var context = CreateMockContext(new AntiforgeryOptions()); - - context.TokenSerializer - .Setup(o => o.Deserialize("cookie-token")) - .Returns(context.TestTokenSet.OldCookieToken); - context.TokenSerializer - .Setup(o => o.Deserialize("form-token")) - .Returns(context.TestTokenSet.RequestToken); - - var message = "my-message"; - context.TokenGenerator - .Setup(o => o.TryValidateTokenSet( - context.HttpContext, - context.TestTokenSet.OldCookieToken, - context.TestTokenSet.RequestToken, - out message)) - .Returns(false) - .Verifiable(); - - var antiforgery = new DefaultAntiforgery( - new TestOptionsManager(), - context.TokenGenerator.Object, - context.TokenSerializer.Object, - tokenStore: null); - - var tokenSet = new AntiforgeryTokenSet("form-token", "cookie-token", "form", "header"); - - // Act & Assert - var exception = Assert.Throws( - () => antiforgery.ValidateTokens( - context.HttpContext, - tokenSet)); - Assert.Equal("my-message", exception.Message); - context.TokenGenerator.Verify(); - } - - [Fact] - public void ValidateTokens_FromValidStrings_TokensValidatedSuccessfully() - { - // Arrange - var context = CreateMockContext(new AntiforgeryOptions()); - context.TokenSerializer - .Setup(o => o.Deserialize("cookie-token")) - .Returns(context.TestTokenSet.OldCookieToken); - context.TokenSerializer - .Setup(o => o.Deserialize("form-token")) - .Returns(context.TestTokenSet.RequestToken); - - string message; - context.TokenGenerator - .Setup(o => o.TryValidateTokenSet( - context.HttpContext, - context.TestTokenSet.OldCookieToken, - context.TestTokenSet.RequestToken, - out message)) - .Returns(true) - .Verifiable(); - context.TokenStore = null; - var antiforgery = GetAntiforgery(context); - - var tokenSet = new AntiforgeryTokenSet("form-token", "cookie-token", "form", "header"); - - // Act - antiforgery.ValidateTokens(context.HttpContext, tokenSet); - - // Assert - context.TokenGenerator.Verify(); - } - - [Fact] - public void ValidateTokens_MissingCookieInTokenSet_Throws() - { - // Arrange - var context = CreateMockContext(new AntiforgeryOptions()); - var antiforgery = GetAntiforgery(context); - var tokenSet = new AntiforgeryTokenSet("form-token", null, "form", "header"); - - // Act - ExceptionAssert.ThrowsArgument( - () => antiforgery.ValidateTokens(context.HttpContext, tokenSet), - "antiforgeryTokenSet", - "The required antiforgery cookie token must be provided."); - } - - [Fact] - public async Task IsRequestValueAsync_FromStore_Failure() + public async Task IsRequestValidAsync_FromStore_Failure() { // Arrange var context = CreateMockContext(new AntiforgeryOptions()); @@ -357,6 +246,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal // Assert Assert.False(result); + context.TokenGenerator.Verify(); } [Fact] @@ -409,7 +299,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal // Act & assert var exception = await Assert.ThrowsAsync( - async () => await antiforgery.ValidateRequestAsync(context.HttpContext)); + () => antiforgery.ValidateRequestAsync(context.HttpContext)); Assert.Equal("my-message", exception.Message); context.TokenGenerator.Verify(); } From c8a9ecc0c13e2e3bac0d9fd7dee96a9e3eb427f8 Mon Sep 17 00:00:00 2001 From: ryanbrandenburg Date: Fri, 5 Feb 2016 15:18:56 -0800 Subject: [PATCH 082/296] * Add logging to Antiforgery --- .../Internal/AntiforgeryLoggerExtensions.cs | 77 +++++++++++++++++++ .../Internal/DefaultAntiforgery.cs | 34 +++++++- .../Internal/DefaultAntiforgeryTest.cs | 50 +++++++----- .../project.json | 3 +- 4 files changed, 141 insertions(+), 23 deletions(-) create mode 100644 src/Microsoft.AspNetCore.Antiforgery/Internal/AntiforgeryLoggerExtensions.cs diff --git a/src/Microsoft.AspNetCore.Antiforgery/Internal/AntiforgeryLoggerExtensions.cs b/src/Microsoft.AspNetCore.Antiforgery/Internal/AntiforgeryLoggerExtensions.cs new file mode 100644 index 0000000000..aae0b3176e --- /dev/null +++ b/src/Microsoft.AspNetCore.Antiforgery/Internal/AntiforgeryLoggerExtensions.cs @@ -0,0 +1,77 @@ +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System; +using Microsoft.Extensions.Logging; + +namespace Microsoft.AspNetCore.Antiforgery.Internal +{ + internal static class AntiforgeryLoggerExtensions + { + private static readonly Action _validationFailed; + private static readonly Action _validated; + private static readonly Action _missingCookieToken; + private static readonly Action _missingRequestToken; + private static readonly Action _newCookieToken; + private static readonly Action _reusedCookieToken; + + static AntiforgeryLoggerExtensions() + { + _validationFailed = LoggerMessage.Define( + LogLevel.Warning, + 1, + "Antiforgery validation failed with message '{Message}'."); + _validated = LoggerMessage.Define( + LogLevel.Debug, + 2, + "Antiforgery successfully validated a request."); + _missingCookieToken = LoggerMessage.Define( + LogLevel.Warning, + 3, + "The required antiforgery cookie '{CookieName}' is not present."); + _missingRequestToken = LoggerMessage.Define( + LogLevel.Warning, + 4, + "The required antiforgery request token was not provided in either form field '{FormFieldName}' " + + "or header '{HeaderName}'."); + _newCookieToken = LoggerMessage.Define( + LogLevel.Debug, + 5, + "A new antiforgery cookie token was created."); + _reusedCookieToken = LoggerMessage.Define( + LogLevel.Debug, + 6, + "An antiforgery cookie token was reused."); + } + + public static void ValidationFailed(this ILogger logger, string message) + { + _validationFailed(logger, message, null); + } + + public static void ValidatedAntiforgeryToken(this ILogger logger) + { + _validated(logger, null); + } + + public static void MissingCookieToken(this ILogger logger, string cookieName) + { + _missingCookieToken(logger, cookieName, null); + } + + public static void MissingRequestToken(this ILogger logger, string formFieldName, string headerName) + { + _missingRequestToken(logger, formFieldName, headerName, null); + } + + public static void NewCookieToken(this ILogger logger) + { + _newCookieToken(logger, null); + } + + public static void ReusedCookieToken(this ILogger logger) + { + _reusedCookieToken(logger, null); + } + } +} diff --git a/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgery.cs b/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgery.cs index d25909886d..db4d29e62f 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgery.cs +++ b/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgery.cs @@ -5,6 +5,7 @@ using System; using System.Diagnostics; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; namespace Microsoft.AspNetCore.Antiforgery.Internal @@ -19,17 +20,20 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal private readonly IAntiforgeryTokenGenerator _tokenGenerator; private readonly IAntiforgeryTokenSerializer _tokenSerializer; private readonly IAntiforgeryTokenStore _tokenStore; + private readonly ILogger _logger; public DefaultAntiforgery( IOptions antiforgeryOptionsAccessor, IAntiforgeryTokenGenerator tokenGenerator, IAntiforgeryTokenSerializer tokenSerializer, - IAntiforgeryTokenStore tokenStore) + IAntiforgeryTokenStore tokenStore, + ILoggerFactory loggerFactory) { _options = antiforgeryOptionsAccessor.Value; _tokenGenerator = tokenGenerator; _tokenSerializer = tokenSerializer; _tokenStore = tokenStore; + _logger = loggerFactory.CreateLogger(); } /// @@ -46,6 +50,11 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal if (tokenSet.IsNewCookieToken) { SaveCookieTokenAndHeader(httpContext, tokenSet.CookieToken); + _logger.NewCookieToken(); + } + else + { + _logger.ReusedCookieToken(); } return Serialize(tokenSet); @@ -76,8 +85,14 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal CheckSSLConfig(httpContext); var tokens = await _tokenStore.GetRequestTokensAsync(httpContext); - if (tokens.CookieToken == null || tokens.RequestToken == null) + if (tokens.CookieToken == null) { + _logger.MissingCookieToken(_options.CookieName); + return false; + } + if (tokens.RequestToken == null) + { + _logger.MissingRequestToken(_options.FormFieldName, _options.HeaderName); return false; } @@ -87,11 +102,22 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal // Validate string message; - return _tokenGenerator.TryValidateTokenSet( + var result = _tokenGenerator.TryValidateTokenSet( httpContext, deserializedCookieToken, deserializedRequestToken, out message); + + if (result) + { + _logger.ValidatedAntiforgeryToken(); + } + else + { + _logger.ValidationFailed(message); + } + + return result; } /// @@ -133,6 +159,8 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal } ValidateTokens(httpContext, tokens); + + _logger.ValidatedAntiforgeryToken(); } private void ValidateTokens(HttpContext httpContext, AntiforgeryTokenSet antiforgeryTokenSet) diff --git a/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTest.cs b/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTest.cs index 4651a14d83..8969b05c31 100644 --- a/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTest.cs +++ b/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTest.cs @@ -6,6 +6,9 @@ using System.Security.Claims; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.Internal; +using Microsoft.AspNetCore.Testing; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Moq; using Xunit; @@ -18,13 +21,12 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal public async Task ChecksSSL_ValidateRequestAsync_Throws() { // Arrange - var httpContext = new DefaultHttpContext(); + var httpContext = GetHttpContext(); var options = new AntiforgeryOptions() { RequireSsl = true }; - - var antiforgery = GetAntiforgery(options); + var antiforgery = GetAntiforgery(httpContext, options); // Act & Assert var exception = await Assert.ThrowsAsync( @@ -39,13 +41,13 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal public async Task ChecksSSL_IsRequestValidAsync_Throws() { // Arrange - var httpContext = new DefaultHttpContext(); + var httpContext = GetHttpContext(); var options = new AntiforgeryOptions() { RequireSsl = true }; - var antiforgery = GetAntiforgery(options); + var antiforgery = GetAntiforgery(httpContext, options); // Act & Assert var exception = await Assert.ThrowsAsync( @@ -60,13 +62,13 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal public void ChecksSSL_GetAndStoreTokens_Throws() { // Arrange - var httpContext = new DefaultHttpContext(); + var httpContext = GetHttpContext(); var options = new AntiforgeryOptions() { RequireSsl = true }; - var antiforgery = GetAntiforgery(options); + var antiforgery = GetAntiforgery(httpContext, options); // Act & Assert var exception = Assert.Throws( @@ -81,13 +83,13 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal public void ChecksSSL_GetTokens_Throws() { // Arrange - var httpContext = new DefaultHttpContext(); + var httpContext = GetHttpContext(); var options = new AntiforgeryOptions() { RequireSsl = true }; - var antiforgery = GetAntiforgery(options); + var antiforgery = GetAntiforgery(httpContext, options); // Act & Assert var exception = Assert.Throws( @@ -102,13 +104,13 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal public void ChecksSSL_SetCookieTokenAndHeader_Throws() { // Arrange - var httpContext = new DefaultHttpContext(); + var httpContext = GetHttpContext(); var options = new AntiforgeryOptions() { RequireSsl = true }; - var antiforgery = GetAntiforgery(options); + var antiforgery = GetAntiforgery(httpContext, options); // Act & Assert var exception = Assert.Throws( @@ -290,12 +292,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal out message)) .Returns(false) .Verifiable(); - - var antiforgery = new DefaultAntiforgery( - new TestOptionsManager(), - context.TokenGenerator.Object, - context.TokenSerializer.Object, - context.TokenStore.Object); + var antiforgery = GetAntiforgery(context); // Act & assert var exception = await Assert.ThrowsAsync( @@ -458,6 +455,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal } private DefaultAntiforgery GetAntiforgery( + HttpContext httpContext, AntiforgeryOptions options = null, IAntiforgeryTokenGenerator tokenGenerator = null, IAntiforgeryTokenSerializer tokenSerializer = null, @@ -469,16 +467,29 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal optionsManager.Value = options; } + var loggerFactory = httpContext.RequestServices.GetRequiredService(); return new DefaultAntiforgery( antiforgeryOptionsAccessor: optionsManager, tokenGenerator: tokenGenerator, tokenSerializer: tokenSerializer, - tokenStore: tokenStore); + tokenStore: tokenStore, + loggerFactory: loggerFactory); + } + + private IServiceProvider GetServices() + { + var builder = new ServiceCollection(); + builder.AddSingleton(new LoggerFactory()); + + return builder.BuildServiceProvider(); } private HttpContext GetHttpContext() { var httpContext = new DefaultHttpContext(); + + httpContext.RequestServices = GetServices(); + httpContext.User = new ClaimsPrincipal(new ClaimsIdentity("some-auth")); return httpContext; } @@ -486,6 +497,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal private DefaultAntiforgery GetAntiforgery(AntiforgeryMockContext context) { return GetAntiforgery( + context.HttpContext, context.Options, context.TokenGenerator?.Object, context.TokenSerializer?.Object, @@ -630,4 +642,4 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal public AntiforgeryOptions Value { get; set; } = new AntiforgeryOptions(); } } -} \ No newline at end of file +} diff --git a/test/Microsoft.AspNetCore.Antiforgery.Test/project.json b/test/Microsoft.AspNetCore.Antiforgery.Test/project.json index caabfc7fd0..6b60226074 100644 --- a/test/Microsoft.AspNetCore.Antiforgery.Test/project.json +++ b/test/Microsoft.AspNetCore.Antiforgery.Test/project.json @@ -8,6 +8,7 @@ "Microsoft.AspNetCore.Http": "1.0.0-*", "Microsoft.AspNetCore.Testing": "1.0.0-*", "Microsoft.Extensions.DependencyInjection": "1.0.0-*", + "Microsoft.Extensions.Logging": "1.0.0-*", "Microsoft.Extensions.WebEncoders": "1.0.0-*", "Microsoft.NETCore.Platforms": "1.0.1-*", "xunit": "2.1.0-*" @@ -19,7 +20,7 @@ "frameworks": { "dnx451": { "frameworkAssemblies": { - "System.Threading.Tasks": "" + "System.Threading.Tasks": "" }, "dependencies": { "Moq": "4.2.1312.1622", From 73695fc4439889ecad7b6656235de7eb0feafe5f Mon Sep 17 00:00:00 2001 From: Doug Bunting Date: Fri, 5 Feb 2016 15:15:09 -0800 Subject: [PATCH 083/296] Serialize cookie token at most once - #23 part 3 - `Get[AndStore]Tokens()` would deserialize cookie token from request even if `IsRequestValidAsync()` already had - `GetAndStoreTokens()` serialized an old (never saved) cookie token once and a new one twice - refactor serialization from `DefaultAntiforgeryTokenStore` to `DefaultAntiforgery` - divide responsibilities and ease overall fix - above refactoring took `IAntiforgeryContextAccessor` responsibilities along to `DefaultAntiforgery` as well - store all tokens in `IAntiforgeryContextAccessor` to avoid repeated (de)serializations - remove `AntiforgeryTokenSetInternal` nits: - bit more parameter renaming to `httpContext` - remove argument checks in helper methods - did _not_ do a sweep through the repo; just files in this PR --- .../Internal/AntiforgeryContext.cs | 23 +- .../Internal/DefaultAntiforgery.cs | 237 ++++++--- .../Internal/DefaultAntiforgeryTokenStore.cs | 57 +- .../Internal/IAntiforgeryTokenStore.cs | 4 +- .../Internal/DefaultAntiforgeryTest.cs | 491 ++++++++++++++++-- .../DefaultAntiforgeryTokenStoreTest.cs | 149 +----- 6 files changed, 660 insertions(+), 301 deletions(-) diff --git a/src/Microsoft.AspNetCore.Antiforgery/Internal/AntiforgeryContext.cs b/src/Microsoft.AspNetCore.Antiforgery/Internal/AntiforgeryContext.cs index f1abeefe92..d3f81c694d 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/Internal/AntiforgeryContext.cs +++ b/src/Microsoft.AspNetCore.Antiforgery/Internal/AntiforgeryContext.cs @@ -4,10 +4,31 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal { /// - /// Used as a per request state. + /// Used to hold per-request state. /// public class AntiforgeryContext { + public bool HaveDeserializedCookieToken { get; set; } + public AntiforgeryToken CookieToken { get; set; } + + public bool HaveDeserializedRequestToken { get; set; } + + public AntiforgeryToken RequestToken { get; set; } + + public bool HaveGeneratedNewCookieToken { get; set; } + + // After HaveGeneratedNewCookieToken is true, remains null if CookieToken is valid. + public AntiforgeryToken NewCookieToken { get; set; } + + // After HaveGeneratedNewCookieToken is true, remains null if CookieToken is valid. + public string NewCookieTokenString { get; set; } + + public AntiforgeryToken NewRequestToken { get; set; } + + public string NewRequestTokenString { get; set; } + + // Always false if NewCookieToken is null. Never store null cookie token or re-store cookie token from request. + public bool HaveStoredNewCookieToken { get; set; } } } \ No newline at end of file diff --git a/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgery.cs b/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgery.cs index db4d29e62f..6356d3f6d7 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgery.cs +++ b/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgery.cs @@ -5,6 +5,7 @@ using System; using System.Diagnostics; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; @@ -46,10 +47,17 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal CheckSSLConfig(httpContext); - var tokenSet = GetTokensInternal(httpContext); - if (tokenSet.IsNewCookieToken) + var antiforgeryContext = GetTokensInternal(httpContext); + var tokenSet = Serialize(antiforgeryContext); + + if (!antiforgeryContext.HaveStoredNewCookieToken && antiforgeryContext.NewCookieToken != null) { - SaveCookieTokenAndHeader(httpContext, tokenSet.CookieToken); + // Serialize handles the new cookie token string. + Debug.Assert(antiforgeryContext.NewCookieTokenString != null); + + SaveCookieTokenAndHeader(httpContext, antiforgeryContext.NewCookieTokenString); + antiforgeryContext.HaveStoredNewCookieToken = true; + _logger.NewCookieToken(); } else @@ -57,7 +65,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal _logger.ReusedCookieToken(); } - return Serialize(tokenSet); + return tokenSet; } /// @@ -70,8 +78,8 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal CheckSSLConfig(httpContext); - var tokenSet = GetTokensInternal(httpContext); - return Serialize(tokenSet); + var antiforgeryContext = GetTokensInternal(httpContext); + return Serialize(antiforgeryContext); } /// @@ -90,6 +98,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal _logger.MissingCookieToken(_options.CookieName); return false; } + if (tokens.RequestToken == null) { _logger.MissingRequestToken(_options.FormFieldName, _options.HeaderName); @@ -97,8 +106,9 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal } // Extract cookie & request tokens - var deserializedCookieToken = _tokenSerializer.Deserialize(tokens.CookieToken); - var deserializedRequestToken = _tokenSerializer.Deserialize(tokens.RequestToken); + AntiforgeryToken deserializedCookieToken; + AntiforgeryToken deserializedRequestToken; + DeserializeTokens(httpContext, tokens, out deserializedCookieToken, out deserializedRequestToken); // Validate string message; @@ -165,30 +175,17 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal private void ValidateTokens(HttpContext httpContext, AntiforgeryTokenSet antiforgeryTokenSet) { - if (httpContext == null) - { - throw new ArgumentNullException(nameof(httpContext)); - } - - CheckSSLConfig(httpContext); - - if (string.IsNullOrEmpty(antiforgeryTokenSet.CookieToken)) - { - throw new ArgumentException( - Resources.Antiforgery_CookieToken_MustBeProvided_Generic, - nameof(antiforgeryTokenSet)); - } - - if (string.IsNullOrEmpty(antiforgeryTokenSet.RequestToken)) - { - throw new ArgumentException( - Resources.Antiforgery_RequestToken_MustBeProvided_Generic, - nameof(antiforgeryTokenSet)); - } + Debug.Assert(!string.IsNullOrEmpty(antiforgeryTokenSet.CookieToken)); + Debug.Assert(!string.IsNullOrEmpty(antiforgeryTokenSet.RequestToken)); // Extract cookie & request tokens - var deserializedCookieToken = _tokenSerializer.Deserialize(antiforgeryTokenSet.CookieToken); - var deserializedRequestToken = _tokenSerializer.Deserialize(antiforgeryTokenSet.RequestToken); + AntiforgeryToken deserializedCookieToken; + AntiforgeryToken deserializedRequestToken; + DeserializeTokens( + httpContext, + antiforgeryTokenSet, + out deserializedCookieToken, + out deserializedRequestToken); // Validate string message; @@ -212,38 +209,26 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal CheckSSLConfig(httpContext); - var cookieToken = GetCookieTokenDoesNotThrow(httpContext); - cookieToken = ValidateAndGenerateNewCookieToken(cookieToken); - SaveCookieTokenAndHeader(httpContext, cookieToken); + var antiforgeryContext = GetCookieTokens(httpContext); + if (!antiforgeryContext.HaveStoredNewCookieToken && antiforgeryContext.NewCookieToken != null) + { + if (antiforgeryContext.NewCookieTokenString == null) + { + antiforgeryContext.NewCookieTokenString = + _tokenSerializer.Serialize(antiforgeryContext.NewCookieToken); + } + + SaveCookieTokenAndHeader(httpContext, antiforgeryContext.NewCookieTokenString); + antiforgeryContext.HaveStoredNewCookieToken = true; + } } - // This method returns null if oldCookieToken is valid. - private AntiforgeryToken ValidateAndGenerateNewCookieToken(AntiforgeryToken cookieToken) + private void SaveCookieTokenAndHeader(HttpContext httpContext, string cookieToken) { - if (!_tokenGenerator.IsCookieTokenValid(cookieToken)) - { - // Need to make sure we're always operating with a good cookie token. - var newCookieToken = _tokenGenerator.GenerateCookieToken(); - Debug.Assert(_tokenGenerator.IsCookieTokenValid(newCookieToken)); - return newCookieToken; - } - - return null; - } - - private void SaveCookieTokenAndHeader( - HttpContext context, - AntiforgeryToken cookieToken) - { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } - if (cookieToken != null) { // Persist the new cookie if it is not null. - _tokenStore.SaveCookieToken(context, cookieToken); + _tokenStore.SaveCookieToken(httpContext, cookieToken); } if (!_options.SuppressXFrameOptionsHeader) @@ -251,7 +236,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal // Adding X-Frame-Options header to prevent ClickJacking. See // http://tools.ietf.org/html/draft-ietf-websec-x-frame-options-10 // for more information. - context.Response.Headers["X-Frame-Options"] = "SAMEORIGIN"; + httpContext.Response.Headers["X-Frame-Options"] = "SAMEORIGIN"; } } @@ -266,11 +251,64 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal } } - private AntiforgeryToken GetCookieTokenDoesNotThrow(HttpContext context) + private AntiforgeryContext GetCookieTokens(HttpContext httpContext) + { + var services = httpContext.RequestServices; + var contextAccessor = services.GetRequiredService(); + if (contextAccessor.Value == null) + { + contextAccessor.Value = new AntiforgeryContext(); + } + + var antiforgeryContext = contextAccessor.Value; + if (antiforgeryContext.HaveGeneratedNewCookieToken) + { + Debug.Assert(antiforgeryContext.HaveDeserializedCookieToken); + + // Have executed this method earlier in the context of this request. + return antiforgeryContext; + } + + AntiforgeryToken cookieToken; + if (antiforgeryContext.HaveDeserializedCookieToken) + { + cookieToken = antiforgeryContext.CookieToken; + } + else + { + cookieToken = GetCookieTokenDoesNotThrow(httpContext); + + antiforgeryContext.CookieToken = cookieToken; + antiforgeryContext.HaveDeserializedCookieToken = true; + } + + AntiforgeryToken newCookieToken; + if (_tokenGenerator.IsCookieTokenValid(cookieToken)) + { + // No need for the cookie token from the request after it has been verified. + newCookieToken = null; + } + else + { + // Need to make sure we're always operating with a good cookie token. + newCookieToken = _tokenGenerator.GenerateCookieToken(); + Debug.Assert(_tokenGenerator.IsCookieTokenValid(newCookieToken)); + } + + antiforgeryContext.HaveGeneratedNewCookieToken = true; + antiforgeryContext.NewCookieToken = newCookieToken; + + return antiforgeryContext; + } + + private AntiforgeryToken GetCookieTokenDoesNotThrow(HttpContext httpContext) { try { - return _tokenStore.GetCookieToken(context); + var serializedToken = _tokenStore.GetCookieToken(httpContext); + var token = _tokenSerializer.Deserialize(serializedToken); + + return token; } catch { @@ -279,43 +317,80 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal } } - private AntiforgeryTokenSetInternal GetTokensInternal(HttpContext httpContext) + private AntiforgeryContext GetTokensInternal(HttpContext httpContext) { - var cookieToken = GetCookieTokenDoesNotThrow(httpContext); - var newCookieToken = ValidateAndGenerateNewCookieToken(cookieToken); - if (newCookieToken != null) + var antiforgeryContext = GetCookieTokens(httpContext); + if (antiforgeryContext.NewRequestToken == null) { - cookieToken = newCookieToken; + var cookieToken = antiforgeryContext.NewCookieToken ?? antiforgeryContext.CookieToken; + antiforgeryContext.NewRequestToken = _tokenGenerator.GenerateRequestToken(httpContext, cookieToken); } - var requestToken = _tokenGenerator.GenerateRequestToken( - httpContext, - cookieToken); - return new AntiforgeryTokenSetInternal() - { - // Note : The new cookie would be null if the old cookie is valid. - CookieToken = cookieToken, - RequestToken = requestToken, - IsNewCookieToken = newCookieToken != null - }; + return antiforgeryContext; } - private AntiforgeryTokenSet Serialize(AntiforgeryTokenSetInternal tokenSet) + private AntiforgeryTokenSet Serialize(AntiforgeryContext antiforgeryContext) { + // Should only be called after new tokens have been generated. + Debug.Assert(antiforgeryContext.HaveGeneratedNewCookieToken); + Debug.Assert(antiforgeryContext.NewRequestToken != null); + + if (antiforgeryContext.NewRequestTokenString == null) + { + antiforgeryContext.NewRequestTokenString = + _tokenSerializer.Serialize(antiforgeryContext.NewRequestToken); + } + + if (antiforgeryContext.NewCookieTokenString == null && antiforgeryContext.NewCookieToken != null) + { + antiforgeryContext.NewCookieTokenString = + _tokenSerializer.Serialize(antiforgeryContext.NewCookieToken); + } + return new AntiforgeryTokenSet( - _tokenSerializer.Serialize(tokenSet.RequestToken), - _tokenSerializer.Serialize(tokenSet.CookieToken), + antiforgeryContext.NewRequestTokenString, + antiforgeryContext.NewCookieTokenString, _options.FormFieldName, _options.HeaderName); } - private class AntiforgeryTokenSetInternal + private void DeserializeTokens( + HttpContext httpContext, + AntiforgeryTokenSet antiforgeryTokenSet, + out AntiforgeryToken cookieToken, + out AntiforgeryToken requestToken) { - public AntiforgeryToken RequestToken { get; set; } + var services = httpContext.RequestServices; + var contextAccessor = services.GetRequiredService(); + if (contextAccessor.Value == null) + { + contextAccessor.Value = new AntiforgeryContext(); + } - public AntiforgeryToken CookieToken { get; set; } + var antiforgeryContext = contextAccessor.Value; + if (antiforgeryContext.HaveDeserializedCookieToken) + { + cookieToken = antiforgeryContext.CookieToken; + } + else + { + cookieToken = _tokenSerializer.Deserialize(antiforgeryTokenSet.CookieToken); - public bool IsNewCookieToken { get; set; } + antiforgeryContext.CookieToken = cookieToken; + antiforgeryContext.HaveDeserializedCookieToken = true; + } + + if (antiforgeryContext.HaveDeserializedRequestToken) + { + requestToken = antiforgeryContext.RequestToken; + } + else + { + requestToken = _tokenSerializer.Deserialize(antiforgeryTokenSet.RequestToken); + + antiforgeryContext.RequestToken = requestToken; + antiforgeryContext.HaveDeserializedRequestToken = true; + } } } } \ No newline at end of file diff --git a/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgeryTokenStore.cs b/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgeryTokenStore.cs index 5b0f41426a..cd20eea956 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgeryTokenStore.cs +++ b/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgeryTokenStore.cs @@ -5,7 +5,6 @@ using System; using System.Diagnostics; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; -using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Options; using Microsoft.Extensions.Primitives; @@ -14,39 +13,20 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal public class DefaultAntiforgeryTokenStore : IAntiforgeryTokenStore { private readonly AntiforgeryOptions _options; - private readonly IAntiforgeryTokenSerializer _tokenSerializer; - public DefaultAntiforgeryTokenStore( - IOptions optionsAccessor, - IAntiforgeryTokenSerializer tokenSerializer) + public DefaultAntiforgeryTokenStore(IOptions optionsAccessor) { if (optionsAccessor == null) { throw new ArgumentNullException(nameof(optionsAccessor)); } - if (tokenSerializer == null) - { - throw new ArgumentNullException(nameof(tokenSerializer)); - } - _options = optionsAccessor.Value; - _tokenSerializer = tokenSerializer; } - public AntiforgeryToken GetCookieToken(HttpContext httpContext) + public string GetCookieToken(HttpContext httpContext) { - if (httpContext == null) - { - throw new ArgumentNullException(nameof(httpContext)); - } - - var services = httpContext.RequestServices; - var contextAccessor = services.GetRequiredService(); - if (contextAccessor.Value != null) - { - return contextAccessor.Value.CookieToken; - } + Debug.Assert(httpContext != null); var requestCookie = httpContext.Request.Cookies[_options.CookieName]; if (string.IsNullOrEmpty(requestCookie)) @@ -55,15 +35,12 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal return null; } - return _tokenSerializer.Deserialize(requestCookie); + return requestCookie; } public async Task GetRequestTokensAsync(HttpContext httpContext) { - if (httpContext == null) - { - throw new ArgumentNullException(nameof(httpContext)); - } + Debug.Assert(httpContext != null); var cookieToken = httpContext.Request.Cookies[_options.CookieName]; @@ -85,27 +62,11 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal return new AntiforgeryTokenSet(requestToken, cookieToken, _options.FormFieldName, _options.HeaderName); } - public void SaveCookieToken(HttpContext httpContext, AntiforgeryToken token) + public void SaveCookieToken(HttpContext httpContext, string token) { - if (httpContext == null) - { - throw new ArgumentNullException(nameof(httpContext)); - } + Debug.Assert(httpContext != null); + Debug.Assert(token != null); - if (token == null) - { - throw new ArgumentNullException(nameof(token)); - } - - // Add the cookie to the request based context. - // This is useful if the cookie needs to be reloaded in the context of the same request. - - var services = httpContext.RequestServices; - var contextAccessor = services.GetRequiredService(); - Debug.Assert(contextAccessor.Value == null, "AntiforgeryContext should be set only once per request."); - contextAccessor.Value = new AntiforgeryContext() { CookieToken = token }; - - var serializedToken = _tokenSerializer.Serialize(token); var options = new CookieOptions() { HttpOnly = true }; // Note: don't use "newCookie.Secure = _options.RequireSSL;" since the default @@ -115,7 +76,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal options.Secure = true; } - httpContext.Response.Cookies.Append(_options.CookieName, serializedToken, options); + httpContext.Response.Cookies.Append(_options.CookieName, token, options); } } } \ No newline at end of file diff --git a/src/Microsoft.AspNetCore.Antiforgery/Internal/IAntiforgeryTokenStore.cs b/src/Microsoft.AspNetCore.Antiforgery/Internal/IAntiforgeryTokenStore.cs index 967887a44f..1b4aa8ec05 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/Internal/IAntiforgeryTokenStore.cs +++ b/src/Microsoft.AspNetCore.Antiforgery/Internal/IAntiforgeryTokenStore.cs @@ -8,7 +8,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal { public interface IAntiforgeryTokenStore { - AntiforgeryToken GetCookieToken(HttpContext httpContext); + string GetCookieToken(HttpContext httpContext); /// /// Gets the cookie and request tokens from the request. @@ -17,6 +17,6 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal /// The . Task GetRequestTokensAsync(HttpContext httpContext); - void SaveCookieToken(HttpContext httpContext, AntiforgeryToken token); + void SaveCookieToken(HttpContext httpContext, string token); } } \ No newline at end of file diff --git a/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTest.cs b/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTest.cs index 8969b05c31..d1571fc59b 100644 --- a/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTest.cs +++ b/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTest.cs @@ -125,19 +125,30 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal public void GetTokens_ExistingInvalidCookieToken_GeneratesANewCookieTokenAndANewFormToken() { // Arrange + var contextAccessor = new DefaultAntiforgeryContextAccessor(); // Generate a new cookie. var context = CreateMockContext( new AntiforgeryOptions(), useOldCookie: false, - isOldCookieValid: false); + isOldCookieValid: false, + contextAccessor: contextAccessor); var antiforgery = GetAntiforgery(context); // Act var tokenset = antiforgery.GetTokens(context.HttpContext); // Assert - Assert.Equal("serialized-new-cookie-token", tokenset.CookieToken); - Assert.Equal("serialized-form-token", tokenset.RequestToken); + Assert.Equal(context.TestTokenSet.NewCookieTokenString, tokenset.CookieToken); + Assert.Equal(context.TestTokenSet.FormTokenString, tokenset.RequestToken); + + Assert.NotNull(contextAccessor.Value); + Assert.True(contextAccessor.Value.HaveDeserializedCookieToken); + Assert.Equal(context.TestTokenSet.OldCookieToken, contextAccessor.Value.CookieToken); + Assert.True(contextAccessor.Value.HaveGeneratedNewCookieToken); + Assert.Equal(context.TestTokenSet.NewCookieToken, contextAccessor.Value.NewCookieToken); + Assert.Equal(context.TestTokenSet.NewCookieTokenString, contextAccessor.Value.NewCookieTokenString); + Assert.Equal(context.TestTokenSet.RequestToken, contextAccessor.Value.NewRequestToken); + Assert.Equal(context.TestTokenSet.FormTokenString, contextAccessor.Value.NewRequestTokenString); } [Fact] @@ -150,10 +161,13 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal useOldCookie: false, isOldCookieValid: false); - // This will cause the cookieToken to be null. + // Exception will cause the cookieToken to be null. context.TokenSerializer - .Setup(o => o.Deserialize("serialized-old-cookie-token")) + .Setup(o => o.Deserialize(context.TestTokenSet.OldCookieTokenString)) .Throws(new Exception("should be swallowed")); + context.TokenGenerator + .Setup(o => o.IsCookieTokenValid(null)) + .Returns(false); var antiforgery = GetAntiforgery(context); @@ -161,36 +175,88 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal var tokenset = antiforgery.GetTokens(context.HttpContext); // Assert - Assert.Equal("serialized-new-cookie-token", tokenset.CookieToken); - Assert.Equal("serialized-form-token", tokenset.RequestToken); + Assert.Equal(context.TestTokenSet.NewCookieTokenString, tokenset.CookieToken); + Assert.Equal(context.TestTokenSet.FormTokenString, tokenset.RequestToken); } [Fact] public void GetTokens_ExistingValidCookieToken_GeneratesANewFormToken() { // Arrange + var contextAccessor = new DefaultAntiforgeryContextAccessor(); var context = CreateMockContext( new AntiforgeryOptions(), useOldCookie: true, - isOldCookieValid: true); + isOldCookieValid: true, + contextAccessor: contextAccessor); var antiforgery = GetAntiforgery(context); // Act var tokenset = antiforgery.GetTokens(context.HttpContext); // Assert - Assert.Equal("serialized-old-cookie-token", tokenset.CookieToken); - Assert.Equal("serialized-form-token", tokenset.RequestToken); + Assert.Null(tokenset.CookieToken); + Assert.Equal(context.TestTokenSet.FormTokenString, tokenset.RequestToken); + + Assert.NotNull(contextAccessor.Value); + Assert.True(contextAccessor.Value.HaveDeserializedCookieToken); + Assert.Equal(context.TestTokenSet.OldCookieToken, contextAccessor.Value.CookieToken); + Assert.True(contextAccessor.Value.HaveGeneratedNewCookieToken); + Assert.Null(contextAccessor.Value.NewCookieToken); + Assert.Equal(context.TestTokenSet.RequestToken, contextAccessor.Value.NewRequestToken); + Assert.Equal(context.TestTokenSet.FormTokenString, contextAccessor.Value.NewRequestTokenString); + } + + [Fact] + public void GetTokens_DoesNotSerializeTwice() + { + // Arrange + var contextAccessor = new DefaultAntiforgeryContextAccessor + { + Value = new AntiforgeryContext + { + HaveDeserializedCookieToken = true, + HaveGeneratedNewCookieToken = true, + NewRequestToken = new AntiforgeryToken(), + NewRequestTokenString = "serialized-form-token-from-context", + }, + }; + var context = CreateMockContext( + new AntiforgeryOptions(), + useOldCookie: true, + isOldCookieValid: true, + contextAccessor: contextAccessor); + + var antiforgery = GetAntiforgery(context); + + // Act + var tokenset = antiforgery.GetTokens(context.HttpContext); + + // Assert + Assert.Null(tokenset.CookieToken); + Assert.Equal("serialized-form-token-from-context", tokenset.RequestToken); + + Assert.Null(contextAccessor.Value.NewCookieToken); + + // Token serializer not used. + context.TokenSerializer.Verify( + o => o.Deserialize(It.IsAny()), + Times.Never); + context.TokenSerializer.Verify( + o => o.Serialize(It.IsAny()), + Times.Never); } [Fact] public void GetAndStoreTokens_ExistingValidCookieToken_NotOverriden() { // Arrange + var contextAccessor = new DefaultAntiforgeryContextAccessor(); var context = CreateMockContext( new AntiforgeryOptions(), useOldCookie: true, - isOldCookieValid: true); + isOldCookieValid: true, + contextAccessor: contextAccessor); var antiforgery = GetAntiforgery(context); // Act @@ -199,20 +265,31 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal // Assert // We shouldn't have saved the cookie because it already existed. context.TokenStore.Verify( - t => t.SaveCookieToken(It.IsAny(), It.IsAny()), Times.Never); + t => t.SaveCookieToken(It.IsAny(), It.IsAny()), + Times.Never); - Assert.Equal("serialized-old-cookie-token", tokenSet.CookieToken); - Assert.Equal("serialized-form-token", tokenSet.RequestToken); + Assert.Null(tokenSet.CookieToken); + Assert.Equal(context.TestTokenSet.FormTokenString, tokenSet.RequestToken); + + Assert.NotNull(contextAccessor.Value); + Assert.True(contextAccessor.Value.HaveDeserializedCookieToken); + Assert.Equal(context.TestTokenSet.OldCookieToken, contextAccessor.Value.CookieToken); + Assert.True(contextAccessor.Value.HaveGeneratedNewCookieToken); + Assert.Null(contextAccessor.Value.NewCookieToken); + Assert.Equal(context.TestTokenSet.RequestToken, contextAccessor.Value.NewRequestToken); + Assert.Equal(context.TestTokenSet.FormTokenString, contextAccessor.Value.NewRequestTokenString); } [Fact] public void GetAndStoreTokens_NoExistingCookieToken_Saved() { // Arrange + var contextAccessor = new DefaultAntiforgeryContextAccessor(); var context = CreateMockContext( new AntiforgeryOptions(), useOldCookie: false, - isOldCookieValid: false); + isOldCookieValid: false, + contextAccessor: contextAccessor); var antiforgery = GetAntiforgery(context); // Act @@ -220,17 +297,125 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal // Assert context.TokenStore.Verify( - t => t.SaveCookieToken(It.IsAny(), It.IsAny()), Times.Once); + t => t.SaveCookieToken(It.IsAny(), context.TestTokenSet.NewCookieTokenString), + Times.Once); - Assert.Equal("serialized-new-cookie-token", tokenSet.CookieToken); - Assert.Equal("serialized-form-token", tokenSet.RequestToken); + Assert.Equal(context.TestTokenSet.NewCookieTokenString, tokenSet.CookieToken); + Assert.Equal(context.TestTokenSet.FormTokenString, tokenSet.RequestToken); + + Assert.NotNull(contextAccessor.Value); + Assert.True(contextAccessor.Value.HaveDeserializedCookieToken); + Assert.Equal(context.TestTokenSet.OldCookieToken, contextAccessor.Value.CookieToken); + Assert.True(contextAccessor.Value.HaveGeneratedNewCookieToken); + Assert.Equal(context.TestTokenSet.NewCookieToken, contextAccessor.Value.NewCookieToken); + Assert.Equal(context.TestTokenSet.NewCookieTokenString, contextAccessor.Value.NewCookieTokenString); + Assert.Equal(context.TestTokenSet.RequestToken, contextAccessor.Value.NewRequestToken); + Assert.Equal(context.TestTokenSet.FormTokenString, contextAccessor.Value.NewRequestTokenString); + Assert.True(contextAccessor.Value.HaveStoredNewCookieToken); + } + + [Fact] + public void GetAndStoreTokens_DoesNotSerializeTwice() + { + // Arrange + var contextAccessor = new DefaultAntiforgeryContextAccessor + { + Value = new AntiforgeryContext + { + HaveDeserializedCookieToken = true, + HaveGeneratedNewCookieToken = true, + NewCookieToken = new AntiforgeryToken(), + NewCookieTokenString = "serialized-cookie-token-from-context", + NewRequestToken = new AntiforgeryToken(), + NewRequestTokenString = "serialized-form-token-from-context", + }, + }; + var context = CreateMockContext( + new AntiforgeryOptions(), + useOldCookie: true, + isOldCookieValid: true, + contextAccessor: contextAccessor); + var antiforgery = GetAntiforgery(context); + + context.TokenStore + .Setup(t => t.SaveCookieToken(context.HttpContext, "serialized-cookie-token-from-context")) + .Verifiable(); + + // Act + var tokenset = antiforgery.GetAndStoreTokens(context.HttpContext); + + // Assert + // Token store used once, with expected arguments. + // Passed context's cookie token though request's cookie token was valid. + context.TokenStore.Verify( + t => t.SaveCookieToken(context.HttpContext, "serialized-cookie-token-from-context"), + Times.Once); + + // Token serializer not used. + context.TokenSerializer.Verify( + o => o.Deserialize(It.IsAny()), + Times.Never); + context.TokenSerializer.Verify( + o => o.Serialize(It.IsAny()), + Times.Never); + + Assert.Equal("serialized-cookie-token-from-context", tokenset.CookieToken); + Assert.Equal("serialized-form-token-from-context", tokenset.RequestToken); + + Assert.True(contextAccessor.Value.HaveStoredNewCookieToken); + } + + [Fact] + public void GetAndStoreTokens_DoesNotStoreTwice() + { + // Arrange + var contextAccessor = new DefaultAntiforgeryContextAccessor + { + Value = new AntiforgeryContext + { + HaveDeserializedCookieToken = true, + HaveGeneratedNewCookieToken = true, + HaveStoredNewCookieToken = true, + NewCookieToken = new AntiforgeryToken(), + NewCookieTokenString = "serialized-cookie-token-from-context", + NewRequestToken = new AntiforgeryToken(), + NewRequestTokenString = "serialized-form-token-from-context", + }, + }; + var context = CreateMockContext( + new AntiforgeryOptions(), + useOldCookie: true, + isOldCookieValid: true, + contextAccessor: contextAccessor); + var antiforgery = GetAntiforgery(context); + + // Act + var tokenset = antiforgery.GetAndStoreTokens(context.HttpContext); + + // Assert + // Token store not used. + context.TokenStore.Verify( + t => t.SaveCookieToken(It.IsAny(), It.IsAny()), + Times.Never); + + // Token serializer not used. + context.TokenSerializer.Verify( + o => o.Deserialize(It.IsAny()), + Times.Never); + context.TokenSerializer.Verify( + o => o.Serialize(It.IsAny()), + Times.Never); + + Assert.Equal("serialized-cookie-token-from-context", tokenset.CookieToken); + Assert.Equal("serialized-form-token-from-context", tokenset.RequestToken); } [Fact] public async Task IsRequestValidAsync_FromStore_Failure() { // Arrange - var context = CreateMockContext(new AntiforgeryOptions()); + var contextAccessor = new DefaultAntiforgeryContextAccessor(); + var context = CreateMockContext(new AntiforgeryOptions(), contextAccessor: contextAccessor); string message; context.TokenGenerator @@ -249,13 +434,21 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal // Assert Assert.False(result); context.TokenGenerator.Verify(); + + // Failed _after_ updating the AntiforgeryContext. + Assert.NotNull(contextAccessor.Value); + Assert.True(contextAccessor.Value.HaveDeserializedCookieToken); + Assert.Equal(context.TestTokenSet.OldCookieToken, contextAccessor.Value.CookieToken); + Assert.True(contextAccessor.Value.HaveDeserializedRequestToken); + Assert.Equal(context.TestTokenSet.RequestToken, contextAccessor.Value.RequestToken); } [Fact] public async Task IsRequestValidAsync_FromStore_Success() { // Arrange - var context = CreateMockContext(new AntiforgeryOptions()); + var contextAccessor = new DefaultAntiforgeryContextAccessor(); + var context = CreateMockContext(new AntiforgeryOptions(), contextAccessor: contextAccessor); string message; context.TokenGenerator @@ -275,13 +468,64 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal // Assert Assert.True(result); context.TokenGenerator.Verify(); + + Assert.NotNull(contextAccessor.Value); + Assert.True(contextAccessor.Value.HaveDeserializedCookieToken); + Assert.Equal(context.TestTokenSet.OldCookieToken, contextAccessor.Value.CookieToken); + Assert.True(contextAccessor.Value.HaveDeserializedRequestToken); + Assert.Equal(context.TestTokenSet.RequestToken, contextAccessor.Value.RequestToken); + } + + [Fact] + public async Task IsRequestValidAsync_DoesNotDeserializeTwice() + { + // Arrange + var contextAccessor = new DefaultAntiforgeryContextAccessor + { + Value = new AntiforgeryContext + { + HaveDeserializedCookieToken = true, + CookieToken = new AntiforgeryToken(), + HaveDeserializedRequestToken = true, + RequestToken = new AntiforgeryToken(), + }, + }; + var context = CreateMockContext(new AntiforgeryOptions(), contextAccessor: contextAccessor); + + string message; + context.TokenGenerator + .Setup(o => o.TryValidateTokenSet( + context.HttpContext, + contextAccessor.Value.CookieToken, + contextAccessor.Value.RequestToken, + out message)) + .Returns(true) + .Verifiable(); + + var antiforgery = GetAntiforgery(context); + + // Act + var result = await antiforgery.IsRequestValidAsync(context.HttpContext); + + // Assert + Assert.True(result); + context.TokenGenerator.Verify(); + + // Token serializer not used. + context.TokenSerializer.Verify( + o => o.Deserialize(It.IsAny()), + Times.Never); + context.TokenSerializer.Verify( + o => o.Serialize(It.IsAny()), + Times.Never); } [Fact] public async Task ValidateRequestAsync_FromStore_Failure() { // Arrange - var context = CreateMockContext(new AntiforgeryOptions()); + var contextAccessor = new DefaultAntiforgeryContextAccessor(); + var context = CreateMockContext(new AntiforgeryOptions(), contextAccessor: contextAccessor); var message = "my-message"; context.TokenGenerator @@ -299,13 +543,21 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal () => antiforgery.ValidateRequestAsync(context.HttpContext)); Assert.Equal("my-message", exception.Message); context.TokenGenerator.Verify(); + + // Failed _after_ updating the AntiforgeryContext. + Assert.NotNull(contextAccessor.Value); + Assert.True(contextAccessor.Value.HaveDeserializedCookieToken); + Assert.Equal(context.TestTokenSet.OldCookieToken, contextAccessor.Value.CookieToken); + Assert.True(contextAccessor.Value.HaveDeserializedRequestToken); + Assert.Equal(context.TestTokenSet.RequestToken, contextAccessor.Value.RequestToken); } [Fact] public async Task ValidateRequestAsync_FromStore_Success() { // Arrange - var context = CreateMockContext(new AntiforgeryOptions()); + var contextAccessor = new DefaultAntiforgeryContextAccessor(); + var context = CreateMockContext(new AntiforgeryOptions(), contextAccessor: contextAccessor); string message; context.TokenGenerator @@ -324,6 +576,12 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal // Assert context.TokenGenerator.Verify(); + + Assert.NotNull(contextAccessor.Value); + Assert.True(contextAccessor.Value.HaveDeserializedCookieToken); + Assert.Equal(context.TestTokenSet.OldCookieToken, contextAccessor.Value.CookieToken); + Assert.True(contextAccessor.Value.HaveDeserializedRequestToken); + Assert.Equal(context.TestTokenSet.RequestToken, contextAccessor.Value.RequestToken); } [Fact] @@ -429,6 +687,49 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal exception.Message); } + [Fact] + public async Task ValidateRequestAsync_DoesNotDeserializeTwice() + { + // Arrange + var contextAccessor = new DefaultAntiforgeryContextAccessor + { + Value = new AntiforgeryContext + { + HaveDeserializedCookieToken = true, + CookieToken = new AntiforgeryToken(), + HaveDeserializedRequestToken = true, + RequestToken = new AntiforgeryToken(), + }, + }; + var context = CreateMockContext(new AntiforgeryOptions(), contextAccessor: contextAccessor); + + string message; + context.TokenGenerator + .Setup(o => o.TryValidateTokenSet( + context.HttpContext, + contextAccessor.Value.CookieToken, + contextAccessor.Value.RequestToken, + out message)) + .Returns(true) + .Verifiable(); + + var antiforgery = GetAntiforgery(context); + + // Act + await antiforgery.ValidateRequestAsync(context.HttpContext); + + // Assert (does not throw) + context.TokenGenerator.Verify(); + + // Token serializer not used. + context.TokenSerializer.Verify( + o => o.Deserialize(It.IsAny()), + Times.Never); + context.TokenSerializer.Verify( + o => o.Serialize(It.IsAny()), + Times.Never); + } + [Theory] [InlineData(false, "SAMEORIGIN")] [InlineData(true, null)] @@ -441,9 +742,14 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal { SuppressXFrameOptionsHeader = suppressXFrameOptions }; + var contextAccessor = new DefaultAntiforgeryContextAccessor(); // Generate a new cookie. - var context = CreateMockContext(options, useOldCookie: false, isOldCookieValid: false); + var context = CreateMockContext( + options, + useOldCookie: false, + isOldCookieValid: false, + contextAccessor: contextAccessor); var antiforgery = GetAntiforgery(context); // Act @@ -452,6 +758,102 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal // Assert var xFrameOptions = context.HttpContext.Response.Headers["X-Frame-Options"]; Assert.Equal(expectedHeaderValue, xFrameOptions); + + Assert.NotNull(contextAccessor.Value); + Assert.True(contextAccessor.Value.HaveDeserializedCookieToken); + Assert.Equal(context.TestTokenSet.OldCookieToken, contextAccessor.Value.CookieToken); + Assert.True(contextAccessor.Value.HaveGeneratedNewCookieToken); + Assert.Equal(context.TestTokenSet.NewCookieToken, contextAccessor.Value.NewCookieToken); + Assert.Equal(context.TestTokenSet.NewCookieTokenString, contextAccessor.Value.NewCookieTokenString); + Assert.True(contextAccessor.Value.HaveStoredNewCookieToken); + } + + [Fact] + public void SetCookieTokenAndHeader_DoesNotDeserializeTwice() + { + // Arrange + var contextAccessor = new DefaultAntiforgeryContextAccessor + { + Value = new AntiforgeryContext + { + HaveDeserializedCookieToken = true, + HaveGeneratedNewCookieToken = true, + NewCookieToken = new AntiforgeryToken(), + NewCookieTokenString = "serialized-cookie-token-from-context", + NewRequestToken = new AntiforgeryToken(), + NewRequestTokenString = "serialized-form-token-from-context", + }, + }; + var context = CreateMockContext( + new AntiforgeryOptions(), + useOldCookie: true, + isOldCookieValid: true, + contextAccessor: contextAccessor); + var antiforgery = GetAntiforgery(context); + + context.TokenStore + .Setup(t => t.SaveCookieToken(context.HttpContext, "serialized-cookie-token-from-context")) + .Verifiable(); + + // Act + antiforgery.SetCookieTokenAndHeader(context.HttpContext); + + // Assert + // Token store used once, with expected arguments. + // Passed context's cookie token though request's cookie token was valid. + context.TokenStore.Verify( + t => t.SaveCookieToken(context.HttpContext, "serialized-cookie-token-from-context"), + Times.Once); + + // Token serializer not used. + context.TokenSerializer.Verify( + o => o.Deserialize(It.IsAny()), + Times.Never); + context.TokenSerializer.Verify( + o => o.Serialize(It.IsAny()), + Times.Never); + } + + [Fact] + public void SetCookieTokenAndHeader_DoesNotStoreTwice() + { + // Arrange + var contextAccessor = new DefaultAntiforgeryContextAccessor + { + Value = new AntiforgeryContext + { + HaveDeserializedCookieToken = true, + HaveGeneratedNewCookieToken = true, + HaveStoredNewCookieToken = true, + NewCookieToken = new AntiforgeryToken(), + NewCookieTokenString = "serialized-cookie-token-from-context", + NewRequestToken = new AntiforgeryToken(), + NewRequestTokenString = "serialized-form-token-from-context", + }, + }; + var context = CreateMockContext( + new AntiforgeryOptions(), + useOldCookie: true, + isOldCookieValid: true, + contextAccessor: contextAccessor); + var antiforgery = GetAntiforgery(context); + + // Act + antiforgery.SetCookieTokenAndHeader(context.HttpContext); + + // Assert + // Token serializer not used. + context.TokenSerializer.Verify( + o => o.Deserialize(It.IsAny()), + Times.Never); + context.TokenSerializer.Verify( + o => o.Serialize(It.IsAny()), + Times.Never); + + // Token store not used. + context.TokenStore.Verify( + t => t.SaveCookieToken(It.IsAny(), It.IsAny()), + Times.Never); } private DefaultAntiforgery GetAntiforgery( @@ -484,13 +886,20 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal return builder.BuildServiceProvider(); } - private HttpContext GetHttpContext() + private HttpContext GetHttpContext(IAntiforgeryContextAccessor contextAccessor) { var httpContext = new DefaultHttpContext(); httpContext.RequestServices = GetServices(); httpContext.User = new ClaimsPrincipal(new ClaimsIdentity("some-auth")); + + contextAccessor = contextAccessor ?? new DefaultAntiforgeryContextAccessor(); + + var serviceCollection = new ServiceCollection(); + serviceCollection.AddSingleton(contextAccessor); + httpContext.RequestServices = serviceCollection.BuildServiceProvider(); + return httpContext; } @@ -509,24 +918,27 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal TestTokenSet testTokenSet, bool saveNewCookie = true) { - var oldCookieToken = testTokenSet.OldCookieToken; - var formToken = testTokenSet.RequestToken; + var oldCookieToken = testTokenSet.OldCookieTokenString; + var formToken = testTokenSet.FormTokenString; var mockTokenStore = new Mock(MockBehavior.Strict); - mockTokenStore.Setup(o => o.GetCookieToken(context)) - .Returns(oldCookieToken); + mockTokenStore + .Setup(o => o.GetCookieToken(context)) + .Returns(oldCookieToken); - mockTokenStore.Setup(o => o.GetRequestTokensAsync(context)) - .Returns(() => Task.FromResult(new AntiforgeryTokenSet( - testTokenSet.FormTokenString, - testTokenSet.OldCookieTokenString, - "form", - "header"))); + mockTokenStore + .Setup(o => o.GetRequestTokensAsync(context)) + .Returns(() => Task.FromResult(new AntiforgeryTokenSet( + formToken, + oldCookieToken, + "form", + "header"))); if (saveNewCookie) { - var newCookieToken = testTokenSet.NewCookieToken; - mockTokenStore.Setup(o => o.SaveCookieToken(context, newCookieToken)) - .Verifiable(); + var newCookieToken = testTokenSet.NewCookieTokenString; + mockTokenStore + .Setup(o => o.SaveCookieToken(context, newCookieToken)) + .Verifiable(); } return mockTokenStore; @@ -554,10 +966,11 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal private AntiforgeryMockContext CreateMockContext( AntiforgeryOptions options, bool useOldCookie = false, - bool isOldCookieValid = true) + bool isOldCookieValid = true, + IAntiforgeryContextAccessor contextAccessor = null) { // Arrange - var httpContext = GetHttpContext(); + var httpContext = GetHttpContext(contextAccessor); var testTokenSet = GetTokenSet(); var mockSerializer = GetTokenSerializer(testTokenSet); diff --git a/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTokenStoreTest.cs b/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTokenStoreTest.cs index 16ad4857a1..2b1f6152a3 100644 --- a/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTokenStoreTest.cs +++ b/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTokenStoreTest.cs @@ -4,11 +4,8 @@ using System; using System.Collections.Generic; using System.Threading.Tasks; -using Microsoft.AspNetCore.DataProtection; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.Internal; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.ObjectPool; using Microsoft.Extensions.Primitives; using Moq; using Xunit; @@ -17,8 +14,6 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal { public class DefaultAntiforgeryTokenStoreTest { - private static readonly ObjectPool _pool = - new DefaultObjectPoolProvider().Create(new AntiforgerySerializationContextPooledObjectPolicy()); private readonly string _cookieName = "cookie-name"; [Fact] @@ -31,9 +26,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal CookieName = _cookieName }; - var tokenStore = new DefaultAntiforgeryTokenStore( - optionsAccessor: new TestOptionsManager(options), - tokenSerializer: Mock.Of()); + var tokenStore = new DefaultAntiforgeryTokenStore(new TestOptionsManager(options)); // Act var token = tokenStore.GetCookieToken(httpContext); @@ -42,33 +35,6 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal Assert.Null(token); } - [Fact] - public void GetCookieToken_CookieIsMissingInRequest_LooksUpCookieInAntiforgeryContext() - { - // Arrange - var contextAccessor = new DefaultAntiforgeryContextAccessor(); - var httpContext = GetHttpContext(_cookieName, string.Empty, contextAccessor); - - // add a cookie explicitly. - var cookie = new AntiforgeryToken(); - contextAccessor.Value = new AntiforgeryContext() { CookieToken = cookie }; - - var options = new AntiforgeryOptions - { - CookieName = _cookieName - }; - - var tokenStore = new DefaultAntiforgeryTokenStore( - optionsAccessor: new TestOptionsManager(options), - tokenSerializer: Mock.Of()); - - // Act - var token = tokenStore.GetCookieToken(httpContext); - - // Assert - Assert.Equal(cookie, token); - } - [Fact] public void GetCookieToken_CookieIsEmpty_ReturnsNull() { @@ -79,9 +45,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal CookieName = _cookieName }; - var tokenStore = new DefaultAntiforgeryTokenStore( - optionsAccessor: new TestOptionsManager(options), - tokenSerializer: Mock.Of()); + var tokenStore = new DefaultAntiforgeryTokenStore(new TestOptionsManager(options)); // Act var token = tokenStore.GetCookieToken(httpContext); @@ -91,57 +55,24 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal } [Fact] - public void GetCookieToken_CookieIsInvalid_PropagatesException() + public void GetCookieToken_CookieIsNotEmpty_ReturnsToken() { // Arrange - var httpContext = GetHttpContext(_cookieName, "invalid-value"); - - var expectedException = new AntiforgeryValidationException("some exception"); - var mockSerializer = new Mock(); - mockSerializer - .Setup(o => o.Deserialize("invalid-value")) - .Throws(expectedException); + var expectedToken = "valid-value"; + var httpContext = GetHttpContext(_cookieName, expectedToken); var options = new AntiforgeryOptions() { CookieName = _cookieName }; - var tokenStore = new DefaultAntiforgeryTokenStore( - optionsAccessor: new TestOptionsManager(options), - tokenSerializer: mockSerializer.Object); - - // Act & assert - var ex = Assert.Throws(() => tokenStore.GetCookieToken(httpContext)); - Assert.Same(expectedException, ex); - } - - [Fact] - public void GetCookieToken_CookieIsValid_ReturnsToken() - { - // Arrange - var expectedToken = new AntiforgeryToken(); - var httpContext = GetHttpContext(_cookieName, "valid-value"); - - var mockSerializer = new Mock(); - mockSerializer - .Setup(o => o.Deserialize("valid-value")) - .Returns(expectedToken); - - var options = new AntiforgeryOptions() - { - CookieName = _cookieName - }; - - var tokenStore = new DefaultAntiforgeryTokenStore( - optionsAccessor: new TestOptionsManager(options), - tokenSerializer: mockSerializer.Object); + var tokenStore = new DefaultAntiforgeryTokenStore(new TestOptionsManager(options)); // Act var token = tokenStore.GetCookieToken(httpContext); // Assert - Assert.Same(expectedToken, token); + Assert.Equal(expectedToken, token); } [Fact] @@ -157,9 +88,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal FormFieldName = "form-field-name", }; - var tokenStore = new DefaultAntiforgeryTokenStore( - optionsAccessor: new TestOptionsManager(options), - tokenSerializer: Mock.Of()); + var tokenStore = new DefaultAntiforgeryTokenStore(new TestOptionsManager(options)); // Act var tokenSet = await tokenStore.GetRequestTokensAsync(httpContext); @@ -186,9 +115,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal HeaderName = null, }; - var tokenStore = new DefaultAntiforgeryTokenStore( - optionsAccessor: new TestOptionsManager(options), - tokenSerializer: new DefaultAntiforgeryTokenSerializer(new EphemeralDataProtectionProvider(), _pool)); + var tokenStore = new DefaultAntiforgeryTokenStore(new TestOptionsManager(options)); // Act var tokenSet = await tokenStore.GetRequestTokensAsync(httpContext); @@ -214,9 +141,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal HeaderName = "header-name", }; - var tokenStore = new DefaultAntiforgeryTokenStore( - optionsAccessor: new TestOptionsManager(options), - tokenSerializer: new DefaultAntiforgeryTokenSerializer(new EphemeralDataProtectionProvider(), _pool)); + var tokenStore = new DefaultAntiforgeryTokenStore(new TestOptionsManager(options)); // Act var tokens = await tokenStore.GetRequestTokensAsync(httpContext); @@ -244,9 +169,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal HeaderName = "header-name", }; - var tokenStore = new DefaultAntiforgeryTokenStore( - optionsAccessor: new TestOptionsManager(options), - tokenSerializer: new DefaultAntiforgeryTokenSerializer(new EphemeralDataProtectionProvider(), _pool)); + var tokenStore = new DefaultAntiforgeryTokenStore(new TestOptionsManager(options)); // Act var tokens = await tokenStore.GetRequestTokensAsync(httpContext); @@ -273,9 +196,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal HeaderName = "header-name", }; - var tokenStore = new DefaultAntiforgeryTokenStore( - optionsAccessor: new TestOptionsManager(options), - tokenSerializer: new DefaultAntiforgeryTokenSerializer(new EphemeralDataProtectionProvider(), _pool)); + var tokenStore = new DefaultAntiforgeryTokenStore(new TestOptionsManager(options)); // Act var tokenSet = await tokenStore.GetRequestTokensAsync(httpContext); @@ -300,9 +221,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal HeaderName = "header-name", }; - var tokenStore = new DefaultAntiforgeryTokenStore( - optionsAccessor: new TestOptionsManager(options), - tokenSerializer: Mock.Of()); + var tokenStore = new DefaultAntiforgeryTokenStore(new TestOptionsManager(options)); // Act var tokenSet = await tokenStore.GetRequestTokensAsync(httpContext); @@ -331,9 +250,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal HeaderName = "header-name", }; - var tokenStore = new DefaultAntiforgeryTokenStore( - optionsAccessor: new TestOptionsManager(options), - tokenSerializer: Mock.Of()); + var tokenStore = new DefaultAntiforgeryTokenStore(new TestOptionsManager(options)); // Act var tokens = await tokenStore.GetRequestTokensAsync(httpContext); @@ -349,7 +266,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal public void SaveCookieToken(bool requireSsl, bool? expectedCookieSecureFlag) { // Arrange - var token = new AntiforgeryToken(); + var token = "serialized-value"; bool defaultCookieSecureValue = expectedCookieSecureFlag ?? false; // pulled from config; set by ctor var cookies = new MockResponseCookieCollection(); @@ -358,32 +275,19 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal .Setup(o => o.Response.Cookies) .Returns(cookies); - var contextAccessor = new DefaultAntiforgeryContextAccessor(); - mockHttpContext - .SetupGet(o => o.RequestServices) - .Returns(GetServiceProvider(contextAccessor)); - - var mockSerializer = new Mock(); - mockSerializer - .Setup(o => o.Serialize(token)) - .Returns("serialized-value"); - var options = new AntiforgeryOptions() { CookieName = _cookieName, RequireSsl = requireSsl }; - var tokenStore = new DefaultAntiforgeryTokenStore( - optionsAccessor: new TestOptionsManager(options), - tokenSerializer: mockSerializer.Object); + var tokenStore = new DefaultAntiforgeryTokenStore(new TestOptionsManager(options)); // Act tokenStore.SaveCookieToken(mockHttpContext.Object, token); // Assert Assert.Equal(1, cookies.Count); - Assert.NotNull(contextAccessor.Value.CookieToken); Assert.NotNull(cookies); Assert.Equal(_cookieName, cookies.Key); Assert.Equal("serialized-value", cookies.Value); @@ -391,39 +295,24 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal Assert.Equal(defaultCookieSecureValue, cookies.Options.Secure); } - private HttpContext GetHttpContext( - string cookieName, - string cookieValue, - IAntiforgeryContextAccessor contextAccessor = null) + private HttpContext GetHttpContext(string cookieName, string cookieValue) { var cookies = new RequestCookieCollection(new Dictionary { { cookieName, cookieValue }, }); - return GetHttpContext(cookies, contextAccessor); + return GetHttpContext(cookies); } - private HttpContext GetHttpContext( - IRequestCookieCollection cookies, - IAntiforgeryContextAccessor contextAccessor = null) + private HttpContext GetHttpContext(IRequestCookieCollection cookies) { var httpContext = new DefaultHttpContext(); httpContext.Request.Cookies = cookies; - contextAccessor = contextAccessor ?? new DefaultAntiforgeryContextAccessor(); - httpContext.RequestServices = GetServiceProvider(contextAccessor); - return httpContext; } - private static IServiceProvider GetServiceProvider(IAntiforgeryContextAccessor contextAccessor) - { - var serviceCollection = new ServiceCollection(); - serviceCollection.AddSingleton(contextAccessor); - return serviceCollection.BuildServiceProvider(); - } - private class MockResponseCookieCollection : IResponseCookies { public string Key { get; set; } From c85badcf71e33f5c4301aed0117080c9175f2391 Mon Sep 17 00:00:00 2001 From: Doug Bunting Date: Tue, 9 Feb 2016 16:43:01 -0800 Subject: [PATCH 084/296] Fix bad merge - not exactly logging at the right spot in `GetAndStoreTokens()` - test helpers were creating two separate `ServiceCollections` - also didn't compile! --- .../Internal/DefaultAntiforgery.cs | 23 +++++++++++-------- .../Internal/DefaultAntiforgeryTest.cs | 16 ++++--------- 2 files changed, 18 insertions(+), 21 deletions(-) diff --git a/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgery.cs b/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgery.cs index 6356d3f6d7..a22576bd0b 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgery.cs +++ b/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgery.cs @@ -50,19 +50,22 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal var antiforgeryContext = GetTokensInternal(httpContext); var tokenSet = Serialize(antiforgeryContext); - if (!antiforgeryContext.HaveStoredNewCookieToken && antiforgeryContext.NewCookieToken != null) + if (!antiforgeryContext.HaveStoredNewCookieToken) { - // Serialize handles the new cookie token string. - Debug.Assert(antiforgeryContext.NewCookieTokenString != null); + if (antiforgeryContext.NewCookieToken != null) + { + // Serialize handles the new cookie token string. + Debug.Assert(antiforgeryContext.NewCookieTokenString != null); - SaveCookieTokenAndHeader(httpContext, antiforgeryContext.NewCookieTokenString); - antiforgeryContext.HaveStoredNewCookieToken = true; + SaveCookieTokenAndHeader(httpContext, antiforgeryContext.NewCookieTokenString); + antiforgeryContext.HaveStoredNewCookieToken = true; - _logger.NewCookieToken(); - } - else - { - _logger.ReusedCookieToken(); + _logger.NewCookieToken(); + } + else + { + _logger.ReusedCookieToken(); + } } return tokenSet; diff --git a/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTest.cs b/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTest.cs index d1571fc59b..6fd193db1a 100644 --- a/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTest.cs +++ b/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTest.cs @@ -6,7 +6,6 @@ using System.Security.Claims; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.Internal; -using Microsoft.AspNetCore.Testing; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; @@ -878,28 +877,23 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal loggerFactory: loggerFactory); } - private IServiceProvider GetServices() + private IServiceProvider GetServices(IAntiforgeryContextAccessor contextAccessor) { var builder = new ServiceCollection(); + builder.AddSingleton(contextAccessor); builder.AddSingleton(new LoggerFactory()); return builder.BuildServiceProvider(); } - private HttpContext GetHttpContext(IAntiforgeryContextAccessor contextAccessor) + private HttpContext GetHttpContext(IAntiforgeryContextAccessor contextAccessor = null) { var httpContext = new DefaultHttpContext(); - - httpContext.RequestServices = GetServices(); + contextAccessor = contextAccessor ?? new DefaultAntiforgeryContextAccessor(); + httpContext.RequestServices = GetServices(contextAccessor); httpContext.User = new ClaimsPrincipal(new ClaimsIdentity("some-auth")); - contextAccessor = contextAccessor ?? new DefaultAntiforgeryContextAccessor(); - - var serviceCollection = new ServiceCollection(); - serviceCollection.AddSingleton(contextAccessor); - httpContext.RequestServices = serviceCollection.BuildServiceProvider(); - return httpContext; } From 668b67170f30174c92be46f9dfec01b7b395f856 Mon Sep 17 00:00:00 2001 From: Kiran Challa Date: Mon, 8 Feb 2016 12:40:07 -0800 Subject: [PATCH 085/296] Enable tests to run in donet xunit runner --- .../project.json | 21 ++++++++----------- .../project.json | 17 +++++++-------- 2 files changed, 16 insertions(+), 22 deletions(-) diff --git a/test/Microsoft.AspNetCore.Antiforgery.FunctionalTests/project.json b/test/Microsoft.AspNetCore.Antiforgery.FunctionalTests/project.json index b6125bd758..a2a1bfdb71 100644 --- a/test/Microsoft.AspNetCore.Antiforgery.FunctionalTests/project.json +++ b/test/Microsoft.AspNetCore.Antiforgery.FunctionalTests/project.json @@ -6,10 +6,15 @@ "Microsoft.NETCore.Platforms": "1.0.1-*" }, "testRunner": "xunit", - "commands": { - "test": "xunit.runner.aspnet" - }, "frameworks": { + "dnxcore50": { + "dependencies": { + "moq.netcore": "4.4.0-beta8", + "System.Net.Http": "4.0.1-*", + "dotnet-test-xunit": "1.0.0-dev-*" + }, + "imports": "portable-net451+win8" + }, "dnx451": { "dependencies": { "Moq": "4.2.1312.1622", @@ -18,14 +23,6 @@ "frameworkAssemblies": { "System.Net.Http": "" } - }, - "dnxcore50": { - "dependencies": { - "moq.netcore": "4.4.0-beta8", - "System.Net.Http": "4.0.1-*", - "xunit.runner.aspnet": "2.0.0-aspnet-*" - }, - "imports": "portable-net451+win8" } } -} +} \ No newline at end of file diff --git a/test/Microsoft.AspNetCore.Antiforgery.Test/project.json b/test/Microsoft.AspNetCore.Antiforgery.Test/project.json index 6b60226074..3f7b9441f3 100644 --- a/test/Microsoft.AspNetCore.Antiforgery.Test/project.json +++ b/test/Microsoft.AspNetCore.Antiforgery.Test/project.json @@ -14,10 +14,14 @@ "xunit": "2.1.0-*" }, "testRunner": "xunit", - "commands": { - "test": "xunit.runner.aspnet" - }, "frameworks": { + "dnxcore50": { + "dependencies": { + "moq.netcore": "4.4.0-beta8", + "dotnet-test-xunit": "1.0.0-dev-*" + }, + "imports": "portable-net451+win8" + }, "dnx451": { "frameworkAssemblies": { "System.Threading.Tasks": "" @@ -26,13 +30,6 @@ "Moq": "4.2.1312.1622", "xunit.runner.console": "2.1.0" } - }, - "dnxcore50": { - "dependencies": { - "moq.netcore": "4.4.0-beta8", - "xunit.runner.aspnet": "2.0.0-aspnet-*" - }, - "imports": "portable-net451+win8" } } } From ac107b53717d7e66ba2d6c0c40dd6feabeac746b Mon Sep 17 00:00:00 2001 From: Ryan Nowak Date: Fri, 12 Feb 2016 15:56:07 -0800 Subject: [PATCH 086/296] Make IsRequestValid check HTTP method This code was popping up everywhere this method is called. Seems bad to duplicate it. Really what the caller wants to know is 'is the request valid or a potential CSRF exploit?'. This gets the API closer to that. --- .../IAntiforgery.cs | 7 +- .../Internal/DefaultAntiforgery.cs | 10 +++ .../Internal/DefaultAntiforgeryTest.cs | 70 +++++++++++++++++++ 3 files changed, 84 insertions(+), 3 deletions(-) diff --git a/src/Microsoft.AspNetCore.Antiforgery/IAntiforgery.cs b/src/Microsoft.AspNetCore.Antiforgery/IAntiforgery.cs index 0cdcf35a8b..8d62f67ec1 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/IAntiforgery.cs +++ b/src/Microsoft.AspNetCore.Antiforgery/IAntiforgery.cs @@ -36,12 +36,13 @@ namespace Microsoft.AspNetCore.Antiforgery AntiforgeryTokenSet GetTokens(HttpContext httpContext); /// - /// Asynchronously returns a value indicating whether the request contains a valid antiforgery token. + /// Asynchronously returns a value indicating whether the request passes antiforgery validation. If the + /// request uses a safe HTTP method (GET, HEAD, OPTIONS, TRACE), the antiforgery token is not validated. /// /// The associated with the current request. /// - /// A that, when completed, returns true if the request contains a - /// valid antiforgery token, otherwise returns false. + /// A that, when completed, returns true if the is requst uses a safe HTTP + /// method or contains a value antiforgery token, otherwise returns false. /// Task IsRequestValidAsync(HttpContext httpContext); diff --git a/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgery.cs b/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgery.cs index a22576bd0b..7788a2bb0b 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgery.cs +++ b/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgery.cs @@ -95,6 +95,16 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal CheckSSLConfig(httpContext); + var method = httpContext.Request.Method; + if (string.Equals(method, "GET", StringComparison.OrdinalIgnoreCase) || + string.Equals(method, "HEAD", StringComparison.OrdinalIgnoreCase) || + string.Equals(method, "OPTIONS", StringComparison.OrdinalIgnoreCase) || + string.Equals(method, "TRACE", StringComparison.OrdinalIgnoreCase)) + { + // Validation not needed for these request types. + return true; + } + var tokens = await _tokenStore.GetRequestTokensAsync(httpContext); if (tokens.CookieToken == null) { diff --git a/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTest.cs b/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTest.cs index 6fd193db1a..670b7f607b 100644 --- a/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTest.cs +++ b/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTest.cs @@ -448,6 +448,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal // Arrange var contextAccessor = new DefaultAntiforgeryContextAccessor(); var context = CreateMockContext(new AntiforgeryOptions(), contextAccessor: contextAccessor); + context.HttpContext.Request.Method = "POST"; string message; context.TokenGenerator @@ -490,6 +491,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal }, }; var context = CreateMockContext(new AntiforgeryOptions(), contextAccessor: contextAccessor); + context.HttpContext.Request.Method = "POST"; string message; context.TokenGenerator @@ -519,6 +521,74 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal Times.Never); } + [Theory] + [InlineData("GeT")] + [InlineData("HEAD")] + [InlineData("options")] + [InlineData("TrAcE")] + public async Task IsRequestValidAsync_SkipsAntiforgery_ForSafeHttpMethods(string httpMethod) + { + // Arrange + var context = CreateMockContext(new AntiforgeryOptions()); + context.HttpContext.Request.Method = httpMethod; + + string message; + context.TokenGenerator + .Setup(o => o.TryValidateTokenSet( + context.HttpContext, + It.IsAny(), + It.IsAny(), + out message)) + .Returns(false) + .Verifiable(); + + var antiforgery = GetAntiforgery(context); + + // Act + var result = await antiforgery.IsRequestValidAsync(context.HttpContext); + + // Assert + Assert.True(result); + context.TokenGenerator + .Verify(o => o.TryValidateTokenSet( + context.HttpContext, + It.IsAny(), + It.IsAny(), + out message), + Times.Never); + } + + [Theory] + [InlineData("PUT")] + [InlineData("post")] + [InlineData("Delete")] + [InlineData("Custom")] + public async Task IsRequestValidAsync_ValidatesAntiforgery_ForNonSafeHttpMethods(string httpMethod) + { + // Arrange + var context = CreateMockContext(new AntiforgeryOptions()); + context.HttpContext.Request.Method = httpMethod; + + string message; + context.TokenGenerator + .Setup(o => o.TryValidateTokenSet( + context.HttpContext, + It.IsAny(), + It.IsAny(), + out message)) + .Returns(true) + .Verifiable(); + + var antiforgery = GetAntiforgery(context); + + // Act + var result = await antiforgery.IsRequestValidAsync(context.HttpContext); + + // Assert + Assert.True(result); + context.TokenGenerator.Verify(); + } + [Fact] public async Task ValidateRequestAsync_FromStore_Failure() { From 220479c1a181d3879985843403e7f904aae1a291 Mon Sep 17 00:00:00 2001 From: Ajay Bhargav Baaskaran Date: Fri, 5 Feb 2016 16:12:07 -0800 Subject: [PATCH 087/296] [Fixes #30] Updated UID generation in DefaultClaimUidExtractor --- .../DefaultAntiforgeryTokenGenerator.cs | 52 ++++- .../Internal/DefaultClaimUidExtractor.cs | 99 +++++++-- .../Internal/IClaimUidExtractor.cs | 7 +- .../DefaultAntiforgeryTokenGeneratorTest.cs | 9 +- .../Internal/DefaultClaimUidExtractorTest.cs | 190 ++++++++++++++++-- 5 files changed, 300 insertions(+), 57 deletions(-) diff --git a/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgeryTokenGenerator.cs b/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgeryTokenGenerator.cs index 390a39cab8..872f7ed18c 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgeryTokenGenerator.cs +++ b/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgeryTokenGenerator.cs @@ -2,6 +2,7 @@ // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; +using System.Collections.Generic; using System.Security.Claims; using System.Security.Principal; using Microsoft.AspNetCore.Http; @@ -60,16 +61,17 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal }; var isIdentityAuthenticated = false; - var identity = httpContext.User?.Identity as ClaimsIdentity; // populate Username and ClaimUid - if (identity != null && identity.IsAuthenticated) + var authenticatedIdentity = GetAuthenticatedIdentity(httpContext.User); + if (authenticatedIdentity != null) { isIdentityAuthenticated = true; - requestToken.ClaimUid = GetClaimUidBlob(_claimUidExtractor.ExtractClaimUid(identity)); + requestToken.ClaimUid = GetClaimUidBlob(_claimUidExtractor.ExtractClaimUid(httpContext.User)); + if (requestToken.ClaimUid == null) { - requestToken.Username = identity.Name; + requestToken.Username = authenticatedIdentity.Name; } } @@ -87,7 +89,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal // Application says user is authenticated, but we have no identifier for the user. throw new InvalidOperationException( Resources.FormatAntiforgeryTokenValidator_AuthenticatedUserWithoutUsername( - identity.GetType(), + authenticatedIdentity.GetType(), nameof(IIdentity.IsAuthenticated), "true", nameof(IIdentity.Name), @@ -148,13 +150,13 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal var currentUsername = string.Empty; BinaryBlob currentClaimUid = null; - var identity = httpContext.User?.Identity as ClaimsIdentity; - if (identity != null && identity.IsAuthenticated) + var authenticatedIdentity = GetAuthenticatedIdentity(httpContext.User); + if (authenticatedIdentity != null) { - currentClaimUid = GetClaimUidBlob(_claimUidExtractor.ExtractClaimUid(identity)); + currentClaimUid = GetClaimUidBlob(_claimUidExtractor.ExtractClaimUid(httpContext.User)); if (currentClaimUid == null) { - currentUsername = identity.Name ?? string.Empty; + currentUsername = authenticatedIdentity.Name ?? string.Empty; } } @@ -200,5 +202,37 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal return new BinaryBlob(256, Convert.FromBase64String(base64ClaimUid)); } + + private static ClaimsIdentity GetAuthenticatedIdentity(ClaimsPrincipal claimsPrincipal) + { + if (claimsPrincipal == null) + { + return null; + } + + var identitiesList = claimsPrincipal.Identities as List; + if (identitiesList != null) + { + for (var i = 0; i < identitiesList.Count; i++) + { + if (identitiesList[i].IsAuthenticated) + { + return identitiesList[i]; + } + } + } + else + { + foreach (var identity in claimsPrincipal.Identities) + { + if (identity.IsAuthenticated) + { + return identity; + } + } + } + + return null; + } } } \ No newline at end of file diff --git a/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultClaimUidExtractor.cs b/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultClaimUidExtractor.cs index 7f089073bc..1a7ef394a0 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultClaimUidExtractor.cs +++ b/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultClaimUidExtractor.cs @@ -3,7 +3,7 @@ using System; using System.Collections.Generic; -using System.Linq; +using System.Diagnostics; using System.Security.Claims; using Microsoft.Extensions.ObjectPool; @@ -22,42 +22,99 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal } /// - public string ExtractClaimUid(ClaimsIdentity claimsIdentity) + public string ExtractClaimUid(ClaimsPrincipal claimsPrincipal) { - if (claimsIdentity == null || !claimsIdentity.IsAuthenticated) + Debug.Assert(claimsPrincipal != null); + + var uniqueIdentifierParameters = GetUniqueIdentifierParameters(claimsPrincipal.Identities); + if (uniqueIdentifierParameters == null) { - // Skip anonymous users + // No authenticated identities containing claims found. return null; } - var uniqueIdentifierParameters = GetUniqueIdentifierParameters(claimsIdentity); var claimUidBytes = ComputeSha256(uniqueIdentifierParameters); return Convert.ToBase64String(claimUidBytes); } - // Internal for testing - internal static IEnumerable GetUniqueIdentifierParameters(ClaimsIdentity claimsIdentity) + public static IList GetUniqueIdentifierParameters(IEnumerable claimsIdentities) { - var nameIdentifierClaim = claimsIdentity.FindFirst( - claim => string.Equals(ClaimTypes.NameIdentifier, claim.Type, StringComparison.Ordinal)); - if (nameIdentifierClaim != null && !string.IsNullOrEmpty(nameIdentifierClaim.Value)) + var identitiesList = claimsIdentities as List; + if (identitiesList == null) { - return new string[] - { - ClaimTypes.NameIdentifier, - nameIdentifierClaim.Value - }; + identitiesList = new List(claimsIdentities); } - // We do not understand this ClaimsIdentity, fallback on serializing the entire claims Identity. - var claims = claimsIdentity.Claims.ToList(); - claims.Sort((a, b) => string.Compare(a.Type, b.Type, StringComparison.Ordinal)); - - var identifierParameters = new List(claims.Count * 2); - foreach (var claim in claims) + for (var i = 0; i < identitiesList.Count; i++) { + var identity = identitiesList[i]; + if (!identity.IsAuthenticated) + { + continue; + } + + var subClaim = identity.FindFirst( + claim => string.Equals("sub", claim.Type, StringComparison.Ordinal)); + if (subClaim != null && !string.IsNullOrEmpty(subClaim.Value)) + { + return new string[] + { + subClaim.Type, + subClaim.Value, + subClaim.Issuer + }; + } + + var nameIdentifierClaim = identity.FindFirst( + claim => string.Equals(ClaimTypes.NameIdentifier, claim.Type, StringComparison.Ordinal)); + if (nameIdentifierClaim != null && !string.IsNullOrEmpty(nameIdentifierClaim.Value)) + { + return new string[] + { + nameIdentifierClaim.Type, + nameIdentifierClaim.Value, + nameIdentifierClaim.Issuer + }; + } + + var upnClaim = identity.FindFirst( + claim => string.Equals(ClaimTypes.Upn, claim.Type, StringComparison.Ordinal)); + if (upnClaim != null && !string.IsNullOrEmpty(upnClaim.Value)) + { + return new string[] + { + upnClaim.Type, + upnClaim.Value, + upnClaim.Issuer + }; + } + } + + // We do not understand any of the ClaimsIdentity instances, fallback on serializing all claims in every claims Identity. + var allClaims = new List(); + for (var i = 0; i < identitiesList.Count; i++) + { + if (identitiesList[i].IsAuthenticated) + { + allClaims.AddRange(identitiesList[i].Claims); + } + } + + if (allClaims.Count == 0) + { + // No authenticated identities containing claims found. + return null; + } + + allClaims.Sort((a, b) => string.Compare(a.Type, b.Type, StringComparison.Ordinal)); + + var identifierParameters = new List(allClaims.Count * 3); + for (var i = 0; i < allClaims.Count; i++) + { + var claim = allClaims[i]; identifierParameters.Add(claim.Type); identifierParameters.Add(claim.Value); + identifierParameters.Add(claim.Issuer); } return identifierParameters; diff --git a/src/Microsoft.AspNetCore.Antiforgery/Internal/IClaimUidExtractor.cs b/src/Microsoft.AspNetCore.Antiforgery/Internal/IClaimUidExtractor.cs index d4a888dec5..72ab230fb4 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/Internal/IClaimUidExtractor.cs +++ b/src/Microsoft.AspNetCore.Antiforgery/Internal/IClaimUidExtractor.cs @@ -1,20 +1,21 @@ // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. +using System.Collections.Generic; using System.Security.Claims; namespace Microsoft.AspNetCore.Antiforgery.Internal { /// - /// This interface can extract unique identifers for a claims-based identity. + /// This interface can extract unique identifers for a . /// public interface IClaimUidExtractor { /// /// Extracts claims identifier. /// - /// The . + /// The . /// The claims identifier. - string ExtractClaimUid(ClaimsIdentity identity); + string ExtractClaimUid(ClaimsPrincipal claimsPrincipal); } } \ No newline at end of file diff --git a/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTokenGeneratorTest.cs b/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTokenGeneratorTest.cs index 0e4a2a3d02..5509726a38 100644 --- a/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTokenGeneratorTest.cs +++ b/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTokenGeneratorTest.cs @@ -2,6 +2,7 @@ // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; +using System.Collections.Generic; using System.Security.Claims; using System.Security.Cryptography; using Microsoft.AspNetCore.Http.Internal; @@ -157,7 +158,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal var expectedClaimUid = new BinaryBlob(256, data); var mockClaimUidExtractor = new Mock(); - mockClaimUidExtractor.Setup(o => o.ExtractClaimUid(identity)) + mockClaimUidExtractor.Setup(o => o.ExtractClaimUid(It.Is(c => c.Identity == identity))) .Returns(base64ClaimUId); var tokenProvider = new DefaultAntiforgeryTokenGenerator( @@ -410,7 +411,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal }; var mockClaimUidExtractor = new Mock(); - mockClaimUidExtractor.Setup(o => o.ExtractClaimUid(identity)) + mockClaimUidExtractor.Setup(o => o.ExtractClaimUid(It.Is(c => c.Identity == identity))) .Returns((string)null); var tokenProvider = new DefaultAntiforgeryTokenGenerator( @@ -448,7 +449,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal var differentToken = new BinaryBlob(256); var mockClaimUidExtractor = new Mock(); - mockClaimUidExtractor.Setup(o => o.ExtractClaimUid(identity)) + mockClaimUidExtractor.Setup(o => o.ExtractClaimUid(It.Is(c => c.Identity == identity))) .Returns(Convert.ToBase64String(differentToken.GetData())); var tokenProvider = new DefaultAntiforgeryTokenGenerator( @@ -590,7 +591,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal }; var mockClaimUidExtractor = new Mock(); - mockClaimUidExtractor.Setup(o => o.ExtractClaimUid(identity)) + mockClaimUidExtractor.Setup(o => o.ExtractClaimUid(It.Is(c => c.Identity == identity))) .Returns(Convert.ToBase64String(fieldtoken.ClaimUid.GetData())); var tokenProvider = new DefaultAntiforgeryTokenGenerator( diff --git a/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultClaimUidExtractorTest.cs b/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultClaimUidExtractorTest.cs index 2968358be2..59e2d3a3ac 100644 --- a/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultClaimUidExtractorTest.cs +++ b/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultClaimUidExtractorTest.cs @@ -2,6 +2,8 @@ // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; +using System.Collections.Generic; +using System.Diagnostics; using System.Linq; using System.Security.Claims; using Microsoft.Extensions.ObjectPool; @@ -15,19 +17,6 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal private static readonly ObjectPool _pool = new DefaultObjectPoolProvider().Create(new AntiforgerySerializationContextPooledObjectPolicy()); - [Fact] - public void ExtractClaimUid_NullIdentity() - { - // Arrange - var extractor = new DefaultClaimUidExtractor(_pool); - - // Act - var claimUid = extractor.ExtractClaimUid(null); - - // Assert - Assert.Null(claimUid); - } - [Fact] public void ExtractClaimUid_Unauthenticated() { @@ -39,7 +28,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal .Returns(false); // Act - var claimUid = extractor.ExtractClaimUid(mockIdentity.Object); + var claimUid = extractor.ExtractClaimUid(new ClaimsPrincipal(mockIdentity.Object)); // Assert Assert.Null(claimUid); @@ -52,21 +41,22 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal var mockIdentity = new Mock(); mockIdentity.Setup(o => o.IsAuthenticated) .Returns(true); + mockIdentity.Setup(o => o.Claims).Returns(new Claim[] { new Claim(ClaimTypes.Name, "someName") }); var extractor = new DefaultClaimUidExtractor(_pool); // Act - var claimUid = extractor.ExtractClaimUid(mockIdentity.Object); + var claimUid = extractor.ExtractClaimUid(new ClaimsPrincipal(mockIdentity.Object )); // Assert Assert.NotNull(claimUid); - Assert.Equal("47DEQpj8HBSa+/TImW+5JCeuQeRkm5NMpJWZG3hSuFU=", claimUid); + Assert.Equal("yhXE+2v4zSXHtRHmzm4cmrhZca2J0g7yTUwtUerdeF4=", claimUid); } [Fact] public void DefaultUniqueClaimTypes_NotPresent_SerializesAllClaimTypes() { - var identity = new ClaimsIdentity(); + var identity = new ClaimsIdentity("someAuthentication"); identity.AddClaim(new Claim(ClaimTypes.Email, "someone@antifrogery.com")); identity.AddClaim(new Claim(ClaimTypes.GivenName, "some")); identity.AddClaim(new Claim(ClaimTypes.Surname, "one")); @@ -79,7 +69,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal var claimsIdentity = (ClaimsIdentity)identity; // Act - var identiferParameters = DefaultClaimUidExtractor.GetUniqueIdentifierParameters(claimsIdentity) + var identiferParameters = DefaultClaimUidExtractor.GetUniqueIdentifierParameters(new ClaimsIdentity[] { claimsIdentity }) .ToArray(); var claims = claimsIdentity.Claims.ToList(); claims.Sort((a, b) => string.Compare(a.Type, b.Type, StringComparison.Ordinal)); @@ -90,6 +80,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal { Assert.Equal(identiferParameters[index++], claim.Type); Assert.Equal(identiferParameters[index++], claim.Value); + Assert.Equal(identiferParameters[index++], claim.Issuer); } } @@ -97,18 +88,177 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal public void DefaultUniqueClaimTypes_Present() { // Arrange - var identity = new ClaimsIdentity(); + var identity = new ClaimsIdentity("someAuthentication"); identity.AddClaim(new Claim("fooClaim", "fooClaimValue")); identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, "nameIdentifierValue")); // Act - var uniqueIdentifierParameters = DefaultClaimUidExtractor.GetUniqueIdentifierParameters(identity); + var uniqueIdentifierParameters = DefaultClaimUidExtractor.GetUniqueIdentifierParameters(new ClaimsIdentity[] { identity }); // Assert Assert.Equal(new string[] { ClaimTypes.NameIdentifier, "nameIdentifierValue", + "LOCAL AUTHORITY", + }, uniqueIdentifierParameters); + } + + [Fact] + public void GetUniqueIdentifierParameters_PrefersSubClaimOverNameIdentifierAndUpn() + { + // Arrange + var identity = new ClaimsIdentity("someAuthentication"); + identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, "nameIdentifierValue")); + identity.AddClaim(new Claim("sub", "subClaimValue")); + identity.AddClaim(new Claim(ClaimTypes.Upn, "upnClaimValue")); + + // Act + var uniqueIdentifierParameters = DefaultClaimUidExtractor.GetUniqueIdentifierParameters(new ClaimsIdentity[] { identity }); + + // Assert + Assert.Equal(new string[] + { + "sub", + "subClaimValue", + "LOCAL AUTHORITY", + }, uniqueIdentifierParameters); + } + + [Fact] + public void GetUniqueIdentifierParameters_PrefersNameIdentifierOverUpn() + { + // Arrange + var identity = new ClaimsIdentity("someAuthentication"); + identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, "nameIdentifierValue")); + identity.AddClaim(new Claim(ClaimTypes.Upn, "upnClaimValue")); + + // Act + var uniqueIdentifierParameters = DefaultClaimUidExtractor.GetUniqueIdentifierParameters(new ClaimsIdentity[] { identity }); + + // Assert + Assert.Equal(new string[] + { + ClaimTypes.NameIdentifier, + "nameIdentifierValue", + "LOCAL AUTHORITY", + }, uniqueIdentifierParameters); + } + + [Fact] + public void GetUniqueIdentifierParameters_UsesUpnIfPresent() + { + // Arrange + var identity = new ClaimsIdentity("someAuthentication"); + identity.AddClaim(new Claim("fooClaim", "fooClaimValue")); + identity.AddClaim(new Claim(ClaimTypes.Upn, "upnClaimValue")); + + // Act + var uniqueIdentifierParameters = DefaultClaimUidExtractor.GetUniqueIdentifierParameters(new ClaimsIdentity[] { identity }); + + // Assert + Assert.Equal(new string[] + { + ClaimTypes.Upn, + "upnClaimValue", + "LOCAL AUTHORITY", + }, uniqueIdentifierParameters); + } + + [Fact] + public void GetUniqueIdentifierParameters_MultipleIdentities_UsesOnlyAuthenticatedIdentities() + { + // Arrange + var identity1 = new ClaimsIdentity(); // no authentication + identity1.AddClaim(new Claim("sub", "subClaimValue")); + var identity2 = new ClaimsIdentity("someAuthentication"); + identity2.AddClaim(new Claim(ClaimTypes.NameIdentifier, "nameIdentifierValue")); + + // Act + var uniqueIdentifierParameters = DefaultClaimUidExtractor.GetUniqueIdentifierParameters(new ClaimsIdentity[] { identity1, identity2 }); + + // Assert + Assert.Equal(new string[] + { + ClaimTypes.NameIdentifier, + "nameIdentifierValue", + "LOCAL AUTHORITY", + }, uniqueIdentifierParameters); + } + + [Fact] + public void GetUniqueIdentifierParameters_NoKnownClaimTypesFound_SortsAndReturnsAllClaimsFromAuthenticatedIdentities() + { + // Arrange + var identity1 = new ClaimsIdentity(); // no authentication + identity1.AddClaim(new Claim("sub", "subClaimValue")); + var identity2 = new ClaimsIdentity("someAuthentication"); + identity2.AddClaim(new Claim(ClaimTypes.Email, "email@domain.com")); + var identity3 = new ClaimsIdentity("someAuthentication"); + identity3.AddClaim(new Claim(ClaimTypes.Country, "countryValue")); + var identity4 = new ClaimsIdentity("someAuthentication"); + identity4.AddClaim(new Claim(ClaimTypes.Name, "claimName")); + + // Act + var uniqueIdentifierParameters = DefaultClaimUidExtractor.GetUniqueIdentifierParameters( + new ClaimsIdentity[] { identity1, identity2, identity3, identity4 }); + + // Assert + Assert.Equal(new List + { + ClaimTypes.Country, + "countryValue", + "LOCAL AUTHORITY", + ClaimTypes.Email, + "email@domain.com", + "LOCAL AUTHORITY", + ClaimTypes.Name, + "claimName", + "LOCAL AUTHORITY", + }, uniqueIdentifierParameters); + } + + [Fact] + public void GetUniqueIdentifierParameters_PrefersNameFromFirstIdentity_OverSubFromSecondIdentity() + { + // Arrange + var identity1 = new ClaimsIdentity("someAuthentication"); + identity1.AddClaim(new Claim(ClaimTypes.NameIdentifier, "nameIdentifierValue")); + var identity2 = new ClaimsIdentity("someAuthentication"); + identity2.AddClaim(new Claim("sub", "subClaimValue")); + + // Act + var uniqueIdentifierParameters = DefaultClaimUidExtractor.GetUniqueIdentifierParameters( + new ClaimsIdentity[] { identity1, identity2 }); + + // Assert + Assert.Equal(new string[] + { + ClaimTypes.NameIdentifier, + "nameIdentifierValue", + "LOCAL AUTHORITY", + }, uniqueIdentifierParameters); + } + + [Fact] + public void GetUniqueIdentifierParameters_PrefersUpnFromFirstIdentity_OverNameFromSecondIdentity() + { + // Arrange + var identity1 = new ClaimsIdentity("someAuthentication"); + identity1.AddClaim(new Claim(ClaimTypes.Upn, "upnValue")); + var identity2 = new ClaimsIdentity("someAuthentication"); + identity2.AddClaim(new Claim(ClaimTypes.NameIdentifier, "nameIdentifierValue")); + + // Act + var uniqueIdentifierParameters = DefaultClaimUidExtractor.GetUniqueIdentifierParameters( + new ClaimsIdentity[] { identity1, identity2 }); + + // Assert + Assert.Equal(new string[] + { + ClaimTypes.Upn, + "upnValue", + "LOCAL AUTHORITY", }, uniqueIdentifierParameters); } } From a8dbf6a2550462d5ec72cd6f0d5194c90ec997b3 Mon Sep 17 00:00:00 2001 From: ryanbrandenburg Date: Wed, 10 Feb 2016 17:06:34 -0800 Subject: [PATCH 088/296] * Add logging for other IAntiforgery public methods --- .../Internal/DefaultAntiforgery.cs | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgery.cs b/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgery.cs index 7788a2bb0b..137b0b4fe0 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgery.cs +++ b/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgery.cs @@ -59,7 +59,6 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal SaveCookieTokenAndHeader(httpContext, antiforgeryContext.NewCookieTokenString); antiforgeryContext.HaveStoredNewCookieToken = true; - _logger.NewCookieToken(); } else @@ -233,6 +232,11 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal SaveCookieTokenAndHeader(httpContext, antiforgeryContext.NewCookieTokenString); antiforgeryContext.HaveStoredNewCookieToken = true; + _logger.NewCookieToken(); + } + else + { + _logger.ReusedCookieToken(); } } @@ -406,4 +410,4 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal } } } -} \ No newline at end of file +} From c2f4bd0be5e35bd7bb01628724c7cd3e59fc3382 Mon Sep 17 00:00:00 2001 From: Ajay Bhargav Baaskaran Date: Wed, 17 Feb 2016 12:10:56 -0800 Subject: [PATCH 089/296] Enabled xml doc generation --- NuGetPackageVerifier.json | 14 ++------------ .../IAntiforgery.cs | 2 +- src/Microsoft.AspNetCore.Antiforgery/project.json | 4 +++- 3 files changed, 6 insertions(+), 14 deletions(-) diff --git a/NuGetPackageVerifier.json b/NuGetPackageVerifier.json index 49fcb32a52..67e35e0f0f 100644 --- a/NuGetPackageVerifier.json +++ b/NuGetPackageVerifier.json @@ -1,12 +1,7 @@ { "adx": { // Packages written by the ADX team and that ship on NuGet.org "rules": [ - "AssemblyHasDocumentFileRule", - "AssemblyHasVersionAttributesRule", - "AssemblyHasServicingAttributeRule", - "AssemblyHasNeutralResourcesLanguageAttributeRule", - "SatellitePackageRule", - "StrictSemanticVersionValidationRule" + "AdxVerificationCompositeRule" ], "packages": { "Microsoft.AspNetCore.Antiforgery": { } @@ -14,12 +9,7 @@ }, "Default": { // Rules to run for packages not listed in any other set. "rules": [ - "AssemblyHasDocumentFileRule", - "AssemblyHasVersionAttributesRule", - "AssemblyHasServicingAttributeRule", - "AssemblyHasNeutralResourcesLanguageAttributeRule", - "SatellitePackageRule", - "StrictSemanticVersionValidationRule" + "DefaultCompositeRule" ] } } \ No newline at end of file diff --git a/src/Microsoft.AspNetCore.Antiforgery/IAntiforgery.cs b/src/Microsoft.AspNetCore.Antiforgery/IAntiforgery.cs index 8d62f67ec1..6ac2e44e37 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/IAntiforgery.cs +++ b/src/Microsoft.AspNetCore.Antiforgery/IAntiforgery.cs @@ -41,7 +41,7 @@ namespace Microsoft.AspNetCore.Antiforgery /// /// The associated with the current request. /// - /// A that, when completed, returns true if the is requst uses a safe HTTP + /// A that, when completed, returns true if the is requst uses a safe HTTP /// method or contains a value antiforgery token, otherwise returns false. /// Task IsRequestValidAsync(HttpContext httpContext); diff --git a/src/Microsoft.AspNetCore.Antiforgery/project.json b/src/Microsoft.AspNetCore.Antiforgery/project.json index bcd5357d8d..d5bda2ecf5 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/project.json +++ b/src/Microsoft.AspNetCore.Antiforgery/project.json @@ -3,7 +3,9 @@ "version": "1.0.0-*", "compilationOptions": { "warningsAsErrors": true, - "keyFile": "../../tools/Key.snk" + "keyFile": "../../tools/Key.snk", + "nowarn": [ "CS1591" ], + "xmlDoc": true }, "repository": { "type": "git", From 478edc1735716993cb9771f5640a46bb418f6e88 Mon Sep 17 00:00:00 2001 From: Doug Bunting Date: Wed, 17 Feb 2016 23:17:15 -0800 Subject: [PATCH 090/296] Pool `char`s used for base64url-encoding and -decoding - #23 part 4 - depends on aspnet/HttpAbstractions@8c120a0 nits: - correct name of a field in `AntiforgerySerializationContext` - avoid allocations when returning an `AntiforgerySerializationContext` in (unlikely) case `Stream` is unused - name literal `int` parameters --- .../AntiforgerySerializationContext.cs | 58 ++++++++++++++----- .../DefaultAntiforgeryTokenSerializer.cs | 27 ++++++++- 2 files changed, 69 insertions(+), 16 deletions(-) diff --git a/src/Microsoft.AspNetCore.Antiforgery/Internal/AntiforgerySerializationContext.cs b/src/Microsoft.AspNetCore.Antiforgery/Internal/AntiforgerySerializationContext.cs index 27f7fa3725..5347f6651a 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/Internal/AntiforgerySerializationContext.cs +++ b/src/Microsoft.AspNetCore.Antiforgery/Internal/AntiforgerySerializationContext.cs @@ -16,7 +16,15 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal // Don't let the MemoryStream grow beyond 1 MB. private const int MaximumStreamSize = 0x100000; - private MemoryStream _memory; + // Start _chars off with length 256 (18 bytes is protected into 116 bytes then encoded into 156 characters). + // Double length from there if necessary. + private const int InitialCharsLength = 256; + + // Don't let _chars grow beyond 512k characters. + private const int MaximumCharsLength = 0x80000; + + private char[] _chars; + private MemoryStream _stream; private BinaryReader _reader; private BinaryWriter _writer; private SHA256 _sha256; @@ -25,16 +33,16 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal { get { - if (_memory == null) + if (_stream == null) { - _memory = new MemoryStream(InitialStreamSize); + _stream = new MemoryStream(InitialStreamSize); } - return _memory; + return _stream; } private set { - _memory = value; + _stream = value; } } @@ -91,19 +99,43 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal } } + public char[] GetChars(int count) + { + if (_chars == null || _chars.Length < count) + { + var newLength = _chars == null ? InitialCharsLength : checked(_chars.Length * 2); + while (newLength < count) + { + newLength = checked(newLength * 2); + } + + _chars = new char[newLength]; + } + + return _chars; + } + public void Reset() { - if (Stream.Capacity > MaximumStreamSize) + if (_chars != null && _chars.Length > MaximumCharsLength) { - Stream = null; - Reader = null; - Writer = null; + _chars = null; } - else + + if (_stream != null) { - Stream.Position = 0L; - Stream.SetLength(0L); + if (Stream.Capacity > MaximumStreamSize) + { + Stream = null; + Reader = null; + Writer = null; + } + else + { + Stream.Position = 0L; + Stream.SetLength(0L); + } } } } -} +} \ No newline at end of file diff --git a/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgeryTokenSerializer.cs b/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgeryTokenSerializer.cs index 216f79ae09..474b2fd7a9 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgeryTokenSerializer.cs +++ b/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgeryTokenSerializer.cs @@ -42,10 +42,19 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal Exception innerException = null; try { - var tokenBytes = WebEncoders.Base64UrlDecode(serializedToken); + var count = serializedToken.Length; + var charsRequired = WebEncoders.GetArraySizeRequiredToDecode(count); + var chars = serializationContext.GetChars(charsRequired); + var tokenBytes = WebEncoders.Base64UrlDecode( + serializedToken, + offset: 0, + buffer: chars, + bufferOffset: 0, + count: count); + var unprotectedBytes = _cryptoSystem.Unprotect(tokenBytes); var stream = serializationContext.Stream; - stream.Write(unprotectedBytes, 0, unprotectedBytes.Length); + stream.Write(unprotectedBytes, offset: 0, count: unprotectedBytes.Length); stream.Position = 0L; var reader = serializationContext.Reader; @@ -156,7 +165,19 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal writer.Flush(); var stream = serializationContext.Stream; - return WebEncoders.Base64UrlEncode(_cryptoSystem.Protect(stream.ToArray())); + var bytes = _cryptoSystem.Protect(stream.ToArray()); + + var count = bytes.Length; + var charsRequired = WebEncoders.GetArraySizeRequiredToEncode(count); + var chars = serializationContext.GetChars(charsRequired); + var outputLength = WebEncoders.Base64UrlEncode( + bytes, + offset: 0, + output: chars, + outputOffset: 0, + count: count); + + return new string(chars, startIndex: 0, length: outputLength); } finally { From 9783a7c42b9e0472556d959de8dad79a327b0e67 Mon Sep 17 00:00:00 2001 From: Doug Bunting Date: Wed, 24 Feb 2016 12:27:40 -0800 Subject: [PATCH 091/296] Update `build.cmd` to match latest template - aspnet/Universe#347 - `%KOREBUILD_VERSION%` doesn't work without this fix --- build.cmd | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/build.cmd b/build.cmd index 65fb3e3353..95b049cf63 100644 --- a/build.cmd +++ b/build.cmd @@ -28,12 +28,11 @@ IF NOT EXIST %NUGET_PATH% ( copy %CACHED_NUGET% %NUGET_PATH% > nul ) +SET KOREBUILD_DOWNLOAD_ARGS= +IF NOT "%KOREBUILD_VERSION%"=="" ( + SET KOREBUILD_DOWNLOAD_ARGS=-version %KOREBUILD_VERSION% +) IF NOT EXIST %KOREBUILD_FOLDER% ( - SET KOREBUILD_DOWNLOAD_ARGS= - IF NOT "%KOREBUILD_VERSION%"=="" ( - SET KOREBUILD_DOWNLOAD_ARGS=-version %KOREBUILD_VERSION% - ) - %BUILD_FOLDER%\nuget.exe install KoreBuild-dotnet -ExcludeVersion -o %BUILD_FOLDER% -nocache -pre %KOREBUILD_DOWNLOAD_ARGS% ) From 4629148519cde61200c3871d9ab943607aef3e5d Mon Sep 17 00:00:00 2001 From: Ryan Nowak Date: Thu, 18 Feb 2016 12:08:53 -0800 Subject: [PATCH 092/296] [Design] Add antiforgery middleware This new middleware participates in authentication and acts as a filter when the request doesn't include a valid CSRF token for a POST. Any authentication middleware that you want to validate an antiforgery token should go ahead of this middleware in the pipeline (Cookies, IISIntegration). This also takes care of automatic auth (Windows) done by weblistener. Any authentication middleware that you want to ignore antiforgery should go after this middleware in the pipeline. To facilitate this, there are a few changes in the antiforgery API surface. Namely we can now pass in a principal to validate tokens. You can't pass in a principal to generate tokens - we expect you to be logged in at that poing. Also, ValidateRequestAsync(...) now checks the HTTP verb and won't validate GETs and such. --- .../AntiforgeryBuilderExtensions.cs | 29 ++ .../AntiforgeryMiddleware.cs | 65 +++ .../IAntiforgery.cs | 23 ++ .../AntiforgeryAuthenticationHandler.cs | 161 ++++++++ .../Internal/DefaultAntiforgery.cs | 82 +++- .../DefaultAntiforgeryTokenGenerator.cs | 10 +- .../Internal/IAntiforgeryTokenGenerator.cs | 9 +- .../Internal/TaskCache.cs | 12 + .../project.json | 3 +- .../AntiforgeryMiddlewareTest.cs | 382 ++++++++++++++++++ .../AntiforgeryAuthenticationHandlerTest.cs | 293 ++++++++++++++ .../Internal/DefaultAntiforgeryTest.cs | 262 +++++++++++- .../DefaultAntiforgeryTokenGeneratorTest.cs | 68 ++-- 13 files changed, 1339 insertions(+), 60 deletions(-) create mode 100644 src/Microsoft.AspNetCore.Antiforgery/AntiforgeryBuilderExtensions.cs create mode 100644 src/Microsoft.AspNetCore.Antiforgery/AntiforgeryMiddleware.cs create mode 100644 src/Microsoft.AspNetCore.Antiforgery/Internal/AntiforgeryAuthenticationHandler.cs create mode 100644 src/Microsoft.AspNetCore.Antiforgery/Internal/TaskCache.cs create mode 100644 test/Microsoft.AspNetCore.Antiforgery.Test/AntiforgeryMiddlewareTest.cs create mode 100644 test/Microsoft.AspNetCore.Antiforgery.Test/Internal/AntiforgeryAuthenticationHandlerTest.cs diff --git a/src/Microsoft.AspNetCore.Antiforgery/AntiforgeryBuilderExtensions.cs b/src/Microsoft.AspNetCore.Antiforgery/AntiforgeryBuilderExtensions.cs new file mode 100644 index 0000000000..7181518dfb --- /dev/null +++ b/src/Microsoft.AspNetCore.Antiforgery/AntiforgeryBuilderExtensions.cs @@ -0,0 +1,29 @@ +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System; +using Microsoft.AspNetCore.Antiforgery; + +namespace Microsoft.AspNetCore.Builder +{ + /// + /// Extension methods for configuring the antiforgery middleware. + /// + public static class AntiforgeryBuilderExtensions + { + /// + /// Adds the antiforgery middleware. + /// + /// The . + /// The . + public static IApplicationBuilder UseAntiforgery(this IApplicationBuilder app) + { + if (app == null) + { + throw new ArgumentNullException(nameof(app)); + } + + return app.UseMiddleware(); + } + } +} diff --git a/src/Microsoft.AspNetCore.Antiforgery/AntiforgeryMiddleware.cs b/src/Microsoft.AspNetCore.Antiforgery/AntiforgeryMiddleware.cs new file mode 100644 index 0000000000..eccadfd699 --- /dev/null +++ b/src/Microsoft.AspNetCore.Antiforgery/AntiforgeryMiddleware.cs @@ -0,0 +1,65 @@ +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System; +using System.Threading.Tasks; +using Microsoft.AspNetCore.Antiforgery.Internal; +using Microsoft.AspNetCore.Http; + +namespace Microsoft.AspNetCore.Antiforgery +{ + /// + /// A middleware implementation of antiforgery validation. + /// + public class AntiforgeryMiddleware + { + private readonly IAntiforgery _antiforgery; + private readonly RequestDelegate _next; + + /// + /// Creates a new . + /// + /// The for the next middleware. + /// The . + public AntiforgeryMiddleware(RequestDelegate next, IAntiforgery antiforgery) + { + if (next == null) + { + throw new ArgumentNullException(nameof(next)); + } + + if (antiforgery == null) + { + throw new ArgumentNullException(nameof(antiforgery)); + } + + _next = next; + _antiforgery = antiforgery; + } + + /// + /// Invokes the middleware for the given . + /// + /// The associated with the current request. + /// A which will be completed when execution of the middleware completes. + public async Task Invoke(HttpContext httpContext) + { + if (httpContext == null) + { + throw new ArgumentNullException(nameof(httpContext)); + } + + var handler = new AntiforgeryAuthenticationHandler(_antiforgery); + await handler.InitializeAsync(httpContext); + + try + { + await _next(httpContext); + } + finally + { + handler.Teardown(); + } + } + } +} diff --git a/src/Microsoft.AspNetCore.Antiforgery/IAntiforgery.cs b/src/Microsoft.AspNetCore.Antiforgery/IAntiforgery.cs index 6ac2e44e37..d22828ef31 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/IAntiforgery.cs +++ b/src/Microsoft.AspNetCore.Antiforgery/IAntiforgery.cs @@ -1,6 +1,7 @@ // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. +using System.Security.Claims; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; @@ -46,6 +47,18 @@ namespace Microsoft.AspNetCore.Antiforgery /// Task IsRequestValidAsync(HttpContext httpContext); + /// + /// Asynchronously returns a value indicating whether the request passes antiforgery validation. If the + /// request uses a safe HTTP method (GET, HEAD, OPTIONS, TRACE), the antiforgery token is not validated. + /// + /// The associated with the current request. + /// The claims-based principal to validate. + /// + /// A that, when completed, returns true if the is requst uses a safe HTTP + /// method or contains a value antiforgery token, otherwise returns false. + /// + Task IsRequestValidAsync(HttpContext httpContext, ClaimsPrincipal principal); + /// /// Validates an antiforgery token that was supplied as part of the request. /// @@ -55,6 +68,16 @@ namespace Microsoft.AspNetCore.Antiforgery /// Task ValidateRequestAsync(HttpContext httpContext); + /// + /// Validates an antiforgery token that was supplied as part of the request. + /// + /// The associated with the current request. + /// The claims-based principal to validate. + /// + /// Thrown when the request does not include a valid antiforgery token. + /// + Task ValidateRequestAsync(HttpContext httpContext, ClaimsPrincipal principal); + /// /// Generates and stores an antiforgery cookie token if one is not available or not valid. /// diff --git a/src/Microsoft.AspNetCore.Antiforgery/Internal/AntiforgeryAuthenticationHandler.cs b/src/Microsoft.AspNetCore.Antiforgery/Internal/AntiforgeryAuthenticationHandler.cs new file mode 100644 index 0000000000..c3abeb0ac6 --- /dev/null +++ b/src/Microsoft.AspNetCore.Antiforgery/Internal/AntiforgeryAuthenticationHandler.cs @@ -0,0 +1,161 @@ +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System; +using System.Threading.Tasks; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.Features.Authentication; +using Microsoft.AspNetCore.Http.Features.Authentication.Internal; + +namespace Microsoft.AspNetCore.Antiforgery.Internal +{ + public class AntiforgeryAuthenticationHandler : IAuthenticationHandler + { + private readonly IAntiforgery _antiforgery; + private HttpContext _httpContext; + private IAuthenticationHandler _priorHandler; + + public AntiforgeryAuthenticationHandler(IAntiforgery antiforgery) + { + if (antiforgery == null) + { + throw new ArgumentNullException(nameof(antiforgery)); + } + + _antiforgery = antiforgery; + } + + public async Task InitializeAsync(HttpContext httpContext) + { + if (httpContext == null) + { + throw new ArgumentNullException(nameof(httpContext)); + } + + _httpContext = httpContext; + + var authentication = GetAuthenticationFeature(_httpContext); + + _priorHandler = authentication.Handler; + authentication.Handler = this; + + if (authentication.User != null) + { + if (!await _antiforgery.IsRequestValidAsync(_httpContext)) + { + // Wipe out any existing principal if we can't validate this request. + authentication.User = null; + return; + } + } + } + + public void Teardown() + { + var authentication = GetAuthenticationFeature(_httpContext); + authentication.Handler = _priorHandler; + } + + /// + public async Task AuthenticateAsync(AuthenticateContext context) + { + if (context == null) + { + throw new ArgumentNullException(nameof(context)); + } + + if (_priorHandler != null) + { + await _priorHandler.AuthenticateAsync(context); + + var authentication = GetAuthenticationFeature(_httpContext); + if (context.Principal != null) + { + try + { + await _antiforgery.ValidateRequestAsync(_httpContext, context.Principal); + } + catch (AntiforgeryValidationException ex) + { + context.Failed(ex); + return; + } + } + } + } + + /// + public Task ChallengeAsync(ChallengeContext context) + { + if (context == null) + { + throw new ArgumentNullException(nameof(context)); + } + + if (_priorHandler != null) + { + return _priorHandler.ChallengeAsync(context); + } + + return TaskCache.CompletedTask; + } + + /// + public void GetDescriptions(DescribeSchemesContext context) + { + if (context == null) + { + throw new ArgumentNullException(nameof(context)); + } + + if (_priorHandler != null) + { + _priorHandler.GetDescriptions(context); + } + } + + /// + public Task SignInAsync(SignInContext context) + { + if (context == null) + { + throw new ArgumentNullException(nameof(context)); + } + + if (_priorHandler != null) + { + return _priorHandler.SignInAsync(context); + } + + return TaskCache.CompletedTask; + } + + /// + public Task SignOutAsync(SignOutContext context) + { + if (context == null) + { + throw new ArgumentNullException(nameof(context)); + } + + if (_priorHandler != null) + { + return _priorHandler.SignOutAsync(context); + } + + return TaskCache.CompletedTask; + } + + private static IHttpAuthenticationFeature GetAuthenticationFeature(HttpContext httpContext) + { + var authentication = httpContext.Features.Get(); + if (authentication == null) + { + authentication = new HttpAuthenticationFeature(); + httpContext.Features.Set(authentication); + } + + return authentication; + } + } +} diff --git a/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgery.cs b/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgery.cs index 137b0b4fe0..95f0208054 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgery.cs +++ b/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgery.cs @@ -3,6 +3,7 @@ using System; using System.Diagnostics; +using System.Security.Claims; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.DependencyInjection; @@ -85,7 +86,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal } /// - public async Task IsRequestValidAsync(HttpContext httpContext) + public Task IsRequestValidAsync(HttpContext httpContext) { if (httpContext == null) { @@ -94,13 +95,26 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal CheckSSLConfig(httpContext); - var method = httpContext.Request.Method; - if (string.Equals(method, "GET", StringComparison.OrdinalIgnoreCase) || - string.Equals(method, "HEAD", StringComparison.OrdinalIgnoreCase) || - string.Equals(method, "OPTIONS", StringComparison.OrdinalIgnoreCase) || - string.Equals(method, "TRACE", StringComparison.OrdinalIgnoreCase)) + return IsRequestValidAsync(httpContext, httpContext.User); + } + + /// + public async Task IsRequestValidAsync(HttpContext httpContext, ClaimsPrincipal principal) + { + if (httpContext == null) + { + throw new ArgumentNullException(nameof(httpContext)); + } + + if (principal == null) + { + throw new ArgumentNullException(nameof(principal)); + } + + CheckSSLConfig(httpContext); + + if (!IsValidationRequired(httpContext)) { - // Validation not needed for these request types. return true; } @@ -126,6 +140,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal string message; var result = _tokenGenerator.TryValidateTokenSet( httpContext, + principal, deserializedCookieToken, deserializedRequestToken, out message); @@ -143,7 +158,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal } /// - public async Task ValidateRequestAsync(HttpContext httpContext) + public Task ValidateRequestAsync(HttpContext httpContext) { if (httpContext == null) { @@ -152,6 +167,29 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal CheckSSLConfig(httpContext); + return ValidateRequestAsync(httpContext, httpContext.User); + } + + /// + public async Task ValidateRequestAsync(HttpContext httpContext, ClaimsPrincipal principal) + { + if (httpContext == null) + { + throw new ArgumentNullException(nameof(httpContext)); + } + + if (principal == null) + { + throw new ArgumentNullException(nameof(principal)); + } + + CheckSSLConfig(httpContext); + + if (!IsValidationRequired(httpContext)) + { + return; + } + var tokens = await _tokenStore.GetRequestTokensAsync(httpContext); if (tokens.CookieToken == null) { @@ -180,12 +218,15 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal } } - ValidateTokens(httpContext, tokens); + ValidateTokens(httpContext, principal, tokens); _logger.ValidatedAntiforgeryToken(); } - private void ValidateTokens(HttpContext httpContext, AntiforgeryTokenSet antiforgeryTokenSet) + private void ValidateTokens( + HttpContext httpContext, + ClaimsPrincipal principal, + AntiforgeryTokenSet antiforgeryTokenSet) { Debug.Assert(!string.IsNullOrEmpty(antiforgeryTokenSet.CookieToken)); Debug.Assert(!string.IsNullOrEmpty(antiforgeryTokenSet.RequestToken)); @@ -203,6 +244,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal string message; if (!_tokenGenerator.TryValidateTokenSet( httpContext, + principal, deserializedCookieToken, deserializedRequestToken, out message)) @@ -268,6 +310,21 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal } } + private bool IsValidationRequired(HttpContext httpContext) + { + var method = httpContext.Request.Method; + if (string.Equals(method, "GET", StringComparison.OrdinalIgnoreCase) || + string.Equals(method, "HEAD", StringComparison.OrdinalIgnoreCase) || + string.Equals(method, "OPTIONS", StringComparison.OrdinalIgnoreCase) || + string.Equals(method, "TRACE", StringComparison.OrdinalIgnoreCase)) + { + // Validation not needed for HTTP methods that don't mutate any state. + return false; + } + + return true; + } + private AntiforgeryContext GetCookieTokens(HttpContext httpContext) { var services = httpContext.RequestServices; @@ -340,7 +397,10 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal if (antiforgeryContext.NewRequestToken == null) { var cookieToken = antiforgeryContext.NewCookieToken ?? antiforgeryContext.CookieToken; - antiforgeryContext.NewRequestToken = _tokenGenerator.GenerateRequestToken(httpContext, cookieToken); + antiforgeryContext.NewRequestToken = _tokenGenerator.GenerateRequestToken( + httpContext, + httpContext.User, + cookieToken); } return antiforgeryContext; diff --git a/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgeryTokenGenerator.cs b/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgeryTokenGenerator.cs index 872f7ed18c..14c102bb51 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgeryTokenGenerator.cs +++ b/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgeryTokenGenerator.cs @@ -35,6 +35,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal /// public AntiforgeryToken GenerateRequestToken( HttpContext httpContext, + ClaimsPrincipal principal, AntiforgeryToken cookieToken) { if (httpContext == null) @@ -63,11 +64,11 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal var isIdentityAuthenticated = false; // populate Username and ClaimUid - var authenticatedIdentity = GetAuthenticatedIdentity(httpContext.User); + var authenticatedIdentity = GetAuthenticatedIdentity(principal); if (authenticatedIdentity != null) { isIdentityAuthenticated = true; - requestToken.ClaimUid = GetClaimUidBlob(_claimUidExtractor.ExtractClaimUid(httpContext.User)); + requestToken.ClaimUid = GetClaimUidBlob(_claimUidExtractor.ExtractClaimUid(principal)); if (requestToken.ClaimUid == null) { @@ -109,6 +110,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal /// public bool TryValidateTokenSet( HttpContext httpContext, + ClaimsPrincipal principal, AntiforgeryToken cookieToken, AntiforgeryToken requestToken, out string message) @@ -150,10 +152,10 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal var currentUsername = string.Empty; BinaryBlob currentClaimUid = null; - var authenticatedIdentity = GetAuthenticatedIdentity(httpContext.User); + var authenticatedIdentity = GetAuthenticatedIdentity(principal); if (authenticatedIdentity != null) { - currentClaimUid = GetClaimUidBlob(_claimUidExtractor.ExtractClaimUid(httpContext.User)); + currentClaimUid = GetClaimUidBlob(_claimUidExtractor.ExtractClaimUid(principal)); if (currentClaimUid == null) { currentUsername = authenticatedIdentity.Name ?? string.Empty; diff --git a/src/Microsoft.AspNetCore.Antiforgery/Internal/IAntiforgeryTokenGenerator.cs b/src/Microsoft.AspNetCore.Antiforgery/Internal/IAntiforgeryTokenGenerator.cs index c0dff86047..8c5d22cf31 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/Internal/IAntiforgeryTokenGenerator.cs +++ b/src/Microsoft.AspNetCore.Antiforgery/Internal/IAntiforgeryTokenGenerator.cs @@ -1,6 +1,7 @@ // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. +using System.Security.Claims; using Microsoft.AspNetCore.Http; namespace Microsoft.AspNetCore.Antiforgery.Internal @@ -20,9 +21,13 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal /// Generates a request token corresponding to . /// /// The associated with the current request. + /// The claims-based principal to use for token generation. /// A valid cookie token. /// An . - AntiforgeryToken GenerateRequestToken(HttpContext httpContext, AntiforgeryToken cookieToken); + AntiforgeryToken GenerateRequestToken( + HttpContext httpContext, + ClaimsPrincipal principal, + AntiforgeryToken cookieToken); /// /// Attempts to validate a cookie token. @@ -35,6 +40,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal /// Attempts to validate a cookie and request token set for the given . /// /// The associated with the current request. + /// The claims-based principal to use for token validation. /// A cookie token. /// A request token. /// @@ -43,6 +49,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal /// true if the tokens are valid, otherwise false. bool TryValidateTokenSet( HttpContext httpContext, + ClaimsPrincipal principal, AntiforgeryToken cookieToken, AntiforgeryToken requestToken, out string message); diff --git a/src/Microsoft.AspNetCore.Antiforgery/Internal/TaskCache.cs b/src/Microsoft.AspNetCore.Antiforgery/Internal/TaskCache.cs new file mode 100644 index 0000000000..d21d2e7a76 --- /dev/null +++ b/src/Microsoft.AspNetCore.Antiforgery/Internal/TaskCache.cs @@ -0,0 +1,12 @@ +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System.Threading.Tasks; + +namespace Microsoft.AspNetCore.Antiforgery.Internal +{ + public static class TaskCache + { + public static readonly Task CompletedTask = Task.FromResult(0); + } +} diff --git a/src/Microsoft.AspNetCore.Antiforgery/project.json b/src/Microsoft.AspNetCore.Antiforgery/project.json index d5bda2ecf5..4fcfc49f40 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/project.json +++ b/src/Microsoft.AspNetCore.Antiforgery/project.json @@ -13,8 +13,7 @@ }, "dependencies": { "Microsoft.AspNetCore.DataProtection": "1.0.0-*", - "Microsoft.AspNetCore.Http.Abstractions": "1.0.0-*", - "Microsoft.AspNetCore.WebUtilities": "1.0.0-*", + "Microsoft.AspNetCore.Http": "1.0.0-*", "Microsoft.Extensions.ObjectPool": "1.0.0-*" }, "frameworks": { diff --git a/test/Microsoft.AspNetCore.Antiforgery.Test/AntiforgeryMiddlewareTest.cs b/test/Microsoft.AspNetCore.Antiforgery.Test/AntiforgeryMiddlewareTest.cs new file mode 100644 index 0000000000..56c606c847 --- /dev/null +++ b/test/Microsoft.AspNetCore.Antiforgery.Test/AntiforgeryMiddlewareTest.cs @@ -0,0 +1,382 @@ +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System; +using System.Security.Claims; +using System.Threading.Tasks; +using Microsoft.AspNetCore.Antiforgery.Internal; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Builder.Internal; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.Features.Authentication; +using Microsoft.AspNetCore.Http.Features.Authentication.Internal; +using Microsoft.AspNetCore.Http.Internal; +using Microsoft.Extensions.DependencyInjection; +using Moq; +using Xunit; + +namespace Microsoft.AspNetCore.Antiforgery +{ + // These are really more like integration tests and just verify a bunch of different + // reasonable combinations of authN middleware. + public class AntiforgeryMiddlewareTest + { + private readonly ClaimsPrincipal LoggedInUser = new ClaimsPrincipal(new ClaimsIdentity[] + { + new ClaimsIdentity("Test"), + }); + + private readonly ClaimsPrincipal LoggedInUser2 = new ClaimsPrincipal(new ClaimsIdentity[] + { + new ClaimsIdentity("Test"), + }); + + [Fact] + public async Task AutomaticAuthentication_Anonymous() + { + // Arrange + var context = Setup((app) => + { + app.Use(next => new AutomaticAuthenticationMiddleware(next, null).Invoke); + app.UseAntiforgery(); + }); + + var httpContext = new DefaultHttpContext(); + + await context.AppFunc(httpContext); + + Assert.Null(context.Principal); + } + + [Fact] + public async Task AutomaticAuthentication_LoggedIn_WithoutToken() + { + // Arrange + var context = Setup((app) => + { + app.UseMiddleware(LoggedInUser); + app.UseAntiforgery(); + }); + + context.Antiforgery + .Setup(a => a.IsRequestValidAsync(It.IsAny())) + .ReturnsAsync(false); + + var httpContext = new DefaultHttpContext(); + + await context.AppFunc(httpContext); + + Assert.Null(context.Principal); + } + + [Fact] + public async Task AutomaticAuthentication_LoggedIn_WithValidToken() + { + // Arrange + var context = Setup((app) => + { + app.UseMiddleware(LoggedInUser); + app.UseAntiforgery(); + }); + + context.Antiforgery + .Setup(a => a.IsRequestValidAsync(It.IsAny())) + .ReturnsAsync(true); + + var httpContext = new DefaultHttpContext(); + + await context.AppFunc(httpContext); + + Assert.Same(LoggedInUser, context.Principal); + } + + // A middleware after antiforgery in the pipeline can authenticate without going through token + // validation. + [Fact] + public async Task AutomaticAuthentication_LoggedIn_WithoutToken_AuthenticatedBySubsequentMiddleware() + { + // Arrange + var context = Setup((app) => + { + app.UseMiddleware(LoggedInUser); + app.UseAntiforgery(); + app.UseMiddleware(LoggedInUser2); + }); + + context.Antiforgery + .Setup(a => a.IsRequestValidAsync(It.IsAny())) + .ReturnsAsync(false); + + var httpContext = new DefaultHttpContext(); + + await context.AppFunc(httpContext); + + Assert.Same(LoggedInUser2, context.Principal); + } + + [Fact] + public async Task PasiveAuthentication_Anonymous() + { + // Arrange + var context = Setup((app) => + { + app.Use(next => new AuthenticationHandlerMiddleware(next, null).Invoke); + app.UseAntiforgery(); + app.UseMiddleware(); + }); + + var httpContext = new DefaultHttpContext(); + + await context.AppFunc(httpContext); + + Assert.Null(context.Principal); + } + + [Fact] + public async Task PassiveAuthentication_LoggedIn_WithoutToken() + { + // Arrange + var context = Setup((app) => + { + app.UseMiddleware(LoggedInUser); + app.UseAntiforgery(); + app.UseMiddleware(); + }); + + context.Antiforgery + .Setup(a => a.ValidateRequestAsync(It.IsAny(), LoggedInUser)) + .Throws(new AntiforgeryValidationException("error")); + + var httpContext = new DefaultHttpContext(); + + await context.AppFunc(httpContext); + + Assert.Null(context.Principal); + } + + [Fact] + public async Task PassiveAuthentication_LoggedIn_WithValidToken() + { + // Arrange + var context = Setup((app) => + { + app.UseMiddleware(LoggedInUser); + app.UseAntiforgery(); + app.UseMiddleware(); + }); + + context.Antiforgery + .Setup(a => a.ValidateRequestAsync(It.IsAny(), LoggedInUser)) + .Returns(TaskCache.CompletedTask); + + var httpContext = new DefaultHttpContext(); + + await context.AppFunc(httpContext); + + Assert.Same(LoggedInUser, context.Principal); + } + + // A middleware after antiforgery in the pipeline can authenticate without going through token + // validation. + [Fact] + public async Task PassiveAuthentication_LoggedIn_WithoutToken_AuthenticatedBySubsequentMiddleware() + { + // Arrange + var context = Setup((app) => + { + app.UseMiddleware(LoggedInUser); + app.UseAntiforgery(); + app.UseMiddleware(LoggedInUser2); + app.UseMiddleware(); + }); + + var httpContext = new DefaultHttpContext(); + + await context.AppFunc(httpContext); + + Assert.Same(LoggedInUser2, context.Principal); + } + + private static IHttpAuthenticationFeature GetAuthenticationFeature(HttpContext httpContext) + { + var authentication = httpContext.Features.Get(); + if (authentication == null) + { + authentication = new HttpAuthenticationFeature(); + httpContext.Features.Set(authentication); + } + + return authentication; + } + + private static TestContext Setup(Action action) + { + var services = new ServiceCollection(); + services.AddLogging(); + services.AddOptions(); + + var antiforgery = new Mock(MockBehavior.Strict); + services.AddSingleton(antiforgery.Object); + + var result = new TestContext(); + result.Antiforgery = antiforgery; + + var app = new ApplicationBuilder(services.BuildServiceProvider()); + action(app); + + // Capture the logged in user 'after' the middleware so we can validate it. + app.Run(c => + { + result.Principal = GetAuthenticationFeature(c).User; + return TaskCache.CompletedTask; + }); + + result.AppFunc = app.Build(); + return result; + } + + private class TestContext + { + public Mock Antiforgery { get; set; } + + public RequestDelegate AppFunc { get; set; } + + public ClaimsPrincipal Principal { get; set; } + } + + private class AutomaticAuthenticationMiddleware + { + private readonly RequestDelegate _next; + private readonly ClaimsPrincipal _principal; + + public AutomaticAuthenticationMiddleware(RequestDelegate next, ClaimsPrincipal principal) + { + _next = next; + _principal = principal; + } + + public Task Invoke(HttpContext httpContext) + { + GetAuthenticationFeature(httpContext).User = _principal; + return _next(httpContext); + } + } + + private class AuthenticationHandlerMiddleware + { + private readonly RequestDelegate _next; + private readonly ClaimsPrincipal _principal; + + public AuthenticationHandlerMiddleware(RequestDelegate next, ClaimsPrincipal principal) + { + _next = next; + _principal = principal; + } + + public async Task Invoke(HttpContext httpContext) + { + var handler = new AuthenticationHandler(_principal); + await handler.InitializeAsync(httpContext); + + try + { + await _next(httpContext); + } + finally + { + await handler.TeardownAsync(); + } + } + } + + private class AuthenticationHandler : IAuthenticationHandler + { + private readonly ClaimsPrincipal _principal; + private IAuthenticationHandler _priorHandler; + private HttpContext _httpContext; + + public AuthenticationHandler(ClaimsPrincipal principal) + { + _principal = principal; + } + + public Task InitializeAsync(HttpContext httpContext) + { + _httpContext = httpContext; + + var authenticationFeature = GetAuthenticationFeature(_httpContext); + _priorHandler = authenticationFeature.Handler; + authenticationFeature.Handler = this; + + return TaskCache.CompletedTask; + } + + public Task TeardownAsync() + { + var authenticationFeature = GetAuthenticationFeature(_httpContext); + authenticationFeature.Handler = _priorHandler; + + return TaskCache.CompletedTask; + } + + public Task AuthenticateAsync(AuthenticateContext context) + { + if (_principal == null) + { + context.NotAuthenticated(); + } + else + { + context.Authenticated(_principal, null, null); + } + + return TaskCache.CompletedTask; + } + + public Task ChallengeAsync(ChallengeContext context) + { + throw new NotImplementedException(); + } + + public void GetDescriptions(DescribeSchemesContext context) + { + throw new NotImplementedException(); + } + + public Task SignInAsync(SignInContext context) + { + throw new NotImplementedException(); + } + + public Task SignOutAsync(SignOutContext context) + { + throw new NotImplementedException(); + } + } + + private class CallAuthenticateMiddleware + { + private readonly RequestDelegate _next; + + public CallAuthenticateMiddleware(RequestDelegate next) + { + _next = next; + } + + public async Task Invoke(HttpContext httpContext) + { + var authenticationFeature = GetAuthenticationFeature(httpContext); + + var authenticateContext = new AuthenticateContext("Test"); + await httpContext.Authentication.AuthenticateAsync(authenticateContext); + + if (authenticateContext.Accepted) + { + authenticationFeature.User = authenticateContext.Principal; + } + + await _next(httpContext); + } + } + } +} diff --git a/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/AntiforgeryAuthenticationHandlerTest.cs b/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/AntiforgeryAuthenticationHandlerTest.cs new file mode 100644 index 0000000000..670f818bf7 --- /dev/null +++ b/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/AntiforgeryAuthenticationHandlerTest.cs @@ -0,0 +1,293 @@ +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System.Security.Claims; +using System.Threading.Tasks; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.Features.Authentication; +using Microsoft.AspNetCore.Http.Features.Authentication.Internal; +using Microsoft.AspNetCore.Http.Internal; +using Moq; +using Xunit; + +namespace Microsoft.AspNetCore.Antiforgery.Internal +{ + public class AntiforgeryAuthenticationHandlerTest + { + [Fact] + public async Task IntializeAsync_NoOp_WhenAnonymous() + { + // Arrange + var antiforgery = new Mock(MockBehavior.Strict); + var handler = new AntiforgeryAuthenticationHandler(antiforgery.Object); + + antiforgery + .Setup(a => a.IsRequestValidAsync(It.IsAny())) + .ReturnsAsync(false) + .Verifiable(); + + var httpContext = new DefaultHttpContext(); + + // Act + await handler.InitializeAsync(httpContext); + + // Assert + antiforgery.Verify(a => a.IsRequestValidAsync(It.IsAny()), Times.Never()); + } + + [Fact] + public async Task IntializeAsync_ValidatesRequest_WhenLoggedIn() + { + // Arrange + var antiforgery = new Mock(MockBehavior.Strict); + var handler = new AntiforgeryAuthenticationHandler(antiforgery.Object); + + antiforgery + .Setup(a => a.IsRequestValidAsync(It.IsAny())) + .ReturnsAsync(true) + .Verifiable(); + + var httpContext = new DefaultHttpContext(); + + var authenticationFeature = new HttpAuthenticationFeature(); + httpContext.Features.Set(authenticationFeature); + authenticationFeature.User = new ClaimsPrincipal(); + + // Act + await handler.InitializeAsync(httpContext); + + // Assert + antiforgery.Verify(a => a.IsRequestValidAsync(It.IsAny()), Times.Once()); + } + + [Fact] + public async Task IntializeAsync_ClearsUser_WhenInvalid() + { + // Arrange + var antiforgery = new Mock(MockBehavior.Strict); + var handler = new AntiforgeryAuthenticationHandler(antiforgery.Object); + + antiforgery + .Setup(a => a.IsRequestValidAsync(It.IsAny())) + .ReturnsAsync(false) + .Verifiable(); + + var httpContext = new DefaultHttpContext(); + + var authenticationFeature = new HttpAuthenticationFeature(); + httpContext.Features.Set(authenticationFeature); + authenticationFeature.User = new ClaimsPrincipal(); + + // Act + await handler.InitializeAsync(httpContext); + + // Assert + Assert.Null(authenticationFeature.User); + antiforgery.Verify(a => a.IsRequestValidAsync(It.IsAny()), Times.Once()); + } + + [Fact] + public async Task IntializeAsync_AttachesAuthorizationHandler() + { + // Arrange + var antiforgery = new Mock(MockBehavior.Strict); + var handler = new AntiforgeryAuthenticationHandler(antiforgery.Object); + + antiforgery + .Setup(a => a.IsRequestValidAsync(It.IsAny())) + .ReturnsAsync(false) + .Verifiable(); + + var httpContext = new DefaultHttpContext(); + + var authenticationFeature = new HttpAuthenticationFeature(); + httpContext.Features.Set(authenticationFeature); + + // Act + await handler.InitializeAsync(httpContext); + + // Assert + Assert.Same(handler, authenticationFeature.Handler); + antiforgery.Verify(a => a.IsRequestValidAsync(It.IsAny()), Times.Never()); + } + + [Fact] + public async Task AuthenticateAsync_NoPriorHandler_NoOp() + { + // Arrange + var antiforgery = new Mock(MockBehavior.Strict); + var handler = new AntiforgeryAuthenticationHandler(antiforgery.Object); + + antiforgery + .Setup(a => a.IsRequestValidAsync(It.IsAny())) + .ReturnsAsync(false) + .Verifiable(); + + antiforgery + .Setup(a => a.ValidateRequestAsync(It.IsAny(), It.IsAny())) + .Verifiable(); + + var httpContext = new DefaultHttpContext(); + + var authenticationFeature = new HttpAuthenticationFeature(); + httpContext.Features.Set(authenticationFeature); + + await handler.InitializeAsync(httpContext); + + var authenticateContext = new AuthenticateContext("Test"); + + // Act + await handler.AuthenticateAsync(authenticateContext); + + // Assert + Assert.False(authenticateContext.Accepted); + + antiforgery.Verify(a => a.IsRequestValidAsync(It.IsAny()), Times.Never()); + antiforgery.Verify( + a => a.ValidateRequestAsync(It.IsAny(), It.IsAny()), + Times.Never()); + } + + [Fact] + public async Task AuthenticateAsync_PriorHandlerDoesNotAuthenticate_NoOp() + { + // Arrange + var antiforgery = new Mock(MockBehavior.Strict); + var handler = new AntiforgeryAuthenticationHandler(antiforgery.Object); + + antiforgery + .Setup(a => a.IsRequestValidAsync(It.IsAny())) + .ReturnsAsync(false) + .Verifiable(); + + antiforgery + .Setup(a => a.ValidateRequestAsync(It.IsAny(), It.IsAny())) + .Verifiable(); + + var httpContext = new DefaultHttpContext(); + + var authenticationFeature = new HttpAuthenticationFeature(); + httpContext.Features.Set(authenticationFeature); + var priorHandler = new Mock(MockBehavior.Strict); + authenticationFeature.Handler = priorHandler.Object; + + priorHandler + .Setup(h => h.AuthenticateAsync(It.IsAny())) + .Returns(TaskCache.CompletedTask) + .Callback(c => c.NotAuthenticated()); + + await handler.InitializeAsync(httpContext); + + var authenticateContext = new AuthenticateContext("Test"); + + // Act + await handler.AuthenticateAsync(authenticateContext); + + // Assert + Assert.True(authenticateContext.Accepted); + Assert.Null(authenticateContext.Principal); + + antiforgery.Verify(a => a.IsRequestValidAsync(It.IsAny()), Times.Never()); + antiforgery.Verify( + a => a.ValidateRequestAsync(It.IsAny(), It.IsAny()), + Times.Never()); + } + + [Fact] + public async Task AuthenticateAsync_PriorHandlerSetsPrincipal_Valid() + { + // Arrange + var antiforgery = new Mock(MockBehavior.Strict); + var handler = new AntiforgeryAuthenticationHandler(antiforgery.Object); + + var principal = new ClaimsPrincipal(); + + antiforgery + .Setup(a => a.IsRequestValidAsync(It.IsAny())) + .ReturnsAsync(false) + .Verifiable(); + + antiforgery + .Setup(a => a.ValidateRequestAsync(It.IsAny(), principal)) + .Returns(TaskCache.CompletedTask) + .Verifiable(); + + var httpContext = new DefaultHttpContext(); + + var authenticationFeature = new HttpAuthenticationFeature(); + httpContext.Features.Set(authenticationFeature); + var priorHandler = new Mock(MockBehavior.Strict); + authenticationFeature.Handler = priorHandler.Object; + + priorHandler + .Setup(h => h.AuthenticateAsync(It.IsAny())) + .Returns(TaskCache.CompletedTask) + .Callback(c => c.Authenticated(principal, null, null)); + + await handler.InitializeAsync(httpContext); + + var authenticateContext = new AuthenticateContext("Test"); + + // Act + await handler.AuthenticateAsync(authenticateContext); + + // Assert + Assert.True(authenticateContext.Accepted); + Assert.Same(principal, authenticateContext.Principal); + + antiforgery.Verify(a => a.IsRequestValidAsync(It.IsAny()), Times.Never()); + antiforgery.Verify( + a => a.ValidateRequestAsync(It.IsAny(), principal), + Times.Once()); + } + + [Fact] + public async Task AuthenticateAsync_PriorHandlerSetsPrincipal_Invalid() + { + // Arrange + var antiforgery = new Mock(MockBehavior.Strict); + var handler = new AntiforgeryAuthenticationHandler(antiforgery.Object); + + var principal = new ClaimsPrincipal(); + + antiforgery + .Setup(a => a.IsRequestValidAsync(It.IsAny())) + .ReturnsAsync(false) + .Verifiable(); + + antiforgery + .Setup(a => a.ValidateRequestAsync(It.IsAny(), principal)) + .Throws(new AntiforgeryValidationException("invalid")) + .Verifiable(); + + var httpContext = new DefaultHttpContext(); + + var authenticationFeature = new HttpAuthenticationFeature(); + httpContext.Features.Set(authenticationFeature); + var priorHandler = new Mock(MockBehavior.Strict); + authenticationFeature.Handler = priorHandler.Object; + + priorHandler + .Setup(h => h.AuthenticateAsync(It.IsAny())) + .Returns(TaskCache.CompletedTask) + .Callback(c => c.Authenticated(principal, null, null)); + + await handler.InitializeAsync(httpContext); + + var authenticateContext = new AuthenticateContext("Test"); + + // Act + await handler.AuthenticateAsync(authenticateContext); + + // Assert + Assert.True(authenticateContext.Accepted); + Assert.Null(authenticateContext.Principal); + Assert.NotNull(authenticateContext.Error); + + antiforgery.Verify(a => a.IsRequestValidAsync(It.IsAny()), Times.Never()); + antiforgery.Verify( + a => a.ValidateRequestAsync(It.IsAny(), principal), + Times.Once()); + } + } +} diff --git a/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTest.cs b/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTest.cs index 670b7f607b..2d10221a41 100644 --- a/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTest.cs +++ b/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTest.cs @@ -16,6 +16,22 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal { public class DefaultAntiforgeryTest { + public static TheoryData SafeHttpMethods => new TheoryData() + { + "GeT", + "HEAD", + "options", + "TrAcE", + }; + + public static TheoryData UnsafeHttpMethods => new TheoryData() + { + "PUT", + "post", + "Delete", + "Custom", + }; + [Fact] public async Task ChecksSSL_ValidateRequestAsync_Throws() { @@ -36,6 +52,26 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal exception.Message); } + [Fact] + public async Task ChecksSSL_ValidateRequestAsync_WithPrincipal_Throws() + { + // Arrange + var httpContext = GetHttpContext(); + var options = new AntiforgeryOptions() + { + RequireSsl = true + }; + var antiforgery = GetAntiforgery(httpContext, options); + + // Act & Assert + var exception = await Assert.ThrowsAsync( + () => antiforgery.ValidateRequestAsync(httpContext, new ClaimsPrincipal())); + Assert.Equal( + @"The antiforgery system has the configuration value AntiforgeryOptions.RequireSsl = true, " + + "but the current request is not an SSL request.", + exception.Message); + } + [Fact] public async Task ChecksSSL_IsRequestValidAsync_Throws() { @@ -57,6 +93,27 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal exception.Message); } + [Fact] + public async Task ChecksSSL_IsRequestValidAsync_WithPrincipal_Throws() + { + // Arrange + var httpContext = GetHttpContext(); + var options = new AntiforgeryOptions() + { + RequireSsl = true + }; + + var antiforgery = GetAntiforgery(httpContext, options); + + // Act & Assert + var exception = await Assert.ThrowsAsync( + () => antiforgery.IsRequestValidAsync(httpContext, new ClaimsPrincipal())); + Assert.Equal( + @"The antiforgery system has the configuration value AntiforgeryOptions.RequireSsl = true, " + + "but the current request is not an SSL request.", + exception.Message); + } + [Fact] public void ChecksSSL_GetAndStoreTokens_Throws() { @@ -420,6 +477,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal context.TokenGenerator .Setup(o => o.TryValidateTokenSet( context.HttpContext, + It.IsAny(), context.TestTokenSet.OldCookieToken, context.TestTokenSet.RequestToken, out message)) @@ -454,6 +512,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal context.TokenGenerator .Setup(o => o.TryValidateTokenSet( context.HttpContext, + It.IsAny(), context.TestTokenSet.OldCookieToken, context.TestTokenSet.RequestToken, out message)) @@ -497,6 +556,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal context.TokenGenerator .Setup(o => o.TryValidateTokenSet( context.HttpContext, + It.IsAny(), contextAccessor.Value.CookieToken, contextAccessor.Value.RequestToken, out message)) @@ -522,10 +582,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal } [Theory] - [InlineData("GeT")] - [InlineData("HEAD")] - [InlineData("options")] - [InlineData("TrAcE")] + [MemberData(nameof(SafeHttpMethods))] public async Task IsRequestValidAsync_SkipsAntiforgery_ForSafeHttpMethods(string httpMethod) { // Arrange @@ -536,6 +593,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal context.TokenGenerator .Setup(o => o.TryValidateTokenSet( context.HttpContext, + It.IsAny(), It.IsAny(), It.IsAny(), out message)) @@ -552,6 +610,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal context.TokenGenerator .Verify(o => o.TryValidateTokenSet( context.HttpContext, + It.IsAny(), It.IsAny(), It.IsAny(), out message), @@ -559,10 +618,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal } [Theory] - [InlineData("PUT")] - [InlineData("post")] - [InlineData("Delete")] - [InlineData("Custom")] + [MemberData(nameof(UnsafeHttpMethods))] public async Task IsRequestValidAsync_ValidatesAntiforgery_ForNonSafeHttpMethods(string httpMethod) { // Arrange @@ -573,6 +629,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal context.TokenGenerator .Setup(o => o.TryValidateTokenSet( context.HttpContext, + It.IsAny(), It.IsAny(), It.IsAny(), out message)) @@ -589,6 +646,68 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal context.TokenGenerator.Verify(); } + [Fact] + public async Task IsRequestValidAsync_UsesPrincipalFromHttpContext() + { + // Arrange + var context = CreateMockContext(new AntiforgeryOptions()); + context.HttpContext.Request.Method = "POST"; + + var principal = new ClaimsPrincipal(); + context.HttpContext.User = principal; + + string message; + context.TokenGenerator + .Setup(o => o.TryValidateTokenSet( + context.HttpContext, + principal, + It.IsAny(), + It.IsAny(), + out message)) + .Returns(true) + .Verifiable(); + + var antiforgery = GetAntiforgery(context); + + // Act + var result = await antiforgery.IsRequestValidAsync(context.HttpContext); + + // Assert + Assert.True(result); + context.TokenGenerator.Verify(); + } + + [Fact] + public async Task IsRequestValidAsync_UsesPassedInPrincipal() + { + // Arrange + var context = CreateMockContext(new AntiforgeryOptions()); + context.HttpContext.Request.Method = "POST"; + + var principal = new ClaimsPrincipal(); + context.HttpContext.User = new ClaimsPrincipal(); // This should be ignored. + + string message; + context.TokenGenerator + .Setup(o => o.TryValidateTokenSet( + context.HttpContext, + principal, + It.IsAny(), + It.IsAny(), + out message)) + .Returns(true) + .Verifiable(); + + var antiforgery = GetAntiforgery(context); + + // Act + var result = await antiforgery.IsRequestValidAsync(context.HttpContext, principal); + + // Assert + Assert.True(result); + context.TokenGenerator.Verify(); + } + [Fact] public async Task ValidateRequestAsync_FromStore_Failure() { @@ -600,6 +719,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal context.TokenGenerator .Setup(o => o.TryValidateTokenSet( context.HttpContext, + It.IsAny(), context.TestTokenSet.OldCookieToken, context.TestTokenSet.RequestToken, out message)) @@ -632,6 +752,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal context.TokenGenerator .Setup(o => o.TryValidateTokenSet( context.HttpContext, + It.IsAny(), context.TestTokenSet.OldCookieToken, context.TestTokenSet.RequestToken, out message)) @@ -776,6 +897,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal context.TokenGenerator .Setup(o => o.TryValidateTokenSet( context.HttpContext, + It.IsAny(), contextAccessor.Value.CookieToken, contextAccessor.Value.RequestToken, out message)) @@ -799,6 +921,129 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal Times.Never); } + [Theory] + [MemberData(nameof(SafeHttpMethods))] + public async Task ValidateRequestAsync_SkipsAntiforgery_ForSafeHttpMethods(string httpMethod) + { + // Arrange + var context = CreateMockContext(new AntiforgeryOptions()); + context.HttpContext.Request.Method = httpMethod; + + string message; + context.TokenGenerator + .Setup(o => o.TryValidateTokenSet( + context.HttpContext, + It.IsAny(), + It.IsAny(), + It.IsAny(), + out message)) + .Returns(false) + .Verifiable(); + + var antiforgery = GetAntiforgery(context); + + // Act + await antiforgery.ValidateRequestAsync(context.HttpContext); + + // Assert + context.TokenGenerator + .Verify(o => o.TryValidateTokenSet( + context.HttpContext, + It.IsAny(), + It.IsAny(), + It.IsAny(), + out message), + Times.Never); + } + + [Theory] + [MemberData(nameof(UnsafeHttpMethods))] + public async Task ValidateRequestAsync_ValidatesAntiforgery_ForNonSafeHttpMethods(string httpMethod) + { + // Arrange + var context = CreateMockContext(new AntiforgeryOptions()); + context.HttpContext.Request.Method = httpMethod; + + string message; + context.TokenGenerator + .Setup(o => o.TryValidateTokenSet( + context.HttpContext, + It.IsAny(), + It.IsAny(), + It.IsAny(), + out message)) + .Returns(true) + .Verifiable(); + + var antiforgery = GetAntiforgery(context); + + // Act + await antiforgery.ValidateRequestAsync(context.HttpContext); + + // Assert + context.TokenGenerator.Verify(); + } + + [Fact] + public async Task ValidateRequestAsync_UsesPrincipalFromHttpContext() + { + // Arrange + var context = CreateMockContext(new AntiforgeryOptions()); + context.HttpContext.Request.Method = "POST"; + + var principal = new ClaimsPrincipal(); + context.HttpContext.User = principal; + + string message; + context.TokenGenerator + .Setup(o => o.TryValidateTokenSet( + context.HttpContext, + principal, + It.IsAny(), + It.IsAny(), + out message)) + .Returns(true) + .Verifiable(); + + var antiforgery = GetAntiforgery(context); + + // Act + await antiforgery.ValidateRequestAsync(context.HttpContext); + + // Assert + context.TokenGenerator.Verify(); + } + + [Fact] + public async Task ValidateRequestAsync_UsesPassedInPrincipal() + { + // Arrange + var context = CreateMockContext(new AntiforgeryOptions()); + context.HttpContext.Request.Method = "POST"; + + var principal = new ClaimsPrincipal(); + context.HttpContext.User = new ClaimsPrincipal(); // This should be ignored. + + string message; + context.TokenGenerator + .Setup(o => o.TryValidateTokenSet( + context.HttpContext, + principal, + It.IsAny(), + It.IsAny(), + out message)) + .Returns(true) + .Verifiable(); + + var antiforgery = GetAntiforgery(context); + + // Act + await antiforgery.ValidateRequestAsync(context.HttpContext, principal); + + // Assert + context.TokenGenerator.Verify(); + } + [Theory] [InlineData(false, "SAMEORIGIN")] [InlineData(true, null)] @@ -1045,6 +1290,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal mockGenerator .Setup(o => o.GenerateRequestToken( httpContext, + It.IsAny(), useOldCookie ? testTokenSet.OldCookieToken : testTokenSet.NewCookieToken)) .Returns(testTokenSet.RequestToken); diff --git a/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTokenGeneratorTest.cs b/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTokenGeneratorTest.cs index 5509726a38..1720d93b95 100644 --- a/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTokenGeneratorTest.cs +++ b/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTokenGeneratorTest.cs @@ -35,7 +35,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal // Arrange var cookieToken = new AntiforgeryToken() { IsCookieToken = false }; var httpContext = new DefaultHttpContext(); - httpContext.User = new ClaimsPrincipal(new ClaimsIdentity()); + var principal = new ClaimsPrincipal(new ClaimsIdentity()); Assert.False(httpContext.User.Identity.IsAuthenticated); var tokenProvider = new DefaultAntiforgeryTokenGenerator( @@ -44,7 +44,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal // Act & Assert ExceptionAssert.ThrowsArgument( - () => tokenProvider.GenerateRequestToken(httpContext, cookieToken), + () => tokenProvider.GenerateRequestToken(httpContext, principal, cookieToken), "cookieToken", "The antiforgery cookie token is invalid."); } @@ -55,7 +55,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal // Arrange var cookieToken = new AntiforgeryToken() { IsCookieToken = true }; var httpContext = new DefaultHttpContext(); - httpContext.User = new ClaimsPrincipal(new ClaimsIdentity()); + var principal = new ClaimsPrincipal(new ClaimsIdentity()); Assert.False(httpContext.User.Identity.IsAuthenticated); var tokenProvider = new DefaultAntiforgeryTokenGenerator( @@ -63,7 +63,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal additionalDataProvider: null); // Act - var fieldToken = tokenProvider.GenerateRequestToken(httpContext, cookieToken); + var fieldToken = tokenProvider.GenerateRequestToken(httpContext, principal, cookieToken); // Assert Assert.NotNull(fieldToken); @@ -84,7 +84,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal }; var httpContext = new DefaultHttpContext(); - httpContext.User = new ClaimsPrincipal(new MyAuthenticatedIdentityWithoutUsername()); + var principal = new ClaimsPrincipal(new MyAuthenticatedIdentityWithoutUsername()); var options = new AntiforgeryOptions(); var claimUidExtractor = new Mock().Object; @@ -95,7 +95,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal // Act & assert var exception = Assert.Throws( - () => tokenProvider.GenerateRequestToken(httpContext, cookieToken)); + () => tokenProvider.GenerateRequestToken(httpContext, principal, cookieToken)); Assert.Equal( "The provided identity of type " + $"'{typeof(MyAuthenticatedIdentityWithoutUsername).FullName}' " + @@ -115,7 +115,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal var cookieToken = new AntiforgeryToken() { IsCookieToken = true }; var httpContext = new DefaultHttpContext(); - httpContext.User = new ClaimsPrincipal(new MyAuthenticatedIdentityWithoutUsername()); + var principal = new ClaimsPrincipal(new MyAuthenticatedIdentityWithoutUsername()); var mockAdditionalDataProvider = new Mock(); mockAdditionalDataProvider.Setup(o => o.GetAdditionalData(httpContext)) @@ -128,7 +128,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal additionalDataProvider: mockAdditionalDataProvider.Object); // Act - var fieldToken = tokenProvider.GenerateRequestToken(httpContext, cookieToken); + var fieldToken = tokenProvider.GenerateRequestToken(httpContext, principal, cookieToken); // Assert Assert.NotNull(fieldToken); @@ -147,7 +147,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal var identity = GetAuthenticatedIdentity("some-identity"); var httpContext = new DefaultHttpContext(); - httpContext.User = new ClaimsPrincipal(identity); + var principal = new ClaimsPrincipal(identity); byte[] data = new byte[256 / 8]; using (var rng = RandomNumberGenerator.Create()) @@ -166,7 +166,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal additionalDataProvider: null); // Act - var fieldToken = tokenProvider.GenerateRequestToken(httpContext, cookieToken); + var fieldToken = tokenProvider.GenerateRequestToken(httpContext, principal, cookieToken); // Assert Assert.NotNull(fieldToken); @@ -190,7 +190,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal mockIdentity.Setup(o => o.Name) .Returns("my-username"); - httpContext.User = new ClaimsPrincipal(mockIdentity.Object); + var principal = new ClaimsPrincipal(mockIdentity.Object); var claimUidExtractor = new Mock().Object; @@ -199,7 +199,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal additionalDataProvider: null); // Act - var fieldToken = tokenProvider.GenerateRequestToken(httpContext, cookieToken); + var fieldToken = tokenProvider.GenerateRequestToken(httpContext, principal, cookieToken); // Assert Assert.NotNull(fieldToken); @@ -272,7 +272,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal { // Arrange var httpContext = new DefaultHttpContext(); - httpContext.User = new ClaimsPrincipal(new ClaimsIdentity()); + var principal = new ClaimsPrincipal(new ClaimsIdentity()); var fieldtoken = new AntiforgeryToken() { IsCookieToken = false }; @@ -283,7 +283,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal // Act & Assert string message; var ex = Assert.Throws( - () => tokenProvider.TryValidateTokenSet(httpContext, null, fieldtoken, out message)); + () => tokenProvider.TryValidateTokenSet(httpContext, principal, null, fieldtoken, out message)); var trimmed = ex.Message.Substring(0, ex.Message.IndexOf(Environment.NewLine)); Assert.Equal(@"The required antiforgery cookie token must be provided.", trimmed); @@ -294,7 +294,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal { // Arrange var httpContext = new DefaultHttpContext(); - httpContext.User = new ClaimsPrincipal(new ClaimsIdentity()); + var principal = new ClaimsPrincipal(new ClaimsIdentity()); var cookieToken = new AntiforgeryToken() { IsCookieToken = true }; @@ -306,7 +306,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal // Act & Assert string message; var ex = Assert.Throws( - () => tokenProvider.TryValidateTokenSet(httpContext, cookieToken, null, out message)); + () => tokenProvider.TryValidateTokenSet(httpContext, principal, cookieToken, null, out message)); var trimmed = ex.Message.Substring(0, ex.Message.IndexOf(Environment.NewLine)); Assert.Equal("The required antiforgery request token must be provided.", trimmed); @@ -317,7 +317,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal { // Arrange var httpContext = new DefaultHttpContext(); - httpContext.User = new ClaimsPrincipal(new ClaimsIdentity()); + var principal = new ClaimsPrincipal(new ClaimsIdentity()); var cookieToken = new AntiforgeryToken() { IsCookieToken = true }; var fieldtoken = new AntiforgeryToken() { IsCookieToken = false }; @@ -332,7 +332,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal // Act string message; - var result = tokenProvider.TryValidateTokenSet(httpContext, fieldtoken, fieldtoken, out message); + var result = tokenProvider.TryValidateTokenSet(httpContext, principal, fieldtoken, fieldtoken, out message); // Assert Assert.False(result); @@ -344,7 +344,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal { // Arrange var httpContext = new DefaultHttpContext(); - httpContext.User = new ClaimsPrincipal(new ClaimsIdentity()); + var principal = new ClaimsPrincipal(new ClaimsIdentity()); var cookieToken = new AntiforgeryToken() { IsCookieToken = true }; var fieldtoken = new AntiforgeryToken() { IsCookieToken = false }; @@ -359,7 +359,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal // Act string message; - var result = tokenProvider.TryValidateTokenSet(httpContext, cookieToken, cookieToken, out message); + var result = tokenProvider.TryValidateTokenSet(httpContext, principal, cookieToken, cookieToken, out message); // Assert Assert.False(result); @@ -371,7 +371,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal { // Arrange var httpContext = new DefaultHttpContext(); - httpContext.User = new ClaimsPrincipal(new ClaimsIdentity()); + var principal = new ClaimsPrincipal(new ClaimsIdentity()); var cookieToken = new AntiforgeryToken() { IsCookieToken = true }; var fieldtoken = new AntiforgeryToken() { IsCookieToken = false }; @@ -384,7 +384,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal // Act string message; - var result = tokenProvider.TryValidateTokenSet(httpContext, cookieToken, fieldtoken, out message); + var result = tokenProvider.TryValidateTokenSet(httpContext, principal, cookieToken, fieldtoken, out message); // Assert Assert.False(result); @@ -400,7 +400,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal // Arrange var httpContext = new DefaultHttpContext(); var identity = GetAuthenticatedIdentity(identityUsername); - httpContext.User = new ClaimsPrincipal(identity); + var principal = new ClaimsPrincipal(identity); var cookieToken = new AntiforgeryToken() { IsCookieToken = true }; var fieldtoken = new AntiforgeryToken() @@ -424,7 +424,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal // Act string message; - var result = tokenProvider.TryValidateTokenSet(httpContext, cookieToken, fieldtoken, out message); + var result = tokenProvider.TryValidateTokenSet(httpContext, principal, cookieToken, fieldtoken, out message); // Assert Assert.False(result); @@ -437,7 +437,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal // Arrange var httpContext = new DefaultHttpContext(); var identity = GetAuthenticatedIdentity("the-user"); - httpContext.User = new ClaimsPrincipal(identity); + var principal = new ClaimsPrincipal(identity); var cookieToken = new AntiforgeryToken() { IsCookieToken = true }; var fieldtoken = new AntiforgeryToken() @@ -462,7 +462,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal // Act string message; - var result = tokenProvider.TryValidateTokenSet(httpContext, cookieToken, fieldtoken, out message); + var result = tokenProvider.TryValidateTokenSet(httpContext, principal, cookieToken, fieldtoken, out message); // Assert Assert.False(result); @@ -475,7 +475,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal // Arrange var httpContext = new DefaultHttpContext(); var identity = new ClaimsIdentity(); - httpContext.User = new ClaimsPrincipal(identity); + var principal = new ClaimsPrincipal(identity); var cookieToken = new AntiforgeryToken() { IsCookieToken = true }; var fieldtoken = new AntiforgeryToken() @@ -499,7 +499,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal // Act string message; - var result = tokenProvider.TryValidateTokenSet(httpContext, cookieToken, fieldtoken, out message); + var result = tokenProvider.TryValidateTokenSet(httpContext, principal, cookieToken, fieldtoken, out message); // Assert Assert.False(result); @@ -512,7 +512,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal // Arrange var httpContext = new DefaultHttpContext(); var identity = new ClaimsIdentity(); - httpContext.User = new ClaimsPrincipal(identity); + var principal = new ClaimsPrincipal(identity); var cookieToken = new AntiforgeryToken() { IsCookieToken = true }; var fieldtoken = new AntiforgeryToken() @@ -533,7 +533,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal // Act string message; - var result = tokenProvider.TryValidateTokenSet(httpContext, cookieToken, fieldtoken, out message); + var result = tokenProvider.TryValidateTokenSet(httpContext, principal, cookieToken, fieldtoken, out message); // Assert Assert.True(result); @@ -546,7 +546,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal // Arrange var httpContext = new DefaultHttpContext(); var identity = GetAuthenticatedIdentity("the-user"); - httpContext.User = new ClaimsPrincipal(identity); + var principal = new ClaimsPrincipal(identity); var cookieToken = new AntiforgeryToken() { IsCookieToken = true }; var fieldtoken = new AntiforgeryToken() @@ -567,7 +567,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal // Act string message; - var result = tokenProvider.TryValidateTokenSet(httpContext, cookieToken, fieldtoken, out message); + var result = tokenProvider.TryValidateTokenSet(httpContext, principal, cookieToken, fieldtoken, out message); // Assert Assert.True(result); @@ -580,7 +580,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal // Arrange var httpContext = new DefaultHttpContext(); var identity = GetAuthenticatedIdentity("the-user"); - httpContext.User = new ClaimsPrincipal(identity); + var principal = new ClaimsPrincipal(identity); var cookieToken = new AntiforgeryToken() { IsCookieToken = true }; var fieldtoken = new AntiforgeryToken() @@ -600,7 +600,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal // Act string message; - var result = tokenProvider.TryValidateTokenSet(httpContext, cookieToken, fieldtoken, out message); + var result = tokenProvider.TryValidateTokenSet(httpContext, principal, cookieToken, fieldtoken, out message); // Assert Assert.True(result); From aa8fd48c64b9a5251ba8a1ba2c938377de999428 Mon Sep 17 00:00:00 2001 From: jacalvar Date: Mon, 22 Feb 2016 11:49:15 -0800 Subject: [PATCH 093/296] Updated antiforgery ServiceCollectionExtensions --- .../ServiceCollectionExtensions.cs | 29 ++++++++++++------- 1 file changed, 18 insertions(+), 11 deletions(-) diff --git a/src/Microsoft.AspNetCore.Antiforgery/ServiceCollectionExtensions.cs b/src/Microsoft.AspNetCore.Antiforgery/ServiceCollectionExtensions.cs index 4a8fe1cf58..2d5b2b808c 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/ServiceCollectionExtensions.cs +++ b/src/Microsoft.AspNetCore.Antiforgery/ServiceCollectionExtensions.cs @@ -10,9 +10,16 @@ using Microsoft.Extensions.Options; namespace Microsoft.Extensions.DependencyInjection { + /// + /// Extension methods for setting up antiforgery services in an . + /// public static class ServiceCollectionExtensions { - public static IServiceCollection AddAntiforgery(this IServiceCollection services) + /// + /// Adds antiforgery services to the specified . + /// + /// The to add services to. + public static void AddAntiforgery(this IServiceCollection services) { if (services == null) { @@ -40,27 +47,27 @@ namespace Microsoft.Extensions.DependencyInjection var policy = new AntiforgerySerializationContextPooledObjectPolicy(); return provider.Create(policy); }); - - return services; } - public static IServiceCollection AddAntiforgery( - this IServiceCollection services, - Action setupAction) + /// + /// Adds antiforgery services to the specified . + /// + /// The to add services to. + /// An to configure the provided . + public static void AddAntiforgery(this IServiceCollection services, Action setupAction) { if (services == null) { throw new ArgumentNullException(nameof(services)); } - services.AddAntiforgery(); - - if (setupAction != null) + if (setupAction == null) { - services.Configure(setupAction); + throw new ArgumentNullException(nameof(setupAction)); } - return services; + services.AddAntiforgery(); + services.Configure(setupAction); } } } From 6e3518dafcd22d9ef9d0113ae7c3e04e3f9c1faf Mon Sep 17 00:00:00 2001 From: Victor Hurdugaci Date: Sat, 27 Feb 2016 12:51:13 -0800 Subject: [PATCH 094/296] Update the build scripts --- build.cmd | 41 ++----------------------------------- build.ps1 | 36 +++++++++++++++++++++++++++++++++ build.sh | 60 +++++++++++++++++++++++-------------------------------- 3 files changed, 63 insertions(+), 74 deletions(-) create mode 100644 build.ps1 diff --git a/build.cmd b/build.cmd index 95b049cf63..2fa024b15e 100644 --- a/build.cmd +++ b/build.cmd @@ -1,39 +1,2 @@ -@ECHO off -SETLOCAL - -SET REPO_FOLDER=%~dp0 -CD "%REPO_FOLDER%" - -SET BUILD_FOLDER=.build -SET KOREBUILD_FOLDER=%BUILD_FOLDER%\KoreBuild-dotnet -SET KOREBUILD_VERSION= - -SET NUGET_PATH=%BUILD_FOLDER%\NuGet.exe -SET NUGET_VERSION=latest -SET CACHED_NUGET=%LocalAppData%\NuGet\nuget.%NUGET_VERSION%.exe - -IF NOT EXIST %BUILD_FOLDER% ( - md %BUILD_FOLDER% -) - -IF NOT EXIST %NUGET_PATH% ( - IF NOT EXIST %CACHED_NUGET% ( - echo Downloading latest version of NuGet.exe... - IF NOT EXIST %LocalAppData%\NuGet ( - md %LocalAppData%\NuGet - ) - @powershell -NoProfile -ExecutionPolicy unrestricted -Command "$ProgressPreference = 'SilentlyContinue'; Invoke-WebRequest 'https://dist.nuget.org/win-x86-commandline/%NUGET_VERSION%/nuget.exe' -OutFile '%CACHED_NUGET%'" - ) - - copy %CACHED_NUGET% %NUGET_PATH% > nul -) - -SET KOREBUILD_DOWNLOAD_ARGS= -IF NOT "%KOREBUILD_VERSION%"=="" ( - SET KOREBUILD_DOWNLOAD_ARGS=-version %KOREBUILD_VERSION% -) -IF NOT EXIST %KOREBUILD_FOLDER% ( - %BUILD_FOLDER%\nuget.exe install KoreBuild-dotnet -ExcludeVersion -o %BUILD_FOLDER% -nocache -pre %KOREBUILD_DOWNLOAD_ARGS% -) - -"%KOREBUILD_FOLDER%\build\KoreBuild.cmd" %* +@ECHO OFF +PowerShell -NoProfile -NoLogo -ExecutionPolicy unrestricted -Command "[System.Threading.Thread]::CurrentThread.CurrentCulture = ''; [System.Threading.Thread]::CurrentThread.CurrentUICulture = '';& '%~dp0build.ps1' %*" \ No newline at end of file diff --git a/build.ps1 b/build.ps1 new file mode 100644 index 0000000000..4fd24a30d5 --- /dev/null +++ b/build.ps1 @@ -0,0 +1,36 @@ +cd $PSScriptRoot + +$repoFolder = $PSScriptRoot +$env:REPO_FOLDER = $repoFolder + +$koreBuildZip="https://github.com/aspnet/KoreBuild/archive/dev.zip" +if ($env:KOREBUILD_ZIP) +{ + $koreBuildZip=$env:KOREBUILD_ZIP +} + +$buildFolder = ".build" +$buildFile="$buildFolder\KoreBuild.ps1" + +if (!(Test-Path $buildFolder)) { + Write-Host "Downloading KoreBuild from $koreBuildZip" + + $tempFolder=$env:TEMP + "\KoreBuild-" + [guid]::NewGuid() + New-Item -Path "$tempFolder" -Type directory | Out-Null + + $localZipFile="$tempFolder\korebuild.zip" + + Invoke-WebRequest $koreBuildZip -OutFile $localZipFile + Add-Type -AssemblyName System.IO.Compression.FileSystem + [System.IO.Compression.ZipFile]::ExtractToDirectory($localZipFile, $tempFolder) + + New-Item -Path "$buildFolder" -Type directory | Out-Null + copy-item "$tempFolder\**\build\*" $buildFolder -Recurse + + # Cleanup + if (Test-Path $tempFolder) { + Remove-Item -Recurse -Force $tempFolder + } +} + +&"$buildFile" $args \ No newline at end of file diff --git a/build.sh b/build.sh index 263fb667a8..79638d06b6 100755 --- a/build.sh +++ b/build.sh @@ -1,45 +1,35 @@ #!/usr/bin/env bash +repoFolder="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" +cd $repoFolder -buildFolder=.build -koreBuildFolder=$buildFolder/KoreBuild-dotnet - -nugetPath=$buildFolder/nuget.exe - -if test `uname` = Darwin; then - cachedir=~/Library/Caches/KBuild -else - if [ -z $XDG_DATA_HOME ]; then - cachedir=$HOME/.local/share - else - cachedir=$XDG_DATA_HOME; - fi +koreBuildZip="https://github.com/aspnet/KoreBuild/archive/dev.zip" +if [ ! -z $KOREBUILD_ZIP ]; then + koreBuildZip=$KOREBUILD_ZIP fi -mkdir -p $cachedir -nugetVersion=latest -cacheNuget=$cachedir/nuget.$nugetVersion.exe -nugetUrl=https://dist.nuget.org/win-x86-commandline/$nugetVersion/nuget.exe +buildFolder=".build" +buildFile="$buildFolder/KoreBuild.sh" if test ! -d $buildFolder; then + echo "Downloading KoreBuild from $koreBuildZip" + + tempFolder="/tmp/KoreBuild-$(uuidgen)" + mkdir $tempFolder + + localZipFile="$tempFolder/korebuild.zip" + + wget -O $localZipFile $koreBuildZip 2>/dev/null || curl -o $localZipFile --location $koreBuildZip /dev/null + unzip -q -d $tempFolder $localZipFile + mkdir $buildFolder -fi - -if test ! -f $nugetPath; then - if test ! -f $cacheNuget; then - wget -O $cacheNuget $nugetUrl 2>/dev/null || curl -o $cacheNuget --location $nugetUrl /dev/null + cp -r $tempFolder/**/build/** $buildFolder + + chmod +x $buildFile + + # Cleanup + if test ! -d $tempFolder; then + rm -rf $tempFolder fi - - cp $cacheNuget $nugetPath fi -if test ! -d $koreBuildFolder; then - mono $nugetPath install KoreBuild-dotnet -ExcludeVersion -o $buildFolder -nocache -pre - chmod +x $koreBuildFolder/build/KoreBuild.sh -fi - -makeFile=makefile.shade -if [ ! -e $makeFile ]; then - makeFile=$koreBuildFolder/build/makefile.shade -fi - -./$koreBuildFolder/build/KoreBuild.sh -n $nugetPath -m $makeFile "$@" +$buildFile -r $repoFolder "$@" From db2093ec2aa494a74f2311f8fa33f44669adb166 Mon Sep 17 00:00:00 2001 From: Victor Hurdugaci Date: Sun, 28 Feb 2016 10:12:16 -0800 Subject: [PATCH 095/296] Return the error code from build.cmd --- build.cmd | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/build.cmd b/build.cmd index 2fa024b15e..7d4894cb4a 100644 --- a/build.cmd +++ b/build.cmd @@ -1,2 +1,2 @@ @ECHO OFF -PowerShell -NoProfile -NoLogo -ExecutionPolicy unrestricted -Command "[System.Threading.Thread]::CurrentThread.CurrentCulture = ''; [System.Threading.Thread]::CurrentThread.CurrentUICulture = '';& '%~dp0build.ps1' %*" \ No newline at end of file +PowerShell -NoProfile -NoLogo -ExecutionPolicy unrestricted -Command "[System.Threading.Thread]::CurrentThread.CurrentCulture = ''; [System.Threading.Thread]::CurrentThread.CurrentUICulture = '';& '%~dp0build.ps1' %*; exit $LASTEXITCODE" \ No newline at end of file From f9b9dcd79b0687bb1c6abfc790369ec2a9808e7e Mon Sep 17 00:00:00 2001 From: "N. Taylor Mullen" Date: Tue, 1 Mar 2016 13:36:35 -0800 Subject: [PATCH 096/296] Transition to netstandard. - dotnet5.X => netstandard1.y (where y = x-1). - DNXCore50 => netstandardapp1.5. - Applied the same changes to ifdefs. --- samples/AntiforgerySample/project.json | 16 +++++++--------- .../project.json | 12 +++++++++--- .../project.json | 7 +++++-- .../project.json | 9 ++++++--- 4 files changed, 27 insertions(+), 17 deletions(-) diff --git a/samples/AntiforgerySample/project.json b/samples/AntiforgerySample/project.json index 761ce827e4..db44c51ba6 100644 --- a/samples/AntiforgerySample/project.json +++ b/samples/AntiforgerySample/project.json @@ -1,6 +1,5 @@ { "version": "1.0.0-*", - "dependencies": { "Microsoft.AspNetCore.Antiforgery": "1.0.0-*", "Microsoft.AspNetCore.Http.Abstractions": "1.0.0-*", @@ -11,22 +10,21 @@ "Microsoft.NETCore.Platforms": "1.0.1-*", "Newtonsoft.Json": "8.0.2" }, - "compilationOptions": { "emitEntryPoint": true }, - "commands": { "web": "AntiforgerySample" }, - "frameworks": { - "dnx451": { }, - "dnxcore50": { - "imports": "portable-net451+win8" + "dnx451": {}, + "netstandardapp1.5": { + "imports": [ + "dnxcore50", + "portable-net451+win8" + ] } }, - "publishExclude": [ "node_modules", "bower_components", @@ -39,4 +37,4 @@ "node_modules", "bower_components" ] -} +} \ No newline at end of file diff --git a/src/Microsoft.AspNetCore.Antiforgery/project.json b/src/Microsoft.AspNetCore.Antiforgery/project.json index 4fcfc49f40..e920a5da1a 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/project.json +++ b/src/Microsoft.AspNetCore.Antiforgery/project.json @@ -4,7 +4,9 @@ "compilationOptions": { "warningsAsErrors": true, "keyFile": "../../tools/Key.snk", - "nowarn": [ "CS1591" ], + "nowarn": [ + "CS1591" + ], "xmlDoc": true }, "repository": { @@ -17,7 +19,11 @@ "Microsoft.Extensions.ObjectPool": "1.0.0-*" }, "frameworks": { - "dotnet5.4": { }, - "net451": { } + "netstandard1.3": { + "imports": [ + "dotnet5.4" + ] + }, + "net451": {} } } \ No newline at end of file diff --git a/test/Microsoft.AspNetCore.Antiforgery.FunctionalTests/project.json b/test/Microsoft.AspNetCore.Antiforgery.FunctionalTests/project.json index a2a1bfdb71..3c3384faca 100644 --- a/test/Microsoft.AspNetCore.Antiforgery.FunctionalTests/project.json +++ b/test/Microsoft.AspNetCore.Antiforgery.FunctionalTests/project.json @@ -7,13 +7,16 @@ }, "testRunner": "xunit", "frameworks": { - "dnxcore50": { + "netstandardapp1.5": { "dependencies": { "moq.netcore": "4.4.0-beta8", "System.Net.Http": "4.0.1-*", "dotnet-test-xunit": "1.0.0-dev-*" }, - "imports": "portable-net451+win8" + "imports": [ + "dnxcore50", + "portable-net451+win8" + ] }, "dnx451": { "dependencies": { diff --git a/test/Microsoft.AspNetCore.Antiforgery.Test/project.json b/test/Microsoft.AspNetCore.Antiforgery.Test/project.json index 3f7b9441f3..47ba8e76bf 100644 --- a/test/Microsoft.AspNetCore.Antiforgery.Test/project.json +++ b/test/Microsoft.AspNetCore.Antiforgery.Test/project.json @@ -15,12 +15,15 @@ }, "testRunner": "xunit", "frameworks": { - "dnxcore50": { + "netstandardapp1.5": { "dependencies": { "moq.netcore": "4.4.0-beta8", "dotnet-test-xunit": "1.0.0-dev-*" }, - "imports": "portable-net451+win8" + "imports": [ + "dnxcore50", + "portable-net451+win8" + ] }, "dnx451": { "frameworkAssemblies": { @@ -32,4 +35,4 @@ } } } -} +} \ No newline at end of file From 260f1b7db9c7365bc91a72b099d5f15fa3576b16 Mon Sep 17 00:00:00 2001 From: Doug Bunting Date: Wed, 2 Mar 2016 15:21:47 -0800 Subject: [PATCH 097/296] Remove project name from output path - aspnet/Coherence-Signed#187 - remove `` settings but maintain other unique aspects e.g. `` - in a few cases, standardize on VS version `14.0` and not something more specific --- samples/AntiforgerySample/AntiforgerySample.xproj | 3 +-- .../Microsoft.AspNetCore.Antiforgery.xproj | 9 +++------ ...icrosoft.AspNetCore.Antiforgery.FunctionalTests.xproj | 7 +++---- .../Microsoft.AspNetCore.Antiforgery.Test.xproj | 5 ++--- 4 files changed, 9 insertions(+), 15 deletions(-) diff --git a/samples/AntiforgerySample/AntiforgerySample.xproj b/samples/AntiforgerySample/AntiforgerySample.xproj index d6dbc6607b..254d0c3d03 100644 --- a/samples/AntiforgerySample/AntiforgerySample.xproj +++ b/samples/AntiforgerySample/AntiforgerySample.xproj @@ -7,9 +7,8 @@ af9e0784-5edb-494f-b46c-1a8da785c49c - AntiforgerySample ..\..\artifacts\obj\$(MSBuildProjectName) - ..\..\artifacts\bin\$(MSBuildProjectName)\ + ..\..\artifacts\bin\ 2.0 diff --git a/src/Microsoft.AspNetCore.Antiforgery/Microsoft.AspNetCore.Antiforgery.xproj b/src/Microsoft.AspNetCore.Antiforgery/Microsoft.AspNetCore.Antiforgery.xproj index c616520381..cfd5f9890c 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/Microsoft.AspNetCore.Antiforgery.xproj +++ b/src/Microsoft.AspNetCore.Antiforgery/Microsoft.AspNetCore.Antiforgery.xproj @@ -1,20 +1,17 @@ - + 14.0 $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion) - 46fb03fb-7a44-4106-bdde-d6f5417544ab - Microsoft.AspNetCore.Antiforgery ..\..\artifacts\obj\$(MSBuildProjectName) - ..\..\artifacts\bin\$(MSBuildProjectName)\ + ..\..\artifacts\bin\ - 2.0 - + \ No newline at end of file diff --git a/test/Microsoft.AspNetCore.Antiforgery.FunctionalTests/Microsoft.AspNetCore.Antiforgery.FunctionalTests.xproj b/test/Microsoft.AspNetCore.Antiforgery.FunctionalTests/Microsoft.AspNetCore.Antiforgery.FunctionalTests.xproj index 775501b0ed..8ecb47ec07 100644 --- a/test/Microsoft.AspNetCore.Antiforgery.FunctionalTests/Microsoft.AspNetCore.Antiforgery.FunctionalTests.xproj +++ b/test/Microsoft.AspNetCore.Antiforgery.FunctionalTests/Microsoft.AspNetCore.Antiforgery.FunctionalTests.xproj @@ -1,15 +1,14 @@  - + - 14.0.24720 + 14.0 $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion) 8b288810-5a96-4af5-9836-8ba2d2953203 - FunctionalTests ..\..\artifacts\obj\$(MSBuildProjectName) - ..\..\artifacts\bin\$(MSBuildProjectName)\ + ..\..\artifacts\bin\ 2.0 diff --git a/test/Microsoft.AspNetCore.Antiforgery.Test/Microsoft.AspNetCore.Antiforgery.Test.xproj b/test/Microsoft.AspNetCore.Antiforgery.Test/Microsoft.AspNetCore.Antiforgery.Test.xproj index d97cfa0d9e..b016f46aac 100644 --- a/test/Microsoft.AspNetCore.Antiforgery.Test/Microsoft.AspNetCore.Antiforgery.Test.xproj +++ b/test/Microsoft.AspNetCore.Antiforgery.Test/Microsoft.AspNetCore.Antiforgery.Test.xproj @@ -1,4 +1,4 @@ - + 14.0 @@ -7,9 +7,8 @@ 415e83f8-6002-47e4-aa8e-cd5169c06f28 - Microsoft.AspNetCore.Antiforgery.Test ..\..\artifacts\obj\$(MSBuildProjectName) - ..\..\artifacts\bin\$(MSBuildProjectName)\ + ..\..\artifacts\bin\ 2.0 From 91f44549ac3216c0f14e2a46418d3de438fd849c Mon Sep 17 00:00:00 2001 From: Ajay Bhargav Baaskaran Date: Thu, 3 Mar 2016 17:33:26 -0800 Subject: [PATCH 098/296] Added Company, Copyright and Product attributes to AssemblyInfo --- .../Properties/AssemblyInfo.cs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/Microsoft.AspNetCore.Antiforgery/Properties/AssemblyInfo.cs b/src/Microsoft.AspNetCore.Antiforgery/Properties/AssemblyInfo.cs index e30b53b634..5b79e64ce4 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/Properties/AssemblyInfo.cs +++ b/src/Microsoft.AspNetCore.Antiforgery/Properties/AssemblyInfo.cs @@ -9,3 +9,6 @@ using System.Runtime.CompilerServices; [assembly: InternalsVisibleTo("Microsoft.AspNetCore.Antiforgery.Test, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f33a29044fa9d740c9b3213a93e57c84b472c84e0b8a0e1ae48e67a9f8f6de9d5f7f3d52ac23e48ac51801f1dc950abe901da34d2a9e3baadb141a17c77ef3c565dd5ee5054b91cf63bb3c6ab83f72ab3aafe93d0fc3c2348b764fafb0b1c0733de51459aeab46580384bf9d74c4e28164b7cde247f891ba07891c9d872ad2bb")] [assembly: AssemblyMetadata("Serviceable", "True")] [assembly: NeutralResourcesLanguage("en-us")] +[assembly: AssemblyCompany("Microsoft Corporation.")] +[assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] +[assembly: AssemblyProduct("Microsoft ASP.NET Core")] From 91b955e080e95cb9332ac6ff44c02ca87e98f402 Mon Sep 17 00:00:00 2001 From: John Luo Date: Thu, 3 Mar 2016 16:42:17 -0800 Subject: [PATCH 099/296] Update cookie name --- .../AntiforgeryOptions.cs | 8 +++++++- .../Internal/AntiforgeryOptionsSetup.cs | 2 +- .../Internal/AntiforgeryOptionsSetupTest.cs | 4 ++-- 3 files changed, 10 insertions(+), 4 deletions(-) diff --git a/src/Microsoft.AspNetCore.Antiforgery/AntiforgeryOptions.cs b/src/Microsoft.AspNetCore.Antiforgery/AntiforgeryOptions.cs index e59b6aecd9..2c05e1dc1c 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/AntiforgeryOptions.cs +++ b/src/Microsoft.AspNetCore.Antiforgery/AntiforgeryOptions.cs @@ -16,11 +16,17 @@ namespace Microsoft.AspNetCore.Antiforgery private string _cookieName; private string _formFieldName = AntiforgeryTokenFieldName; + /// + /// The default cookie prefix, which is ".AspNetCore.Antiforgery.". + /// + public static readonly string DefaultCookiePrefix = ".AspNetCore.Antiforgery."; + /// /// Specifies the name of the cookie that is used by the antiforgery system. /// /// - /// If an explicit name is not provided, the system will automatically generate a name. + /// If an explicit name is not provided, the system will automatically generate a + /// unique name that begins with . /// public string CookieName { diff --git a/src/Microsoft.AspNetCore.Antiforgery/Internal/AntiforgeryOptionsSetup.cs b/src/Microsoft.AspNetCore.Antiforgery/Internal/AntiforgeryOptionsSetup.cs index f1f7dc612a..1c5a3fa4b8 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/Internal/AntiforgeryOptionsSetup.cs +++ b/src/Microsoft.AspNetCore.Antiforgery/Internal/AntiforgeryOptionsSetup.cs @@ -22,7 +22,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal if (options.CookieName == null) { var applicationId = dataProtectionOptions.ApplicationDiscriminator ?? string.Empty; - options.CookieName = ComputeCookieName(applicationId); + options.CookieName = AntiforgeryOptions.DefaultCookiePrefix + ComputeCookieName(applicationId); } } diff --git a/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/AntiforgeryOptionsSetupTest.cs b/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/AntiforgeryOptionsSetupTest.cs index a981339793..79804b4117 100644 --- a/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/AntiforgeryOptionsSetupTest.cs +++ b/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/AntiforgeryOptionsSetupTest.cs @@ -10,8 +10,8 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal public class AntiforgeryOptionsSetupTest { [Theory] - [InlineData("HelloWorldApp", "tGmK82_ckDw")] - [InlineData("TodoCalendar", "7mK1hBEBwYs")] + [InlineData("HelloWorldApp", ".AspNetCore.Antiforgery.tGmK82_ckDw")] + [InlineData("TodoCalendar", ".AspNetCore.Antiforgery.7mK1hBEBwYs")] public void AntiforgeryOptionsSetup_SetsDefaultCookieName_BasedOnApplicationId( string applicationId, string expectedCookieName) From 1d78d51cb1f8149fc42f296c093ea6dfccbe78d1 Mon Sep 17 00:00:00 2001 From: Eilon Lipton Date: Sun, 6 Mar 2016 21:00:28 -0800 Subject: [PATCH 100/296] Fix package metadata --- README.md | 2 +- src/Microsoft.AspNetCore.Antiforgery/project.json | 8 ++++++-- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 8c911eb6f1..3ea14d6634 100644 --- a/README.md +++ b/README.md @@ -7,4 +7,4 @@ Travis: [![Travis](https://travis-ci.org/aspnet/Antiforgery.svg?branch=dev)](h Antiforgery system for generating secure tokens to prevent Cross-Site Request Forgery attacks. -This project is part of ASP.NET 5. You can find samples, documentation and getting started instructions for ASP.NET 5 at the [Home](https://github.com/aspnet/home) repo. +This project is part of ASP.NET Core. You can find samples, documentation and getting started instructions for ASP.NET Core at the [Home](https://github.com/aspnet/home) repo. diff --git a/src/Microsoft.AspNetCore.Antiforgery/project.json b/src/Microsoft.AspNetCore.Antiforgery/project.json index e920a5da1a..2ef0639561 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/project.json +++ b/src/Microsoft.AspNetCore.Antiforgery/project.json @@ -1,5 +1,9 @@ { - "description": "An antiforgery system for ASP.NET designed to generate and validate tokens to prevent Cross-Site Request Forgery attacks.", + "description": "An antiforgery system for ASP.NET Core designed to generate and validate tokens to prevent Cross-Site Request Forgery attacks.", + "tags": [ + "aspnetcore", + "antiforgery" + ], "version": "1.0.0-*", "compilationOptions": { "warningsAsErrors": true, @@ -24,6 +28,6 @@ "dotnet5.4" ] }, - "net451": {} + "net451": { } } } \ No newline at end of file From 42417a985e5293f4d1646b344ed00d5d6aa0a9a6 Mon Sep 17 00:00:00 2001 From: Victor Hurdugaci Date: Mon, 7 Mar 2016 20:55:02 -0800 Subject: [PATCH 101/296] Update the build scripts to the latest version --- build.ps1 | 33 ++++++++++++++++++++++++++++++++- build.sh | 15 +++++++++++++-- 2 files changed, 45 insertions(+), 3 deletions(-) diff --git a/build.ps1 b/build.ps1 index 4fd24a30d5..8f2f99691a 100644 --- a/build.ps1 +++ b/build.ps1 @@ -1,3 +1,33 @@ +$ErrorActionPreference = "Stop" + +function DownloadWithRetry([string] $url, [string] $downloadLocation, [int] $retries) +{ + while($true) + { + try + { + Invoke-WebRequest $url -OutFile $downloadLocation + break + } + catch + { + $exceptionMessage = $_.Exception.Message + Write-Host "Failed to download '$url': $exceptionMessage" + if ($retries -gt 0) { + $retries-- + Write-Host "Waiting 10 seconds before retrying. Retries left: $retries" + Start-Sleep -Seconds 10 + + } + else + { + $exception = $_.Exception + throw $exception + } + } + } +} + cd $PSScriptRoot $repoFolder = $PSScriptRoot @@ -20,7 +50,8 @@ if (!(Test-Path $buildFolder)) { $localZipFile="$tempFolder\korebuild.zip" - Invoke-WebRequest $koreBuildZip -OutFile $localZipFile + DownloadWithRetry -url $koreBuildZip -downloadLocation $localZipFile -retries 6 + Add-Type -AssemblyName System.IO.Compression.FileSystem [System.IO.Compression.ZipFile]::ExtractToDirectory($localZipFile, $tempFolder) diff --git a/build.sh b/build.sh index 79638d06b6..f4208100eb 100755 --- a/build.sh +++ b/build.sh @@ -18,7 +18,18 @@ if test ! -d $buildFolder; then localZipFile="$tempFolder/korebuild.zip" - wget -O $localZipFile $koreBuildZip 2>/dev/null || curl -o $localZipFile --location $koreBuildZip /dev/null + retries=6 + until (wget -O $localZipFile $koreBuildZip 2>/dev/null || curl -o $localZipFile --location $koreBuildZip 2>/dev/null) + do + echo "Failed to download '$koreBuildZip'" + if [ "$retries" -le 0 ]; then + exit 1 + fi + retries=$((retries - 1)) + echo "Waiting 10 seconds before retrying. Retries left: $retries" + sleep 10s + done + unzip -q -d $tempFolder $localZipFile mkdir $buildFolder @@ -32,4 +43,4 @@ if test ! -d $buildFolder; then fi fi -$buildFile -r $repoFolder "$@" +$buildFile -r $repoFolder "$@" \ No newline at end of file From 6f7b554496398dff99c6202f4236ff89ab94fa2c Mon Sep 17 00:00:00 2001 From: Nate McMaster Date: Wed, 9 Mar 2016 16:25:31 -0800 Subject: [PATCH 102/296] Limit the branches that build on our public CI. [ci skip] --- .travis.yml | 6 ++++++ appveyor.yml | 6 ++++++ 2 files changed, 12 insertions(+) diff --git a/.travis.yml b/.travis.yml index e8f77f0f14..e63d71127a 100644 --- a/.travis.yml +++ b/.travis.yml @@ -16,5 +16,11 @@ os: - linux - osx osx_image: xcode7.1 +branches: + only: + - master + - release + - dev + - /^(.*\\/)?ci-.*$/ script: - ./build.sh --quiet verify \ No newline at end of file diff --git a/appveyor.yml b/appveyor.yml index 636a7618d3..15ffe737a5 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -1,5 +1,11 @@ init: - git config --global core.autocrlf true +branches: + only: + - master + - release + - dev + - /^(.*\\/)?ci-.*$/ build_script: - build.cmd --quiet verify clone_depth: 1 From fb28bacda13874dc9824d175dccfb2032f3903c9 Mon Sep 17 00:00:00 2001 From: = Date: Wed, 9 Mar 2016 17:21:05 -0800 Subject: [PATCH 103/296] Target net451 so functional tests execute with xunit runner on linux --- samples/AntiforgerySample/project.json | 2 +- .../project.json | 2 +- test/Microsoft.AspNetCore.Antiforgery.Test/project.json | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/samples/AntiforgerySample/project.json b/samples/AntiforgerySample/project.json index db44c51ba6..02fd530988 100644 --- a/samples/AntiforgerySample/project.json +++ b/samples/AntiforgerySample/project.json @@ -17,7 +17,7 @@ "web": "AntiforgerySample" }, "frameworks": { - "dnx451": {}, + "net451": {}, "netstandardapp1.5": { "imports": [ "dnxcore50", diff --git a/test/Microsoft.AspNetCore.Antiforgery.FunctionalTests/project.json b/test/Microsoft.AspNetCore.Antiforgery.FunctionalTests/project.json index 3c3384faca..e516749f67 100644 --- a/test/Microsoft.AspNetCore.Antiforgery.FunctionalTests/project.json +++ b/test/Microsoft.AspNetCore.Antiforgery.FunctionalTests/project.json @@ -18,7 +18,7 @@ "portable-net451+win8" ] }, - "dnx451": { + "net451": { "dependencies": { "Moq": "4.2.1312.1622", "xunit.runner.console": "2.1.0" diff --git a/test/Microsoft.AspNetCore.Antiforgery.Test/project.json b/test/Microsoft.AspNetCore.Antiforgery.Test/project.json index 47ba8e76bf..0ac8f81de0 100644 --- a/test/Microsoft.AspNetCore.Antiforgery.Test/project.json +++ b/test/Microsoft.AspNetCore.Antiforgery.Test/project.json @@ -25,7 +25,7 @@ "portable-net451+win8" ] }, - "dnx451": { + "net451": { "frameworkAssemblies": { "System.Threading.Tasks": "" }, From a3f564e3d17210aa722cb9cc5a00c7e58c9035f4 Mon Sep 17 00:00:00 2001 From: Nate McMaster Date: Wed, 9 Mar 2016 17:44:49 -0800 Subject: [PATCH 104/296] Fix backslashes in yml config. [ci skip] --- .travis.yml | 2 +- appveyor.yml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.travis.yml b/.travis.yml index e63d71127a..304e307169 100644 --- a/.travis.yml +++ b/.travis.yml @@ -21,6 +21,6 @@ branches: - master - release - dev - - /^(.*\\/)?ci-.*$/ + - /^(.*\/)?ci-.*$/ script: - ./build.sh --quiet verify \ No newline at end of file diff --git a/appveyor.yml b/appveyor.yml index 15ffe737a5..be95b88d6f 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -5,7 +5,7 @@ branches: - master - release - dev - - /^(.*\\/)?ci-.*$/ + - /^(.*\/)?ci-.*$/ build_script: - build.cmd --quiet verify clone_depth: 1 From 162cb428cc31ae443d68099161c58b9ecc7f740c Mon Sep 17 00:00:00 2001 From: Pranav K Date: Sat, 12 Mar 2016 09:45:03 -0800 Subject: [PATCH 105/296] Fixing CI build failure Removing unused npm references --- samples/AntiforgerySample/package.json | 6 +----- src/Microsoft.AspNetCore.Antiforgery/project.json | 6 +++++- .../project.json | 3 +-- 3 files changed, 7 insertions(+), 8 deletions(-) diff --git a/samples/AntiforgerySample/package.json b/samples/AntiforgerySample/package.json index e3693fbdb7..cad917e2a0 100644 --- a/samples/AntiforgerySample/package.json +++ b/samples/AntiforgerySample/package.json @@ -4,10 +4,6 @@ "version": "0.0.0", "devDependencies": { "gulp": "^3.9.0", - "gulp-concat": "^2.6.0", - "gulp-cssmin": "^0.1.7", - "gulp-uglify": "^1.5.1", - "main-bower-files": "^2.9.0", - "rimraf": "^2.4.4" + "main-bower-files": "^2.9.0" } } diff --git a/src/Microsoft.AspNetCore.Antiforgery/project.json b/src/Microsoft.AspNetCore.Antiforgery/project.json index 2ef0639561..e1d6fe15b6 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/project.json +++ b/src/Microsoft.AspNetCore.Antiforgery/project.json @@ -28,6 +28,10 @@ "dotnet5.4" ] }, - "net451": { } + "net451": { + "frameworkAssemblies": { + "System.Runtime": { "type": "build"} + } + } } } \ No newline at end of file diff --git a/test/Microsoft.AspNetCore.Antiforgery.FunctionalTests/project.json b/test/Microsoft.AspNetCore.Antiforgery.FunctionalTests/project.json index e516749f67..7b345f04fe 100644 --- a/test/Microsoft.AspNetCore.Antiforgery.FunctionalTests/project.json +++ b/test/Microsoft.AspNetCore.Antiforgery.FunctionalTests/project.json @@ -20,8 +20,7 @@ }, "net451": { "dependencies": { - "Moq": "4.2.1312.1622", - "xunit.runner.console": "2.1.0" + "Moq": "4.2.1312.1622" }, "frameworkAssemblies": { "System.Net.Http": "" From 33c91afbb2892e77c715d36001935d870ac7c28d Mon Sep 17 00:00:00 2001 From: Ajay Bhargav Baaskaran Date: Mon, 14 Mar 2016 14:33:08 -0700 Subject: [PATCH 106/296] Updated Json.Net version --- samples/AntiforgerySample/project.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/samples/AntiforgerySample/project.json b/samples/AntiforgerySample/project.json index 02fd530988..fd999ad29b 100644 --- a/samples/AntiforgerySample/project.json +++ b/samples/AntiforgerySample/project.json @@ -8,7 +8,7 @@ "Microsoft.AspNetCore.Server.Kestrel": "1.0.0-*", "Microsoft.AspNetCore.StaticFiles": "1.0.0-*", "Microsoft.NETCore.Platforms": "1.0.1-*", - "Newtonsoft.Json": "8.0.2" + "Newtonsoft.Json": "8.0.3" }, "compilationOptions": { "emitEntryPoint": true From ddde171fcbf9fb587c99ea4028d4ed8da79294c1 Mon Sep 17 00:00:00 2001 From: Pranav K Date: Mon, 14 Mar 2016 20:53:27 -0700 Subject: [PATCH 107/296] Reacting to Hosting changes --- .../AntiForgerySampleTestFixture.cs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/test/Microsoft.AspNetCore.Antiforgery.FunctionalTests/AntiForgerySampleTestFixture.cs b/test/Microsoft.AspNetCore.Antiforgery.FunctionalTests/AntiForgerySampleTestFixture.cs index ad4514519e..5958064a0c 100644 --- a/test/Microsoft.AspNetCore.Antiforgery.FunctionalTests/AntiForgerySampleTestFixture.cs +++ b/test/Microsoft.AspNetCore.Antiforgery.FunctionalTests/AntiForgerySampleTestFixture.cs @@ -25,8 +25,7 @@ namespace Microsoft.AspNetCore.Antiforgery.FunctionalTests var builder = new WebHostBuilder() .UseConfiguration(configurationBuilder.Build()) - .UseStartup(typeof(AntiforgerySample.Startup)) - .UseApplicationBasePath("../../../../samples/AntiforgerySample"); + .UseStartup(typeof(AntiforgerySample.Startup)); _server = new TestServer(builder); From c237f8989a9b62121fe2bb1e6ac5ebad6c5088eb Mon Sep 17 00:00:00 2001 From: jacalvar Date: Tue, 15 Mar 2016 16:11:49 -0700 Subject: [PATCH 108/296] React to changes in DataProtection --- .../Internal/AntiforgeryOptionsSetupTest.cs | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/AntiforgeryOptionsSetupTest.cs b/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/AntiforgeryOptionsSetupTest.cs index 79804b4117..181c62b3e5 100644 --- a/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/AntiforgeryOptionsSetupTest.cs +++ b/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/AntiforgeryOptionsSetupTest.cs @@ -1,6 +1,7 @@ // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. +using Microsoft.AspNetCore.DataProtection; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Options; using Xunit; @@ -19,7 +20,9 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal // Arrange var serviceCollection = new ServiceCollection(); serviceCollection.AddAntiforgery(); - serviceCollection.AddDataProtection(o => o.SetApplicationName(applicationId)); + serviceCollection + .AddDataProtection() + .SetApplicationName(applicationId); var services = serviceCollection.BuildServiceProvider(); var options = services.GetRequiredService>(); @@ -42,7 +45,9 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal o.CookieName = "antiforgery"; }); serviceCollection.AddAntiforgery(); - serviceCollection.AddDataProtection(o => o.SetApplicationName("HelloWorldApp")); + serviceCollection + .AddDataProtection() + .SetApplicationName("HelloWorldApp"); var services = serviceCollection.BuildServiceProvider(); var options = services.GetRequiredService>(); From 94cefde3ec903647d0f59d13e37c4eaeba9a9fe2 Mon Sep 17 00:00:00 2001 From: ryanbrandenburg Date: Wed, 23 Mar 2016 11:19:34 -0700 Subject: [PATCH 109/296] Make IAntiforgeryContextAccessor a Feature --- ...orgeryContext.cs => AntiforgeryFeature.cs} | 2 +- .../Internal/DefaultAntiforgery.cs | 130 ++++---- .../DefaultAntiforgeryContextAccessor.cs | 10 - .../Internal/IAntiforgeryContextAccessor.cs | 10 - .../Internal/IAntiforgeryFeature.cs | 25 ++ .../ServiceCollectionExtensions.cs | 1 - .../Internal/DefaultAntiforgeryTest.cs | 305 ++++++++---------- 7 files changed, 233 insertions(+), 250 deletions(-) rename src/Microsoft.AspNetCore.Antiforgery/Internal/{AntiforgeryContext.cs => AntiforgeryFeature.cs} (95%) delete mode 100644 src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgeryContextAccessor.cs delete mode 100644 src/Microsoft.AspNetCore.Antiforgery/Internal/IAntiforgeryContextAccessor.cs create mode 100644 src/Microsoft.AspNetCore.Antiforgery/Internal/IAntiforgeryFeature.cs diff --git a/src/Microsoft.AspNetCore.Antiforgery/Internal/AntiforgeryContext.cs b/src/Microsoft.AspNetCore.Antiforgery/Internal/AntiforgeryFeature.cs similarity index 95% rename from src/Microsoft.AspNetCore.Antiforgery/Internal/AntiforgeryContext.cs rename to src/Microsoft.AspNetCore.Antiforgery/Internal/AntiforgeryFeature.cs index d3f81c694d..ad2a38501d 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/Internal/AntiforgeryContext.cs +++ b/src/Microsoft.AspNetCore.Antiforgery/Internal/AntiforgeryFeature.cs @@ -6,7 +6,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal /// /// Used to hold per-request state. /// - public class AntiforgeryContext + public class AntiforgeryFeature : IAntiforgeryFeature { public bool HaveDeserializedCookieToken { get; set; } diff --git a/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgery.cs b/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgery.cs index 95f0208054..c832a378be 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgery.cs +++ b/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgery.cs @@ -48,18 +48,18 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal CheckSSLConfig(httpContext); - var antiforgeryContext = GetTokensInternal(httpContext); - var tokenSet = Serialize(antiforgeryContext); + var antiforgeryFeature = GetTokensInternal(httpContext); + var tokenSet = Serialize(antiforgeryFeature); - if (!antiforgeryContext.HaveStoredNewCookieToken) + if (!antiforgeryFeature.HaveStoredNewCookieToken) { - if (antiforgeryContext.NewCookieToken != null) + if (antiforgeryFeature.NewCookieToken != null) { // Serialize handles the new cookie token string. - Debug.Assert(antiforgeryContext.NewCookieTokenString != null); + Debug.Assert(antiforgeryFeature.NewCookieTokenString != null); - SaveCookieTokenAndHeader(httpContext, antiforgeryContext.NewCookieTokenString); - antiforgeryContext.HaveStoredNewCookieToken = true; + SaveCookieTokenAndHeader(httpContext, antiforgeryFeature.NewCookieTokenString); + antiforgeryFeature.HaveStoredNewCookieToken = true; _logger.NewCookieToken(); } else @@ -81,8 +81,8 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal CheckSSLConfig(httpContext); - var antiforgeryContext = GetTokensInternal(httpContext); - return Serialize(antiforgeryContext); + var antiforgeryFeature = GetTokensInternal(httpContext); + return Serialize(antiforgeryFeature); } /// @@ -263,17 +263,17 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal CheckSSLConfig(httpContext); - var antiforgeryContext = GetCookieTokens(httpContext); - if (!antiforgeryContext.HaveStoredNewCookieToken && antiforgeryContext.NewCookieToken != null) + var antiforgeryFeature = GetCookieTokens(httpContext); + if (!antiforgeryFeature.HaveStoredNewCookieToken && antiforgeryFeature.NewCookieToken != null) { - if (antiforgeryContext.NewCookieTokenString == null) + if (antiforgeryFeature.NewCookieTokenString == null) { - antiforgeryContext.NewCookieTokenString = - _tokenSerializer.Serialize(antiforgeryContext.NewCookieToken); + antiforgeryFeature.NewCookieTokenString = + _tokenSerializer.Serialize(antiforgeryFeature.NewCookieToken); } - SaveCookieTokenAndHeader(httpContext, antiforgeryContext.NewCookieTokenString); - antiforgeryContext.HaveStoredNewCookieToken = true; + SaveCookieTokenAndHeader(httpContext, antiforgeryFeature.NewCookieTokenString); + antiforgeryFeature.HaveStoredNewCookieToken = true; _logger.NewCookieToken(); } else @@ -325,35 +325,41 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal return true; } - private AntiforgeryContext GetCookieTokens(HttpContext httpContext) + private static IAntiforgeryFeature GetAntiforgeryFeature(HttpContext httpContext) { - var services = httpContext.RequestServices; - var contextAccessor = services.GetRequiredService(); - if (contextAccessor.Value == null) + var antiforgeryFeature = httpContext.Features.Get(); + if (antiforgeryFeature == null) { - contextAccessor.Value = new AntiforgeryContext(); + antiforgeryFeature = new AntiforgeryFeature(); + httpContext.Features.Set(antiforgeryFeature); } - var antiforgeryContext = contextAccessor.Value; - if (antiforgeryContext.HaveGeneratedNewCookieToken) + return antiforgeryFeature; + } + + private IAntiforgeryFeature GetCookieTokens(HttpContext httpContext) + { + var antiforgeryFeature = GetAntiforgeryFeature(httpContext); + + if (antiforgeryFeature.HaveGeneratedNewCookieToken) { - Debug.Assert(antiforgeryContext.HaveDeserializedCookieToken); + Debug.Assert(antiforgeryFeature.HaveDeserializedCookieToken); // Have executed this method earlier in the context of this request. - return antiforgeryContext; + return antiforgeryFeature; } AntiforgeryToken cookieToken; - if (antiforgeryContext.HaveDeserializedCookieToken) + if (antiforgeryFeature.HaveDeserializedCookieToken) { - cookieToken = antiforgeryContext.CookieToken; + cookieToken = antiforgeryFeature.CookieToken; } else { cookieToken = GetCookieTokenDoesNotThrow(httpContext); - antiforgeryContext.CookieToken = cookieToken; - antiforgeryContext.HaveDeserializedCookieToken = true; + antiforgeryFeature.CookieToken = cookieToken; + antiforgeryFeature.HaveDeserializedCookieToken = true; } AntiforgeryToken newCookieToken; @@ -369,10 +375,10 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal Debug.Assert(_tokenGenerator.IsCookieTokenValid(newCookieToken)); } - antiforgeryContext.HaveGeneratedNewCookieToken = true; - antiforgeryContext.NewCookieToken = newCookieToken; + antiforgeryFeature.HaveGeneratedNewCookieToken = true; + antiforgeryFeature.NewCookieToken = newCookieToken; - return antiforgeryContext; + return antiforgeryFeature; } private AntiforgeryToken GetCookieTokenDoesNotThrow(HttpContext httpContext) @@ -391,42 +397,42 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal } } - private AntiforgeryContext GetTokensInternal(HttpContext httpContext) + private IAntiforgeryFeature GetTokensInternal(HttpContext httpContext) { - var antiforgeryContext = GetCookieTokens(httpContext); - if (antiforgeryContext.NewRequestToken == null) + var antiforgeryFeature = GetCookieTokens(httpContext); + if (antiforgeryFeature.NewRequestToken == null) { - var cookieToken = antiforgeryContext.NewCookieToken ?? antiforgeryContext.CookieToken; - antiforgeryContext.NewRequestToken = _tokenGenerator.GenerateRequestToken( - httpContext, + var cookieToken = antiforgeryFeature.NewCookieToken ?? antiforgeryFeature.CookieToken; + antiforgeryFeature.NewRequestToken = _tokenGenerator.GenerateRequestToken( + httpContext, httpContext.User, cookieToken); } - return antiforgeryContext; + return antiforgeryFeature; } - private AntiforgeryTokenSet Serialize(AntiforgeryContext antiforgeryContext) + private AntiforgeryTokenSet Serialize(IAntiforgeryFeature antiforgeryFeature) { // Should only be called after new tokens have been generated. - Debug.Assert(antiforgeryContext.HaveGeneratedNewCookieToken); - Debug.Assert(antiforgeryContext.NewRequestToken != null); + Debug.Assert(antiforgeryFeature.HaveGeneratedNewCookieToken); + Debug.Assert(antiforgeryFeature.NewRequestToken != null); - if (antiforgeryContext.NewRequestTokenString == null) + if (antiforgeryFeature.NewRequestTokenString == null) { - antiforgeryContext.NewRequestTokenString = - _tokenSerializer.Serialize(antiforgeryContext.NewRequestToken); + antiforgeryFeature.NewRequestTokenString = + _tokenSerializer.Serialize(antiforgeryFeature.NewRequestToken); } - if (antiforgeryContext.NewCookieTokenString == null && antiforgeryContext.NewCookieToken != null) + if (antiforgeryFeature.NewCookieTokenString == null && antiforgeryFeature.NewCookieToken != null) { - antiforgeryContext.NewCookieTokenString = - _tokenSerializer.Serialize(antiforgeryContext.NewCookieToken); + antiforgeryFeature.NewCookieTokenString = + _tokenSerializer.Serialize(antiforgeryFeature.NewCookieToken); } return new AntiforgeryTokenSet( - antiforgeryContext.NewRequestTokenString, - antiforgeryContext.NewCookieTokenString, + antiforgeryFeature.NewRequestTokenString, + antiforgeryFeature.NewCookieTokenString, _options.FormFieldName, _options.HeaderName); } @@ -437,36 +443,30 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal out AntiforgeryToken cookieToken, out AntiforgeryToken requestToken) { - var services = httpContext.RequestServices; - var contextAccessor = services.GetRequiredService(); - if (contextAccessor.Value == null) - { - contextAccessor.Value = new AntiforgeryContext(); - } + var antiforgeryFeature = GetAntiforgeryFeature(httpContext); - var antiforgeryContext = contextAccessor.Value; - if (antiforgeryContext.HaveDeserializedCookieToken) + if (antiforgeryFeature.HaveDeserializedCookieToken) { - cookieToken = antiforgeryContext.CookieToken; + cookieToken = antiforgeryFeature.CookieToken; } else { cookieToken = _tokenSerializer.Deserialize(antiforgeryTokenSet.CookieToken); - antiforgeryContext.CookieToken = cookieToken; - antiforgeryContext.HaveDeserializedCookieToken = true; + antiforgeryFeature.CookieToken = cookieToken; + antiforgeryFeature.HaveDeserializedCookieToken = true; } - if (antiforgeryContext.HaveDeserializedRequestToken) + if (antiforgeryFeature.HaveDeserializedRequestToken) { - requestToken = antiforgeryContext.RequestToken; + requestToken = antiforgeryFeature.RequestToken; } else { requestToken = _tokenSerializer.Deserialize(antiforgeryTokenSet.RequestToken); - antiforgeryContext.RequestToken = requestToken; - antiforgeryContext.HaveDeserializedRequestToken = true; + antiforgeryFeature.RequestToken = requestToken; + antiforgeryFeature.HaveDeserializedRequestToken = true; } } } diff --git a/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgeryContextAccessor.cs b/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgeryContextAccessor.cs deleted file mode 100644 index ab2df64fa1..0000000000 --- a/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgeryContextAccessor.cs +++ /dev/null @@ -1,10 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -namespace Microsoft.AspNetCore.Antiforgery.Internal -{ - public class DefaultAntiforgeryContextAccessor : IAntiforgeryContextAccessor - { - public AntiforgeryContext Value { get; set; } - } -} diff --git a/src/Microsoft.AspNetCore.Antiforgery/Internal/IAntiforgeryContextAccessor.cs b/src/Microsoft.AspNetCore.Antiforgery/Internal/IAntiforgeryContextAccessor.cs deleted file mode 100644 index 238f2a082e..0000000000 --- a/src/Microsoft.AspNetCore.Antiforgery/Internal/IAntiforgeryContextAccessor.cs +++ /dev/null @@ -1,10 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -namespace Microsoft.AspNetCore.Antiforgery.Internal -{ - public interface IAntiforgeryContextAccessor - { - AntiforgeryContext Value { get; set; } - } -} diff --git a/src/Microsoft.AspNetCore.Antiforgery/Internal/IAntiforgeryFeature.cs b/src/Microsoft.AspNetCore.Antiforgery/Internal/IAntiforgeryFeature.cs new file mode 100644 index 0000000000..2404359de7 --- /dev/null +++ b/src/Microsoft.AspNetCore.Antiforgery/Internal/IAntiforgeryFeature.cs @@ -0,0 +1,25 @@ +namespace Microsoft.AspNetCore.Antiforgery.Internal +{ + public interface IAntiforgeryFeature + { + AntiforgeryToken CookieToken { get; set; } + + bool HaveDeserializedCookieToken { get; set; } + + bool HaveDeserializedRequestToken { get; set; } + + bool HaveGeneratedNewCookieToken { get; set; } + + bool HaveStoredNewCookieToken { get; set; } + + AntiforgeryToken NewCookieToken { get; set; } + + string NewCookieTokenString { get; set; } + + AntiforgeryToken NewRequestToken { get; set; } + + string NewRequestTokenString { get; set; } + + AntiforgeryToken RequestToken { get; set; } + } +} \ No newline at end of file diff --git a/src/Microsoft.AspNetCore.Antiforgery/ServiceCollectionExtensions.cs b/src/Microsoft.AspNetCore.Antiforgery/ServiceCollectionExtensions.cs index 2d5b2b808c..bc07489e2c 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/ServiceCollectionExtensions.cs +++ b/src/Microsoft.AspNetCore.Antiforgery/ServiceCollectionExtensions.cs @@ -37,7 +37,6 @@ namespace Microsoft.Extensions.DependencyInjection services.TryAddSingleton(); services.TryAddSingleton(); services.TryAddSingleton(); - services.TryAddScoped(); services.TryAddSingleton(); services.TryAddSingleton(new DefaultObjectPoolProvider()); diff --git a/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTest.cs b/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTest.cs index 2d10221a41..776284ff72 100644 --- a/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTest.cs +++ b/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTest.cs @@ -5,6 +5,7 @@ using System; using System.Security.Claims; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.Features; using Microsoft.AspNetCore.Http.Internal; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; @@ -181,13 +182,13 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal public void GetTokens_ExistingInvalidCookieToken_GeneratesANewCookieTokenAndANewFormToken() { // Arrange - var contextAccessor = new DefaultAntiforgeryContextAccessor(); + var antiforgeryFeature = new AntiforgeryFeature(); // Generate a new cookie. var context = CreateMockContext( new AntiforgeryOptions(), useOldCookie: false, isOldCookieValid: false, - contextAccessor: contextAccessor); + antiforgeryFeature: antiforgeryFeature); var antiforgery = GetAntiforgery(context); // Act @@ -197,14 +198,14 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal Assert.Equal(context.TestTokenSet.NewCookieTokenString, tokenset.CookieToken); Assert.Equal(context.TestTokenSet.FormTokenString, tokenset.RequestToken); - Assert.NotNull(contextAccessor.Value); - Assert.True(contextAccessor.Value.HaveDeserializedCookieToken); - Assert.Equal(context.TestTokenSet.OldCookieToken, contextAccessor.Value.CookieToken); - Assert.True(contextAccessor.Value.HaveGeneratedNewCookieToken); - Assert.Equal(context.TestTokenSet.NewCookieToken, contextAccessor.Value.NewCookieToken); - Assert.Equal(context.TestTokenSet.NewCookieTokenString, contextAccessor.Value.NewCookieTokenString); - Assert.Equal(context.TestTokenSet.RequestToken, contextAccessor.Value.NewRequestToken); - Assert.Equal(context.TestTokenSet.FormTokenString, contextAccessor.Value.NewRequestTokenString); + Assert.NotNull(antiforgeryFeature); + Assert.True(antiforgeryFeature.HaveDeserializedCookieToken); + Assert.Equal(context.TestTokenSet.OldCookieToken, antiforgeryFeature.CookieToken); + Assert.True(antiforgeryFeature.HaveGeneratedNewCookieToken); + Assert.Equal(context.TestTokenSet.NewCookieToken, antiforgeryFeature.NewCookieToken); + Assert.Equal(context.TestTokenSet.NewCookieTokenString, antiforgeryFeature.NewCookieTokenString); + Assert.Equal(context.TestTokenSet.RequestToken, antiforgeryFeature.NewRequestToken); + Assert.Equal(context.TestTokenSet.FormTokenString, antiforgeryFeature.NewRequestTokenString); } [Fact] @@ -239,12 +240,12 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal public void GetTokens_ExistingValidCookieToken_GeneratesANewFormToken() { // Arrange - var contextAccessor = new DefaultAntiforgeryContextAccessor(); + var antiforgeryFeature = new AntiforgeryFeature(); var context = CreateMockContext( new AntiforgeryOptions(), useOldCookie: true, isOldCookieValid: true, - contextAccessor: contextAccessor); + antiforgeryFeature: antiforgeryFeature); var antiforgery = GetAntiforgery(context); // Act @@ -254,34 +255,31 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal Assert.Null(tokenset.CookieToken); Assert.Equal(context.TestTokenSet.FormTokenString, tokenset.RequestToken); - Assert.NotNull(contextAccessor.Value); - Assert.True(contextAccessor.Value.HaveDeserializedCookieToken); - Assert.Equal(context.TestTokenSet.OldCookieToken, contextAccessor.Value.CookieToken); - Assert.True(contextAccessor.Value.HaveGeneratedNewCookieToken); - Assert.Null(contextAccessor.Value.NewCookieToken); - Assert.Equal(context.TestTokenSet.RequestToken, contextAccessor.Value.NewRequestToken); - Assert.Equal(context.TestTokenSet.FormTokenString, contextAccessor.Value.NewRequestTokenString); + Assert.NotNull(antiforgeryFeature); + Assert.True(antiforgeryFeature.HaveDeserializedCookieToken); + Assert.Equal(context.TestTokenSet.OldCookieToken, antiforgeryFeature.CookieToken); + Assert.True(antiforgeryFeature.HaveGeneratedNewCookieToken); + Assert.Null(antiforgeryFeature.NewCookieToken); + Assert.Equal(context.TestTokenSet.RequestToken, antiforgeryFeature.NewRequestToken); + Assert.Equal(context.TestTokenSet.FormTokenString, antiforgeryFeature.NewRequestTokenString); } [Fact] public void GetTokens_DoesNotSerializeTwice() { // Arrange - var contextAccessor = new DefaultAntiforgeryContextAccessor + var antiforgeryFeature = new AntiforgeryFeature { - Value = new AntiforgeryContext - { - HaveDeserializedCookieToken = true, - HaveGeneratedNewCookieToken = true, - NewRequestToken = new AntiforgeryToken(), - NewRequestTokenString = "serialized-form-token-from-context", - }, + HaveDeserializedCookieToken = true, + HaveGeneratedNewCookieToken = true, + NewRequestToken = new AntiforgeryToken(), + NewRequestTokenString = "serialized-form-token-from-context", }; var context = CreateMockContext( new AntiforgeryOptions(), useOldCookie: true, isOldCookieValid: true, - contextAccessor: contextAccessor); + antiforgeryFeature: antiforgeryFeature); var antiforgery = GetAntiforgery(context); @@ -292,7 +290,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal Assert.Null(tokenset.CookieToken); Assert.Equal("serialized-form-token-from-context", tokenset.RequestToken); - Assert.Null(contextAccessor.Value.NewCookieToken); + Assert.Null(antiforgeryFeature.NewCookieToken); // Token serializer not used. context.TokenSerializer.Verify( @@ -307,12 +305,12 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal public void GetAndStoreTokens_ExistingValidCookieToken_NotOverriden() { // Arrange - var contextAccessor = new DefaultAntiforgeryContextAccessor(); + var antiforgeryFeature = new AntiforgeryFeature(); var context = CreateMockContext( new AntiforgeryOptions(), useOldCookie: true, isOldCookieValid: true, - contextAccessor: contextAccessor); + antiforgeryFeature: antiforgeryFeature); var antiforgery = GetAntiforgery(context); // Act @@ -327,25 +325,25 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal Assert.Null(tokenSet.CookieToken); Assert.Equal(context.TestTokenSet.FormTokenString, tokenSet.RequestToken); - Assert.NotNull(contextAccessor.Value); - Assert.True(contextAccessor.Value.HaveDeserializedCookieToken); - Assert.Equal(context.TestTokenSet.OldCookieToken, contextAccessor.Value.CookieToken); - Assert.True(contextAccessor.Value.HaveGeneratedNewCookieToken); - Assert.Null(contextAccessor.Value.NewCookieToken); - Assert.Equal(context.TestTokenSet.RequestToken, contextAccessor.Value.NewRequestToken); - Assert.Equal(context.TestTokenSet.FormTokenString, contextAccessor.Value.NewRequestTokenString); + Assert.NotNull(antiforgeryFeature); + Assert.True(antiforgeryFeature.HaveDeserializedCookieToken); + Assert.Equal(context.TestTokenSet.OldCookieToken, antiforgeryFeature.CookieToken); + Assert.True(antiforgeryFeature.HaveGeneratedNewCookieToken); + Assert.Null(antiforgeryFeature.NewCookieToken); + Assert.Equal(context.TestTokenSet.RequestToken, antiforgeryFeature.NewRequestToken); + Assert.Equal(context.TestTokenSet.FormTokenString, antiforgeryFeature.NewRequestTokenString); } [Fact] public void GetAndStoreTokens_NoExistingCookieToken_Saved() { // Arrange - var contextAccessor = new DefaultAntiforgeryContextAccessor(); + var antiforgeryFeature = new AntiforgeryFeature(); var context = CreateMockContext( new AntiforgeryOptions(), useOldCookie: false, isOldCookieValid: false, - contextAccessor: contextAccessor); + antiforgeryFeature: antiforgeryFeature); var antiforgery = GetAntiforgery(context); // Act @@ -359,38 +357,35 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal Assert.Equal(context.TestTokenSet.NewCookieTokenString, tokenSet.CookieToken); Assert.Equal(context.TestTokenSet.FormTokenString, tokenSet.RequestToken); - Assert.NotNull(contextAccessor.Value); - Assert.True(contextAccessor.Value.HaveDeserializedCookieToken); - Assert.Equal(context.TestTokenSet.OldCookieToken, contextAccessor.Value.CookieToken); - Assert.True(contextAccessor.Value.HaveGeneratedNewCookieToken); - Assert.Equal(context.TestTokenSet.NewCookieToken, contextAccessor.Value.NewCookieToken); - Assert.Equal(context.TestTokenSet.NewCookieTokenString, contextAccessor.Value.NewCookieTokenString); - Assert.Equal(context.TestTokenSet.RequestToken, contextAccessor.Value.NewRequestToken); - Assert.Equal(context.TestTokenSet.FormTokenString, contextAccessor.Value.NewRequestTokenString); - Assert.True(contextAccessor.Value.HaveStoredNewCookieToken); + Assert.NotNull(antiforgeryFeature); + Assert.True(antiforgeryFeature.HaveDeserializedCookieToken); + Assert.Equal(context.TestTokenSet.OldCookieToken, antiforgeryFeature.CookieToken); + Assert.True(antiforgeryFeature.HaveGeneratedNewCookieToken); + Assert.Equal(context.TestTokenSet.NewCookieToken, antiforgeryFeature.NewCookieToken); + Assert.Equal(context.TestTokenSet.NewCookieTokenString, antiforgeryFeature.NewCookieTokenString); + Assert.Equal(context.TestTokenSet.RequestToken, antiforgeryFeature.NewRequestToken); + Assert.Equal(context.TestTokenSet.FormTokenString, antiforgeryFeature.NewRequestTokenString); + Assert.True(antiforgeryFeature.HaveStoredNewCookieToken); } [Fact] public void GetAndStoreTokens_DoesNotSerializeTwice() { // Arrange - var contextAccessor = new DefaultAntiforgeryContextAccessor + var antiforgeryFeature = new AntiforgeryFeature { - Value = new AntiforgeryContext - { - HaveDeserializedCookieToken = true, - HaveGeneratedNewCookieToken = true, - NewCookieToken = new AntiforgeryToken(), - NewCookieTokenString = "serialized-cookie-token-from-context", - NewRequestToken = new AntiforgeryToken(), - NewRequestTokenString = "serialized-form-token-from-context", - }, + HaveDeserializedCookieToken = true, + HaveGeneratedNewCookieToken = true, + NewCookieToken = new AntiforgeryToken(), + NewCookieTokenString = "serialized-cookie-token-from-context", + NewRequestToken = new AntiforgeryToken(), + NewRequestTokenString = "serialized-form-token-from-context", }; var context = CreateMockContext( new AntiforgeryOptions(), useOldCookie: true, isOldCookieValid: true, - contextAccessor: contextAccessor); + antiforgeryFeature: antiforgeryFeature); var antiforgery = GetAntiforgery(context); context.TokenStore @@ -418,31 +413,28 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal Assert.Equal("serialized-cookie-token-from-context", tokenset.CookieToken); Assert.Equal("serialized-form-token-from-context", tokenset.RequestToken); - Assert.True(contextAccessor.Value.HaveStoredNewCookieToken); + Assert.True(antiforgeryFeature.HaveStoredNewCookieToken); } [Fact] public void GetAndStoreTokens_DoesNotStoreTwice() { // Arrange - var contextAccessor = new DefaultAntiforgeryContextAccessor + var antiforgeryFeature = new AntiforgeryFeature { - Value = new AntiforgeryContext - { - HaveDeserializedCookieToken = true, - HaveGeneratedNewCookieToken = true, - HaveStoredNewCookieToken = true, - NewCookieToken = new AntiforgeryToken(), - NewCookieTokenString = "serialized-cookie-token-from-context", - NewRequestToken = new AntiforgeryToken(), - NewRequestTokenString = "serialized-form-token-from-context", - }, + HaveDeserializedCookieToken = true, + HaveGeneratedNewCookieToken = true, + HaveStoredNewCookieToken = true, + NewCookieToken = new AntiforgeryToken(), + NewCookieTokenString = "serialized-cookie-token-from-context", + NewRequestToken = new AntiforgeryToken(), + NewRequestTokenString = "serialized-form-token-from-context", }; var context = CreateMockContext( new AntiforgeryOptions(), useOldCookie: true, isOldCookieValid: true, - contextAccessor: contextAccessor); + antiforgeryFeature: antiforgeryFeature); var antiforgery = GetAntiforgery(context); // Act @@ -470,8 +462,8 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal public async Task IsRequestValidAsync_FromStore_Failure() { // Arrange - var contextAccessor = new DefaultAntiforgeryContextAccessor(); - var context = CreateMockContext(new AntiforgeryOptions(), contextAccessor: contextAccessor); + var antiforgeryFeature = new AntiforgeryFeature(); + var context = CreateMockContext(new AntiforgeryOptions(), antiforgeryFeature: antiforgeryFeature); string message; context.TokenGenerator @@ -493,19 +485,19 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal context.TokenGenerator.Verify(); // Failed _after_ updating the AntiforgeryContext. - Assert.NotNull(contextAccessor.Value); - Assert.True(contextAccessor.Value.HaveDeserializedCookieToken); - Assert.Equal(context.TestTokenSet.OldCookieToken, contextAccessor.Value.CookieToken); - Assert.True(contextAccessor.Value.HaveDeserializedRequestToken); - Assert.Equal(context.TestTokenSet.RequestToken, contextAccessor.Value.RequestToken); + Assert.NotNull(antiforgeryFeature); + Assert.True(antiforgeryFeature.HaveDeserializedCookieToken); + Assert.Equal(context.TestTokenSet.OldCookieToken, antiforgeryFeature.CookieToken); + Assert.True(antiforgeryFeature.HaveDeserializedRequestToken); + Assert.Equal(context.TestTokenSet.RequestToken, antiforgeryFeature.RequestToken); } [Fact] public async Task IsRequestValidAsync_FromStore_Success() { // Arrange - var contextAccessor = new DefaultAntiforgeryContextAccessor(); - var context = CreateMockContext(new AntiforgeryOptions(), contextAccessor: contextAccessor); + var antiforgeryFeature = new AntiforgeryFeature(); + var context = CreateMockContext(new AntiforgeryOptions(), antiforgeryFeature: antiforgeryFeature); context.HttpContext.Request.Method = "POST"; string message; @@ -528,28 +520,25 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal Assert.True(result); context.TokenGenerator.Verify(); - Assert.NotNull(contextAccessor.Value); - Assert.True(contextAccessor.Value.HaveDeserializedCookieToken); - Assert.Equal(context.TestTokenSet.OldCookieToken, contextAccessor.Value.CookieToken); - Assert.True(contextAccessor.Value.HaveDeserializedRequestToken); - Assert.Equal(context.TestTokenSet.RequestToken, contextAccessor.Value.RequestToken); + Assert.NotNull(antiforgeryFeature); + Assert.True(antiforgeryFeature.HaveDeserializedCookieToken); + Assert.Equal(context.TestTokenSet.OldCookieToken, antiforgeryFeature.CookieToken); + Assert.True(antiforgeryFeature.HaveDeserializedRequestToken); + Assert.Equal(context.TestTokenSet.RequestToken, antiforgeryFeature.RequestToken); } [Fact] public async Task IsRequestValidAsync_DoesNotDeserializeTwice() { // Arrange - var contextAccessor = new DefaultAntiforgeryContextAccessor + var antiforgeryFeature = new AntiforgeryFeature { - Value = new AntiforgeryContext - { - HaveDeserializedCookieToken = true, - CookieToken = new AntiforgeryToken(), - HaveDeserializedRequestToken = true, - RequestToken = new AntiforgeryToken(), - }, + HaveDeserializedCookieToken = true, + CookieToken = new AntiforgeryToken(), + HaveDeserializedRequestToken = true, + RequestToken = new AntiforgeryToken(), }; - var context = CreateMockContext(new AntiforgeryOptions(), contextAccessor: contextAccessor); + var context = CreateMockContext(new AntiforgeryOptions(), antiforgeryFeature: antiforgeryFeature); context.HttpContext.Request.Method = "POST"; string message; @@ -557,8 +546,8 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal .Setup(o => o.TryValidateTokenSet( context.HttpContext, It.IsAny(), - contextAccessor.Value.CookieToken, - contextAccessor.Value.RequestToken, + antiforgeryFeature.CookieToken, + antiforgeryFeature.RequestToken, out message)) .Returns(true) .Verifiable(); @@ -712,8 +701,8 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal public async Task ValidateRequestAsync_FromStore_Failure() { // Arrange - var contextAccessor = new DefaultAntiforgeryContextAccessor(); - var context = CreateMockContext(new AntiforgeryOptions(), contextAccessor: contextAccessor); + var antiforgeryFeature = new AntiforgeryFeature(); + var context = CreateMockContext(new AntiforgeryOptions(), antiforgeryFeature: antiforgeryFeature); var message = "my-message"; context.TokenGenerator @@ -734,19 +723,19 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal context.TokenGenerator.Verify(); // Failed _after_ updating the AntiforgeryContext. - Assert.NotNull(contextAccessor.Value); - Assert.True(contextAccessor.Value.HaveDeserializedCookieToken); - Assert.Equal(context.TestTokenSet.OldCookieToken, contextAccessor.Value.CookieToken); - Assert.True(contextAccessor.Value.HaveDeserializedRequestToken); - Assert.Equal(context.TestTokenSet.RequestToken, contextAccessor.Value.RequestToken); + Assert.NotNull(antiforgeryFeature); + Assert.True(antiforgeryFeature.HaveDeserializedCookieToken); + Assert.Equal(context.TestTokenSet.OldCookieToken, antiforgeryFeature.CookieToken); + Assert.True(antiforgeryFeature.HaveDeserializedRequestToken); + Assert.Equal(context.TestTokenSet.RequestToken, antiforgeryFeature.RequestToken); } [Fact] public async Task ValidateRequestAsync_FromStore_Success() { // Arrange - var contextAccessor = new DefaultAntiforgeryContextAccessor(); - var context = CreateMockContext(new AntiforgeryOptions(), contextAccessor: contextAccessor); + var antiforgeryFeature = new AntiforgeryFeature(); + var context = CreateMockContext(new AntiforgeryOptions(), antiforgeryFeature: antiforgeryFeature); string message; context.TokenGenerator @@ -767,11 +756,11 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal // Assert context.TokenGenerator.Verify(); - Assert.NotNull(contextAccessor.Value); - Assert.True(contextAccessor.Value.HaveDeserializedCookieToken); - Assert.Equal(context.TestTokenSet.OldCookieToken, contextAccessor.Value.CookieToken); - Assert.True(contextAccessor.Value.HaveDeserializedRequestToken); - Assert.Equal(context.TestTokenSet.RequestToken, contextAccessor.Value.RequestToken); + Assert.NotNull(antiforgeryFeature); + Assert.True(antiforgeryFeature.HaveDeserializedCookieToken); + Assert.Equal(context.TestTokenSet.OldCookieToken, antiforgeryFeature.CookieToken); + Assert.True(antiforgeryFeature.HaveDeserializedRequestToken); + Assert.Equal(context.TestTokenSet.RequestToken, antiforgeryFeature.RequestToken); } [Fact] @@ -881,25 +870,22 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal public async Task ValidateRequestAsync_DoesNotDeserializeTwice() { // Arrange - var contextAccessor = new DefaultAntiforgeryContextAccessor + var antiforgeryFeature = new AntiforgeryFeature { - Value = new AntiforgeryContext - { - HaveDeserializedCookieToken = true, - CookieToken = new AntiforgeryToken(), - HaveDeserializedRequestToken = true, - RequestToken = new AntiforgeryToken(), - }, + HaveDeserializedCookieToken = true, + CookieToken = new AntiforgeryToken(), + HaveDeserializedRequestToken = true, + RequestToken = new AntiforgeryToken(), }; - var context = CreateMockContext(new AntiforgeryOptions(), contextAccessor: contextAccessor); + var context = CreateMockContext(new AntiforgeryOptions(), antiforgeryFeature: antiforgeryFeature); string message; context.TokenGenerator .Setup(o => o.TryValidateTokenSet( context.HttpContext, It.IsAny(), - contextAccessor.Value.CookieToken, - contextAccessor.Value.RequestToken, + antiforgeryFeature.CookieToken, + antiforgeryFeature.RequestToken, out message)) .Returns(true) .Verifiable(); @@ -1056,14 +1042,14 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal { SuppressXFrameOptionsHeader = suppressXFrameOptions }; - var contextAccessor = new DefaultAntiforgeryContextAccessor(); + var antiforgeryFeature = new AntiforgeryFeature(); // Generate a new cookie. var context = CreateMockContext( options, useOldCookie: false, isOldCookieValid: false, - contextAccessor: contextAccessor); + antiforgeryFeature: antiforgeryFeature); var antiforgery = GetAntiforgery(context); // Act @@ -1073,36 +1059,33 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal var xFrameOptions = context.HttpContext.Response.Headers["X-Frame-Options"]; Assert.Equal(expectedHeaderValue, xFrameOptions); - Assert.NotNull(contextAccessor.Value); - Assert.True(contextAccessor.Value.HaveDeserializedCookieToken); - Assert.Equal(context.TestTokenSet.OldCookieToken, contextAccessor.Value.CookieToken); - Assert.True(contextAccessor.Value.HaveGeneratedNewCookieToken); - Assert.Equal(context.TestTokenSet.NewCookieToken, contextAccessor.Value.NewCookieToken); - Assert.Equal(context.TestTokenSet.NewCookieTokenString, contextAccessor.Value.NewCookieTokenString); - Assert.True(contextAccessor.Value.HaveStoredNewCookieToken); + Assert.NotNull(antiforgeryFeature); + Assert.True(antiforgeryFeature.HaveDeserializedCookieToken); + Assert.Equal(context.TestTokenSet.OldCookieToken, antiforgeryFeature.CookieToken); + Assert.True(antiforgeryFeature.HaveGeneratedNewCookieToken); + Assert.Equal(context.TestTokenSet.NewCookieToken, antiforgeryFeature.NewCookieToken); + Assert.Equal(context.TestTokenSet.NewCookieTokenString, antiforgeryFeature.NewCookieTokenString); + Assert.True(antiforgeryFeature.HaveStoredNewCookieToken); } [Fact] public void SetCookieTokenAndHeader_DoesNotDeserializeTwice() { // Arrange - var contextAccessor = new DefaultAntiforgeryContextAccessor + var antiforgeryFeature = new AntiforgeryFeature { - Value = new AntiforgeryContext - { - HaveDeserializedCookieToken = true, - HaveGeneratedNewCookieToken = true, - NewCookieToken = new AntiforgeryToken(), - NewCookieTokenString = "serialized-cookie-token-from-context", - NewRequestToken = new AntiforgeryToken(), - NewRequestTokenString = "serialized-form-token-from-context", - }, + HaveDeserializedCookieToken = true, + HaveGeneratedNewCookieToken = true, + NewCookieToken = new AntiforgeryToken(), + NewCookieTokenString = "serialized-cookie-token-from-context", + NewRequestToken = new AntiforgeryToken(), + NewRequestTokenString = "serialized-form-token-from-context", }; var context = CreateMockContext( new AntiforgeryOptions(), useOldCookie: true, isOldCookieValid: true, - contextAccessor: contextAccessor); + antiforgeryFeature: antiforgeryFeature); var antiforgery = GetAntiforgery(context); context.TokenStore @@ -1132,24 +1115,21 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal public void SetCookieTokenAndHeader_DoesNotStoreTwice() { // Arrange - var contextAccessor = new DefaultAntiforgeryContextAccessor + var antiforgeryFeature = new AntiforgeryFeature { - Value = new AntiforgeryContext - { - HaveDeserializedCookieToken = true, - HaveGeneratedNewCookieToken = true, - HaveStoredNewCookieToken = true, - NewCookieToken = new AntiforgeryToken(), - NewCookieTokenString = "serialized-cookie-token-from-context", - NewRequestToken = new AntiforgeryToken(), - NewRequestTokenString = "serialized-form-token-from-context", - }, + HaveDeserializedCookieToken = true, + HaveGeneratedNewCookieToken = true, + HaveStoredNewCookieToken = true, + NewCookieToken = new AntiforgeryToken(), + NewCookieTokenString = "serialized-cookie-token-from-context", + NewRequestToken = new AntiforgeryToken(), + NewRequestTokenString = "serialized-form-token-from-context", }; var context = CreateMockContext( new AntiforgeryOptions(), useOldCookie: true, isOldCookieValid: true, - contextAccessor: contextAccessor); + antiforgeryFeature: antiforgeryFeature); var antiforgery = GetAntiforgery(context); // Act @@ -1192,21 +1172,20 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal loggerFactory: loggerFactory); } - private IServiceProvider GetServices(IAntiforgeryContextAccessor contextAccessor) + private IServiceProvider GetServices() { var builder = new ServiceCollection(); - builder.AddSingleton(contextAccessor); builder.AddSingleton(new LoggerFactory()); return builder.BuildServiceProvider(); } - private HttpContext GetHttpContext(IAntiforgeryContextAccessor contextAccessor = null) + private HttpContext GetHttpContext(IAntiforgeryFeature antiforgeryFeature = null) { var httpContext = new DefaultHttpContext(); - contextAccessor = contextAccessor ?? new DefaultAntiforgeryContextAccessor(); - httpContext.RequestServices = GetServices(contextAccessor); - + antiforgeryFeature = antiforgeryFeature ?? new AntiforgeryFeature(); + httpContext.Features.Set(antiforgeryFeature); + httpContext.RequestServices = GetServices(); httpContext.User = new ClaimsPrincipal(new ClaimsIdentity("some-auth")); return httpContext; @@ -1276,10 +1255,10 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal AntiforgeryOptions options, bool useOldCookie = false, bool isOldCookieValid = true, - IAntiforgeryContextAccessor contextAccessor = null) + IAntiforgeryFeature antiforgeryFeature = null) { // Arrange - var httpContext = GetHttpContext(contextAccessor); + var httpContext = GetHttpContext(antiforgeryFeature); var testTokenSet = GetTokenSet(); var mockSerializer = GetTokenSerializer(testTokenSet); From 4d64c1849ddfa7a4ae08bb7d1c758311949504a1 Mon Sep 17 00:00:00 2001 From: John Luo Date: Tue, 22 Mar 2016 11:55:44 -0700 Subject: [PATCH 110/296] Reacting to Hosting changes --- samples/AntiforgerySample/Startup.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/samples/AntiforgerySample/Startup.cs b/samples/AntiforgerySample/Startup.cs index c8f6263b7b..d56e72aca6 100644 --- a/samples/AntiforgerySample/Startup.cs +++ b/samples/AntiforgerySample/Startup.cs @@ -69,7 +69,7 @@ namespace AntiforgerySample public static void Main(string[] args) { var host = new WebHostBuilder() - .UseDefaultConfiguration(args) + .UseDefaultHostingConfiguration(args) .UseServer("Microsoft.AspNetCore.Server.Kestrel") .UseIISPlatformHandlerUrl() .UseStartup() From c6f7a3434e31f7af3d01a63f1161f242fe8dd1b4 Mon Sep 17 00:00:00 2001 From: David Fowler Date: Fri, 25 Mar 2016 10:50:06 -0700 Subject: [PATCH 111/296] Fixed build --- .../project.json | 7 ++++--- test/Microsoft.AspNetCore.Antiforgery.Test/project.json | 5 +++-- 2 files changed, 7 insertions(+), 5 deletions(-) diff --git a/test/Microsoft.AspNetCore.Antiforgery.FunctionalTests/project.json b/test/Microsoft.AspNetCore.Antiforgery.FunctionalTests/project.json index 7b345f04fe..c26724bfb1 100644 --- a/test/Microsoft.AspNetCore.Antiforgery.FunctionalTests/project.json +++ b/test/Microsoft.AspNetCore.Antiforgery.FunctionalTests/project.json @@ -2,8 +2,7 @@ "dependencies": { "AntiforgerySample": "1.0.0-*", "Microsoft.AspNetCore.TestHost": "1.0.0-*", - "Microsoft.AspNetCore.Testing": "1.0.0-*", - "Microsoft.NETCore.Platforms": "1.0.1-*" + "Microsoft.AspNetCore.Testing": "1.0.0-*" }, "testRunner": "xunit", "frameworks": { @@ -11,7 +10,9 @@ "dependencies": { "moq.netcore": "4.4.0-beta8", "System.Net.Http": "4.0.1-*", - "dotnet-test-xunit": "1.0.0-dev-*" + "dotnet-test-xunit": "1.0.0-dev-*", + "NETStandard.Library": "1.5.0-*", + "System.Diagnostics.Process": "4.1.0-*" }, "imports": [ "dnxcore50", diff --git a/test/Microsoft.AspNetCore.Antiforgery.Test/project.json b/test/Microsoft.AspNetCore.Antiforgery.Test/project.json index 0ac8f81de0..d9a5c2fd95 100644 --- a/test/Microsoft.AspNetCore.Antiforgery.Test/project.json +++ b/test/Microsoft.AspNetCore.Antiforgery.Test/project.json @@ -10,7 +10,6 @@ "Microsoft.Extensions.DependencyInjection": "1.0.0-*", "Microsoft.Extensions.Logging": "1.0.0-*", "Microsoft.Extensions.WebEncoders": "1.0.0-*", - "Microsoft.NETCore.Platforms": "1.0.1-*", "xunit": "2.1.0-*" }, "testRunner": "xunit", @@ -18,7 +17,9 @@ "netstandardapp1.5": { "dependencies": { "moq.netcore": "4.4.0-beta8", - "dotnet-test-xunit": "1.0.0-dev-*" + "dotnet-test-xunit": "1.0.0-dev-*", + "NETStandard.Library": "1.5.0-*", + "System.Diagnostics.Process": "4.1.0-*" }, "imports": [ "dnxcore50", From 0c81df859145801d2846ccbdc9af5830fa791f63 Mon Sep 17 00:00:00 2001 From: Doug Bunting Date: Thu, 24 Mar 2016 15:49:20 -0700 Subject: [PATCH 112/296] An `ObjectPoolProvider` is always registered - react to aspnet/Hosting/pull#673 --- .../ServiceCollectionExtensions.cs | 1 - src/Microsoft.AspNetCore.Antiforgery/project.json | 3 +-- 2 files changed, 1 insertion(+), 3 deletions(-) diff --git a/src/Microsoft.AspNetCore.Antiforgery/ServiceCollectionExtensions.cs b/src/Microsoft.AspNetCore.Antiforgery/ServiceCollectionExtensions.cs index bc07489e2c..dfabbe80e3 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/ServiceCollectionExtensions.cs +++ b/src/Microsoft.AspNetCore.Antiforgery/ServiceCollectionExtensions.cs @@ -39,7 +39,6 @@ namespace Microsoft.Extensions.DependencyInjection services.TryAddSingleton(); services.TryAddSingleton(); - services.TryAddSingleton(new DefaultObjectPoolProvider()); services.TryAddSingleton>(serviceProvider => { var provider = serviceProvider.GetRequiredService(); diff --git a/src/Microsoft.AspNetCore.Antiforgery/project.json b/src/Microsoft.AspNetCore.Antiforgery/project.json index e1d6fe15b6..b207394d87 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/project.json +++ b/src/Microsoft.AspNetCore.Antiforgery/project.json @@ -19,8 +19,7 @@ }, "dependencies": { "Microsoft.AspNetCore.DataProtection": "1.0.0-*", - "Microsoft.AspNetCore.Http": "1.0.0-*", - "Microsoft.Extensions.ObjectPool": "1.0.0-*" + "Microsoft.AspNetCore.Http": "1.0.0-*" }, "frameworks": { "netstandard1.3": { From 0bc42a9b21acb5ade5c305263c5949d021794158 Mon Sep 17 00:00:00 2001 From: jacalvar Date: Mon, 28 Mar 2016 14:59:08 -0700 Subject: [PATCH 113/296] Return IServiceCollection from AddAntiforgery extension methods --- .../ServiceCollectionExtensions.cs | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/src/Microsoft.AspNetCore.Antiforgery/ServiceCollectionExtensions.cs b/src/Microsoft.AspNetCore.Antiforgery/ServiceCollectionExtensions.cs index dfabbe80e3..c16ac5c255 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/ServiceCollectionExtensions.cs +++ b/src/Microsoft.AspNetCore.Antiforgery/ServiceCollectionExtensions.cs @@ -19,7 +19,8 @@ namespace Microsoft.Extensions.DependencyInjection /// Adds antiforgery services to the specified . /// /// The to add services to. - public static void AddAntiforgery(this IServiceCollection services) + /// The so that additional calls can be chained. + public static IServiceCollection AddAntiforgery(this IServiceCollection services) { if (services == null) { @@ -45,6 +46,8 @@ namespace Microsoft.Extensions.DependencyInjection var policy = new AntiforgerySerializationContextPooledObjectPolicy(); return provider.Create(policy); }); + + return services; } /// @@ -52,7 +55,8 @@ namespace Microsoft.Extensions.DependencyInjection /// /// The to add services to. /// An to configure the provided . - public static void AddAntiforgery(this IServiceCollection services, Action setupAction) + /// The so that additional calls can be chained. + public static IServiceCollection AddAntiforgery(this IServiceCollection services, Action setupAction) { if (services == null) { @@ -66,6 +70,7 @@ namespace Microsoft.Extensions.DependencyInjection services.AddAntiforgery(); services.Configure(setupAction); + return services; } } } From ea4b94a75711991c6468c99b852abd66657617b9 Mon Sep 17 00:00:00 2001 From: Victor Hurdugaci Date: Wed, 30 Mar 2016 10:27:16 -0700 Subject: [PATCH 114/296] Add webhook notification --- .travis.yml | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index 304e307169..dd00cf00cc 100644 --- a/.travis.yml +++ b/.travis.yml @@ -23,4 +23,10 @@ branches: - dev - /^(.*\/)?ci-.*$/ script: - - ./build.sh --quiet verify \ No newline at end of file + - ./build.sh --quiet verify +notifications: + webhooks: + secure: "dzKsW/YJVie2UeYKMlKFA9dcHv0WpF4IKd7z/yEhV96eB5e2Pls+vtQFUP86Wg/fcqeLHAmb0GazXnomPg2cX13ihz+mF0hCvA58UTczNpwwfTZd7VHQe9Ti93Zoo49HkTFBbIDMns9eUxhcEo4T4lC85dG4ZRz7v8X6/Nlr71PMIGYI29Uyur/1oPrnNI7DBweOY4Z1Xhl5cfaSPd945VM8QPHeM494XGmgldGpIZs+LjZbA8S3xxB0YaxpAwGKO4gWSXL2fP4y1z5rFEY1JZamPaedA3dICVi3BVDjJ4l3sn3fEBxOAv8QwjHvSu0xWK/MAIX/SmY7ScgIND+UMjGFTaeZLYN18hJDm+a4mAx/tPaqsOGAKm9F/aVQAzP0g4z+VAVDz1iqxDWe+x/cK4DPjUbLXpP6Y6jtrVES/TkKNuLNA/NUOp+vDPXieDaQAmeU2l6M2el1PscQPtla6KIS1oDDiuHeWC/b4suCAJVsads25y7KyncmmwYE1Tgh1sUJa+Vk9c/hxiIuDJQUWxmi/4BGjDYO29y60jc2niimzvQ3sV2x+Rh81zJaLWXNYdIgugzQpe4nG8wQDbLuEAlfINBt7cIxw3MK3ov4MV5MVRaDVMEm0A5yIN9Mz83USPkuXxfhGtOo6YU1Ny/D2bjc9LI7lGHbjQtFlJa6U6c=" + on_success: always + on_failure: always + on_start: always \ No newline at end of file From d0ed4f86883f7204e0ff3014bf85954ef642d1c6 Mon Sep 17 00:00:00 2001 From: John Luo Date: Wed, 30 Mar 2016 15:54:02 -0700 Subject: [PATCH 115/296] Reacting to Kestrel extensions --- samples/AntiforgerySample/Startup.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/samples/AntiforgerySample/Startup.cs b/samples/AntiforgerySample/Startup.cs index d56e72aca6..df60314f9c 100644 --- a/samples/AntiforgerySample/Startup.cs +++ b/samples/AntiforgerySample/Startup.cs @@ -70,7 +70,7 @@ namespace AntiforgerySample { var host = new WebHostBuilder() .UseDefaultHostingConfiguration(args) - .UseServer("Microsoft.AspNetCore.Server.Kestrel") + .UseKestrel() .UseIISPlatformHandlerUrl() .UseStartup() .Build(); @@ -79,3 +79,4 @@ namespace AntiforgerySample } } } + From 65a2b8d25b8f17f2d061d05ae964ab5cb85f086a Mon Sep 17 00:00:00 2001 From: Doug Bunting Date: Sun, 27 Mar 2016 20:56:01 -0700 Subject: [PATCH 116/296] React to HttpAbstractions namespace changes - aspnet/HttpAbstractions#549 and aspnet/HttpAbstractions#592 - clean up `using`s --- .../Internal/AntiforgeryAuthenticationHandler.cs | 1 - .../AntiforgeryMiddlewareTest.cs | 2 -- .../Internal/AntiforgeryAuthenticationHandlerTest.cs | 2 -- .../Internal/DefaultAntiforgeryTest.cs | 2 -- .../Internal/DefaultAntiforgeryTokenGeneratorTest.cs | 3 +-- 5 files changed, 1 insertion(+), 9 deletions(-) diff --git a/src/Microsoft.AspNetCore.Antiforgery/Internal/AntiforgeryAuthenticationHandler.cs b/src/Microsoft.AspNetCore.Antiforgery/Internal/AntiforgeryAuthenticationHandler.cs index c3abeb0ac6..cffa86c5e4 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/Internal/AntiforgeryAuthenticationHandler.cs +++ b/src/Microsoft.AspNetCore.Antiforgery/Internal/AntiforgeryAuthenticationHandler.cs @@ -5,7 +5,6 @@ using System; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.Features.Authentication; -using Microsoft.AspNetCore.Http.Features.Authentication.Internal; namespace Microsoft.AspNetCore.Antiforgery.Internal { diff --git a/test/Microsoft.AspNetCore.Antiforgery.Test/AntiforgeryMiddlewareTest.cs b/test/Microsoft.AspNetCore.Antiforgery.Test/AntiforgeryMiddlewareTest.cs index 56c606c847..54e40e7d93 100644 --- a/test/Microsoft.AspNetCore.Antiforgery.Test/AntiforgeryMiddlewareTest.cs +++ b/test/Microsoft.AspNetCore.Antiforgery.Test/AntiforgeryMiddlewareTest.cs @@ -9,8 +9,6 @@ using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Builder.Internal; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.Features.Authentication; -using Microsoft.AspNetCore.Http.Features.Authentication.Internal; -using Microsoft.AspNetCore.Http.Internal; using Microsoft.Extensions.DependencyInjection; using Moq; using Xunit; diff --git a/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/AntiforgeryAuthenticationHandlerTest.cs b/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/AntiforgeryAuthenticationHandlerTest.cs index 670f818bf7..331cef1be4 100644 --- a/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/AntiforgeryAuthenticationHandlerTest.cs +++ b/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/AntiforgeryAuthenticationHandlerTest.cs @@ -5,8 +5,6 @@ using System.Security.Claims; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.Features.Authentication; -using Microsoft.AspNetCore.Http.Features.Authentication.Internal; -using Microsoft.AspNetCore.Http.Internal; using Moq; using Xunit; diff --git a/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTest.cs b/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTest.cs index 776284ff72..0677d73a0d 100644 --- a/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTest.cs +++ b/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTest.cs @@ -5,8 +5,6 @@ using System; using System.Security.Claims; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; -using Microsoft.AspNetCore.Http.Features; -using Microsoft.AspNetCore.Http.Internal; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; diff --git a/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTokenGeneratorTest.cs b/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTokenGeneratorTest.cs index 1720d93b95..94379071c5 100644 --- a/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTokenGeneratorTest.cs +++ b/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTokenGeneratorTest.cs @@ -2,10 +2,9 @@ // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; -using System.Collections.Generic; using System.Security.Claims; using System.Security.Cryptography; -using Microsoft.AspNetCore.Http.Internal; +using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Testing; using Moq; using Xunit; From fab3bfd23765692c64daefd33fef1e6493eadfba Mon Sep 17 00:00:00 2001 From: Pranav K Date: Thu, 31 Mar 2016 07:01:27 -0700 Subject: [PATCH 117/296] Remove bower \ gulp from sample --- samples/AntiforgerySample/bower.json | 8 -------- samples/AntiforgerySample/gulpfile.js | 18 ------------------ samples/AntiforgerySample/package.json | 9 --------- samples/AntiforgerySample/wwwroot/Index.html | 4 ++-- 4 files changed, 2 insertions(+), 37 deletions(-) delete mode 100644 samples/AntiforgerySample/bower.json delete mode 100644 samples/AntiforgerySample/gulpfile.js delete mode 100644 samples/AntiforgerySample/package.json diff --git a/samples/AntiforgerySample/bower.json b/samples/AntiforgerySample/bower.json deleted file mode 100644 index 89471a5f27..0000000000 --- a/samples/AntiforgerySample/bower.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "name": "ASP.NET", - "private": true, - "dependencies": { - "angular": "~1.4.8", - "bootstrap-css": "~3.3.4" - } -} diff --git a/samples/AntiforgerySample/gulpfile.js b/samples/AntiforgerySample/gulpfile.js deleted file mode 100644 index dedfea6f45..0000000000 --- a/samples/AntiforgerySample/gulpfile.js +++ /dev/null @@ -1,18 +0,0 @@ -/// -"use strict"; - -var gulp = require("gulp"), - bowerFiles = require('main-bower-files'); - -var paths = { - webroot: "./wwwroot/" -}; - -paths.bowerFilesDest = paths.webroot + '/bower_components'; - -gulp.task("copy:bower", function () { - return gulp.src(bowerFiles()).pipe(gulp.dest(paths.bowerFilesDest)); -}); - -gulp.task("default", ["copy:bower"]); - diff --git a/samples/AntiforgerySample/package.json b/samples/AntiforgerySample/package.json deleted file mode 100644 index cad917e2a0..0000000000 --- a/samples/AntiforgerySample/package.json +++ /dev/null @@ -1,9 +0,0 @@ -{ - "name": "ASP.NET", - "private": true, - "version": "0.0.0", - "devDependencies": { - "gulp": "^3.9.0", - "main-bower-files": "^2.9.0" - } -} diff --git a/samples/AntiforgerySample/wwwroot/Index.html b/samples/AntiforgerySample/wwwroot/Index.html index 7789fe514b..ca705a4666 100644 --- a/samples/AntiforgerySample/wwwroot/Index.html +++ b/samples/AntiforgerySample/wwwroot/Index.html @@ -4,7 +4,7 @@ Todo List Antiforgery Sample - +
@@ -38,7 +38,7 @@
- + From 37c8f5de70c0e446a1842064d70b2094c039ad4a Mon Sep 17 00:00:00 2001 From: Ryan Nowak Date: Fri, 1 Apr 2016 08:15:47 -0700 Subject: [PATCH 118/296] Revert "Add antiforgery middleware" This reverts commit 4629148519cde61200c3871d9ab943607aef3e5d. --- .../AntiforgeryBuilderExtensions.cs | 29 -- .../AntiforgeryMiddleware.cs | 65 --- .../IAntiforgery.cs | 23 -- .../AntiforgeryAuthenticationHandler.cs | 160 -------- .../Internal/DefaultAntiforgery.cs | 78 +--- .../DefaultAntiforgeryTokenGenerator.cs | 10 +- .../Internal/IAntiforgeryTokenGenerator.cs | 9 +- .../Internal/TaskCache.cs | 12 - .../project.json | 4 +- .../AntiforgeryMiddlewareTest.cs | 380 ------------------ .../AntiforgeryAuthenticationHandlerTest.cs | 291 -------------- .../Internal/DefaultAntiforgeryTest.cs | 262 +----------- .../DefaultAntiforgeryTokenGeneratorTest.cs | 68 ++-- 13 files changed, 60 insertions(+), 1331 deletions(-) delete mode 100644 src/Microsoft.AspNetCore.Antiforgery/AntiforgeryBuilderExtensions.cs delete mode 100644 src/Microsoft.AspNetCore.Antiforgery/AntiforgeryMiddleware.cs delete mode 100644 src/Microsoft.AspNetCore.Antiforgery/Internal/AntiforgeryAuthenticationHandler.cs delete mode 100644 src/Microsoft.AspNetCore.Antiforgery/Internal/TaskCache.cs delete mode 100644 test/Microsoft.AspNetCore.Antiforgery.Test/AntiforgeryMiddlewareTest.cs delete mode 100644 test/Microsoft.AspNetCore.Antiforgery.Test/Internal/AntiforgeryAuthenticationHandlerTest.cs diff --git a/src/Microsoft.AspNetCore.Antiforgery/AntiforgeryBuilderExtensions.cs b/src/Microsoft.AspNetCore.Antiforgery/AntiforgeryBuilderExtensions.cs deleted file mode 100644 index 7181518dfb..0000000000 --- a/src/Microsoft.AspNetCore.Antiforgery/AntiforgeryBuilderExtensions.cs +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using Microsoft.AspNetCore.Antiforgery; - -namespace Microsoft.AspNetCore.Builder -{ - /// - /// Extension methods for configuring the antiforgery middleware. - /// - public static class AntiforgeryBuilderExtensions - { - /// - /// Adds the antiforgery middleware. - /// - /// The . - /// The . - public static IApplicationBuilder UseAntiforgery(this IApplicationBuilder app) - { - if (app == null) - { - throw new ArgumentNullException(nameof(app)); - } - - return app.UseMiddleware(); - } - } -} diff --git a/src/Microsoft.AspNetCore.Antiforgery/AntiforgeryMiddleware.cs b/src/Microsoft.AspNetCore.Antiforgery/AntiforgeryMiddleware.cs deleted file mode 100644 index eccadfd699..0000000000 --- a/src/Microsoft.AspNetCore.Antiforgery/AntiforgeryMiddleware.cs +++ /dev/null @@ -1,65 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Threading.Tasks; -using Microsoft.AspNetCore.Antiforgery.Internal; -using Microsoft.AspNetCore.Http; - -namespace Microsoft.AspNetCore.Antiforgery -{ - /// - /// A middleware implementation of antiforgery validation. - /// - public class AntiforgeryMiddleware - { - private readonly IAntiforgery _antiforgery; - private readonly RequestDelegate _next; - - /// - /// Creates a new . - /// - /// The for the next middleware. - /// The . - public AntiforgeryMiddleware(RequestDelegate next, IAntiforgery antiforgery) - { - if (next == null) - { - throw new ArgumentNullException(nameof(next)); - } - - if (antiforgery == null) - { - throw new ArgumentNullException(nameof(antiforgery)); - } - - _next = next; - _antiforgery = antiforgery; - } - - /// - /// Invokes the middleware for the given . - /// - /// The associated with the current request. - /// A which will be completed when execution of the middleware completes. - public async Task Invoke(HttpContext httpContext) - { - if (httpContext == null) - { - throw new ArgumentNullException(nameof(httpContext)); - } - - var handler = new AntiforgeryAuthenticationHandler(_antiforgery); - await handler.InitializeAsync(httpContext); - - try - { - await _next(httpContext); - } - finally - { - handler.Teardown(); - } - } - } -} diff --git a/src/Microsoft.AspNetCore.Antiforgery/IAntiforgery.cs b/src/Microsoft.AspNetCore.Antiforgery/IAntiforgery.cs index d22828ef31..6ac2e44e37 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/IAntiforgery.cs +++ b/src/Microsoft.AspNetCore.Antiforgery/IAntiforgery.cs @@ -1,7 +1,6 @@ // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. -using System.Security.Claims; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; @@ -47,18 +46,6 @@ namespace Microsoft.AspNetCore.Antiforgery /// Task IsRequestValidAsync(HttpContext httpContext); - /// - /// Asynchronously returns a value indicating whether the request passes antiforgery validation. If the - /// request uses a safe HTTP method (GET, HEAD, OPTIONS, TRACE), the antiforgery token is not validated. - /// - /// The associated with the current request. - /// The claims-based principal to validate. - /// - /// A that, when completed, returns true if the is requst uses a safe HTTP - /// method or contains a value antiforgery token, otherwise returns false. - /// - Task IsRequestValidAsync(HttpContext httpContext, ClaimsPrincipal principal); - /// /// Validates an antiforgery token that was supplied as part of the request. /// @@ -68,16 +55,6 @@ namespace Microsoft.AspNetCore.Antiforgery /// Task ValidateRequestAsync(HttpContext httpContext); - /// - /// Validates an antiforgery token that was supplied as part of the request. - /// - /// The associated with the current request. - /// The claims-based principal to validate. - /// - /// Thrown when the request does not include a valid antiforgery token. - /// - Task ValidateRequestAsync(HttpContext httpContext, ClaimsPrincipal principal); - /// /// Generates and stores an antiforgery cookie token if one is not available or not valid. /// diff --git a/src/Microsoft.AspNetCore.Antiforgery/Internal/AntiforgeryAuthenticationHandler.cs b/src/Microsoft.AspNetCore.Antiforgery/Internal/AntiforgeryAuthenticationHandler.cs deleted file mode 100644 index cffa86c5e4..0000000000 --- a/src/Microsoft.AspNetCore.Antiforgery/Internal/AntiforgeryAuthenticationHandler.cs +++ /dev/null @@ -1,160 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Threading.Tasks; -using Microsoft.AspNetCore.Http; -using Microsoft.AspNetCore.Http.Features.Authentication; - -namespace Microsoft.AspNetCore.Antiforgery.Internal -{ - public class AntiforgeryAuthenticationHandler : IAuthenticationHandler - { - private readonly IAntiforgery _antiforgery; - private HttpContext _httpContext; - private IAuthenticationHandler _priorHandler; - - public AntiforgeryAuthenticationHandler(IAntiforgery antiforgery) - { - if (antiforgery == null) - { - throw new ArgumentNullException(nameof(antiforgery)); - } - - _antiforgery = antiforgery; - } - - public async Task InitializeAsync(HttpContext httpContext) - { - if (httpContext == null) - { - throw new ArgumentNullException(nameof(httpContext)); - } - - _httpContext = httpContext; - - var authentication = GetAuthenticationFeature(_httpContext); - - _priorHandler = authentication.Handler; - authentication.Handler = this; - - if (authentication.User != null) - { - if (!await _antiforgery.IsRequestValidAsync(_httpContext)) - { - // Wipe out any existing principal if we can't validate this request. - authentication.User = null; - return; - } - } - } - - public void Teardown() - { - var authentication = GetAuthenticationFeature(_httpContext); - authentication.Handler = _priorHandler; - } - - /// - public async Task AuthenticateAsync(AuthenticateContext context) - { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } - - if (_priorHandler != null) - { - await _priorHandler.AuthenticateAsync(context); - - var authentication = GetAuthenticationFeature(_httpContext); - if (context.Principal != null) - { - try - { - await _antiforgery.ValidateRequestAsync(_httpContext, context.Principal); - } - catch (AntiforgeryValidationException ex) - { - context.Failed(ex); - return; - } - } - } - } - - /// - public Task ChallengeAsync(ChallengeContext context) - { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } - - if (_priorHandler != null) - { - return _priorHandler.ChallengeAsync(context); - } - - return TaskCache.CompletedTask; - } - - /// - public void GetDescriptions(DescribeSchemesContext context) - { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } - - if (_priorHandler != null) - { - _priorHandler.GetDescriptions(context); - } - } - - /// - public Task SignInAsync(SignInContext context) - { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } - - if (_priorHandler != null) - { - return _priorHandler.SignInAsync(context); - } - - return TaskCache.CompletedTask; - } - - /// - public Task SignOutAsync(SignOutContext context) - { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } - - if (_priorHandler != null) - { - return _priorHandler.SignOutAsync(context); - } - - return TaskCache.CompletedTask; - } - - private static IHttpAuthenticationFeature GetAuthenticationFeature(HttpContext httpContext) - { - var authentication = httpContext.Features.Get(); - if (authentication == null) - { - authentication = new HttpAuthenticationFeature(); - httpContext.Features.Set(authentication); - } - - return authentication; - } - } -} diff --git a/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgery.cs b/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgery.cs index c832a378be..9227bd6b78 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgery.cs +++ b/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgery.cs @@ -3,7 +3,6 @@ using System; using System.Diagnostics; -using System.Security.Claims; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.DependencyInjection; @@ -86,7 +85,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal } /// - public Task IsRequestValidAsync(HttpContext httpContext) + public async Task IsRequestValidAsync(HttpContext httpContext) { if (httpContext == null) { @@ -95,26 +94,13 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal CheckSSLConfig(httpContext); - return IsRequestValidAsync(httpContext, httpContext.User); - } - - /// - public async Task IsRequestValidAsync(HttpContext httpContext, ClaimsPrincipal principal) - { - if (httpContext == null) - { - throw new ArgumentNullException(nameof(httpContext)); - } - - if (principal == null) - { - throw new ArgumentNullException(nameof(principal)); - } - - CheckSSLConfig(httpContext); - - if (!IsValidationRequired(httpContext)) + var method = httpContext.Request.Method; + if (string.Equals(method, "GET", StringComparison.OrdinalIgnoreCase) || + string.Equals(method, "HEAD", StringComparison.OrdinalIgnoreCase) || + string.Equals(method, "OPTIONS", StringComparison.OrdinalIgnoreCase) || + string.Equals(method, "TRACE", StringComparison.OrdinalIgnoreCase)) { + // Validation not needed for these request types. return true; } @@ -140,7 +126,6 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal string message; var result = _tokenGenerator.TryValidateTokenSet( httpContext, - principal, deserializedCookieToken, deserializedRequestToken, out message); @@ -158,7 +143,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal } /// - public Task ValidateRequestAsync(HttpContext httpContext) + public async Task ValidateRequestAsync(HttpContext httpContext) { if (httpContext == null) { @@ -167,29 +152,6 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal CheckSSLConfig(httpContext); - return ValidateRequestAsync(httpContext, httpContext.User); - } - - /// - public async Task ValidateRequestAsync(HttpContext httpContext, ClaimsPrincipal principal) - { - if (httpContext == null) - { - throw new ArgumentNullException(nameof(httpContext)); - } - - if (principal == null) - { - throw new ArgumentNullException(nameof(principal)); - } - - CheckSSLConfig(httpContext); - - if (!IsValidationRequired(httpContext)) - { - return; - } - var tokens = await _tokenStore.GetRequestTokensAsync(httpContext); if (tokens.CookieToken == null) { @@ -218,15 +180,12 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal } } - ValidateTokens(httpContext, principal, tokens); + ValidateTokens(httpContext, tokens); _logger.ValidatedAntiforgeryToken(); } - private void ValidateTokens( - HttpContext httpContext, - ClaimsPrincipal principal, - AntiforgeryTokenSet antiforgeryTokenSet) + private void ValidateTokens(HttpContext httpContext, AntiforgeryTokenSet antiforgeryTokenSet) { Debug.Assert(!string.IsNullOrEmpty(antiforgeryTokenSet.CookieToken)); Debug.Assert(!string.IsNullOrEmpty(antiforgeryTokenSet.RequestToken)); @@ -244,7 +203,6 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal string message; if (!_tokenGenerator.TryValidateTokenSet( httpContext, - principal, deserializedCookieToken, deserializedRequestToken, out message)) @@ -310,21 +268,6 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal } } - private bool IsValidationRequired(HttpContext httpContext) - { - var method = httpContext.Request.Method; - if (string.Equals(method, "GET", StringComparison.OrdinalIgnoreCase) || - string.Equals(method, "HEAD", StringComparison.OrdinalIgnoreCase) || - string.Equals(method, "OPTIONS", StringComparison.OrdinalIgnoreCase) || - string.Equals(method, "TRACE", StringComparison.OrdinalIgnoreCase)) - { - // Validation not needed for HTTP methods that don't mutate any state. - return false; - } - - return true; - } - private static IAntiforgeryFeature GetAntiforgeryFeature(HttpContext httpContext) { var antiforgeryFeature = httpContext.Features.Get(); @@ -405,7 +348,6 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal var cookieToken = antiforgeryFeature.NewCookieToken ?? antiforgeryFeature.CookieToken; antiforgeryFeature.NewRequestToken = _tokenGenerator.GenerateRequestToken( httpContext, - httpContext.User, cookieToken); } diff --git a/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgeryTokenGenerator.cs b/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgeryTokenGenerator.cs index 14c102bb51..872f7ed18c 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgeryTokenGenerator.cs +++ b/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgeryTokenGenerator.cs @@ -35,7 +35,6 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal /// public AntiforgeryToken GenerateRequestToken( HttpContext httpContext, - ClaimsPrincipal principal, AntiforgeryToken cookieToken) { if (httpContext == null) @@ -64,11 +63,11 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal var isIdentityAuthenticated = false; // populate Username and ClaimUid - var authenticatedIdentity = GetAuthenticatedIdentity(principal); + var authenticatedIdentity = GetAuthenticatedIdentity(httpContext.User); if (authenticatedIdentity != null) { isIdentityAuthenticated = true; - requestToken.ClaimUid = GetClaimUidBlob(_claimUidExtractor.ExtractClaimUid(principal)); + requestToken.ClaimUid = GetClaimUidBlob(_claimUidExtractor.ExtractClaimUid(httpContext.User)); if (requestToken.ClaimUid == null) { @@ -110,7 +109,6 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal /// public bool TryValidateTokenSet( HttpContext httpContext, - ClaimsPrincipal principal, AntiforgeryToken cookieToken, AntiforgeryToken requestToken, out string message) @@ -152,10 +150,10 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal var currentUsername = string.Empty; BinaryBlob currentClaimUid = null; - var authenticatedIdentity = GetAuthenticatedIdentity(principal); + var authenticatedIdentity = GetAuthenticatedIdentity(httpContext.User); if (authenticatedIdentity != null) { - currentClaimUid = GetClaimUidBlob(_claimUidExtractor.ExtractClaimUid(principal)); + currentClaimUid = GetClaimUidBlob(_claimUidExtractor.ExtractClaimUid(httpContext.User)); if (currentClaimUid == null) { currentUsername = authenticatedIdentity.Name ?? string.Empty; diff --git a/src/Microsoft.AspNetCore.Antiforgery/Internal/IAntiforgeryTokenGenerator.cs b/src/Microsoft.AspNetCore.Antiforgery/Internal/IAntiforgeryTokenGenerator.cs index 8c5d22cf31..c0dff86047 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/Internal/IAntiforgeryTokenGenerator.cs +++ b/src/Microsoft.AspNetCore.Antiforgery/Internal/IAntiforgeryTokenGenerator.cs @@ -1,7 +1,6 @@ // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. -using System.Security.Claims; using Microsoft.AspNetCore.Http; namespace Microsoft.AspNetCore.Antiforgery.Internal @@ -21,13 +20,9 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal /// Generates a request token corresponding to . ///
/// The associated with the current request. - /// The claims-based principal to use for token generation. /// A valid cookie token. /// An . - AntiforgeryToken GenerateRequestToken( - HttpContext httpContext, - ClaimsPrincipal principal, - AntiforgeryToken cookieToken); + AntiforgeryToken GenerateRequestToken(HttpContext httpContext, AntiforgeryToken cookieToken); /// /// Attempts to validate a cookie token. @@ -40,7 +35,6 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal /// Attempts to validate a cookie and request token set for the given . /// /// The associated with the current request. - /// The claims-based principal to use for token validation. /// A cookie token. /// A request token. /// @@ -49,7 +43,6 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal /// true if the tokens are valid, otherwise false. bool TryValidateTokenSet( HttpContext httpContext, - ClaimsPrincipal principal, AntiforgeryToken cookieToken, AntiforgeryToken requestToken, out string message); diff --git a/src/Microsoft.AspNetCore.Antiforgery/Internal/TaskCache.cs b/src/Microsoft.AspNetCore.Antiforgery/Internal/TaskCache.cs deleted file mode 100644 index d21d2e7a76..0000000000 --- a/src/Microsoft.AspNetCore.Antiforgery/Internal/TaskCache.cs +++ /dev/null @@ -1,12 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System.Threading.Tasks; - -namespace Microsoft.AspNetCore.Antiforgery.Internal -{ - public static class TaskCache - { - public static readonly Task CompletedTask = Task.FromResult(0); - } -} diff --git a/src/Microsoft.AspNetCore.Antiforgery/project.json b/src/Microsoft.AspNetCore.Antiforgery/project.json index b207394d87..9d0fd780b5 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/project.json +++ b/src/Microsoft.AspNetCore.Antiforgery/project.json @@ -19,7 +19,9 @@ }, "dependencies": { "Microsoft.AspNetCore.DataProtection": "1.0.0-*", - "Microsoft.AspNetCore.Http": "1.0.0-*" + "Microsoft.AspNetCore.Http.Abstractions": "1.0.0-*", + "Microsoft.AspNetCore.WebUtilities": "1.0.0-*", + "Microsoft.Extensions.ObjectPool": "1.0.0-*" }, "frameworks": { "netstandard1.3": { diff --git a/test/Microsoft.AspNetCore.Antiforgery.Test/AntiforgeryMiddlewareTest.cs b/test/Microsoft.AspNetCore.Antiforgery.Test/AntiforgeryMiddlewareTest.cs deleted file mode 100644 index 54e40e7d93..0000000000 --- a/test/Microsoft.AspNetCore.Antiforgery.Test/AntiforgeryMiddlewareTest.cs +++ /dev/null @@ -1,380 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Security.Claims; -using System.Threading.Tasks; -using Microsoft.AspNetCore.Antiforgery.Internal; -using Microsoft.AspNetCore.Builder; -using Microsoft.AspNetCore.Builder.Internal; -using Microsoft.AspNetCore.Http; -using Microsoft.AspNetCore.Http.Features.Authentication; -using Microsoft.Extensions.DependencyInjection; -using Moq; -using Xunit; - -namespace Microsoft.AspNetCore.Antiforgery -{ - // These are really more like integration tests and just verify a bunch of different - // reasonable combinations of authN middleware. - public class AntiforgeryMiddlewareTest - { - private readonly ClaimsPrincipal LoggedInUser = new ClaimsPrincipal(new ClaimsIdentity[] - { - new ClaimsIdentity("Test"), - }); - - private readonly ClaimsPrincipal LoggedInUser2 = new ClaimsPrincipal(new ClaimsIdentity[] - { - new ClaimsIdentity("Test"), - }); - - [Fact] - public async Task AutomaticAuthentication_Anonymous() - { - // Arrange - var context = Setup((app) => - { - app.Use(next => new AutomaticAuthenticationMiddleware(next, null).Invoke); - app.UseAntiforgery(); - }); - - var httpContext = new DefaultHttpContext(); - - await context.AppFunc(httpContext); - - Assert.Null(context.Principal); - } - - [Fact] - public async Task AutomaticAuthentication_LoggedIn_WithoutToken() - { - // Arrange - var context = Setup((app) => - { - app.UseMiddleware(LoggedInUser); - app.UseAntiforgery(); - }); - - context.Antiforgery - .Setup(a => a.IsRequestValidAsync(It.IsAny())) - .ReturnsAsync(false); - - var httpContext = new DefaultHttpContext(); - - await context.AppFunc(httpContext); - - Assert.Null(context.Principal); - } - - [Fact] - public async Task AutomaticAuthentication_LoggedIn_WithValidToken() - { - // Arrange - var context = Setup((app) => - { - app.UseMiddleware(LoggedInUser); - app.UseAntiforgery(); - }); - - context.Antiforgery - .Setup(a => a.IsRequestValidAsync(It.IsAny())) - .ReturnsAsync(true); - - var httpContext = new DefaultHttpContext(); - - await context.AppFunc(httpContext); - - Assert.Same(LoggedInUser, context.Principal); - } - - // A middleware after antiforgery in the pipeline can authenticate without going through token - // validation. - [Fact] - public async Task AutomaticAuthentication_LoggedIn_WithoutToken_AuthenticatedBySubsequentMiddleware() - { - // Arrange - var context = Setup((app) => - { - app.UseMiddleware(LoggedInUser); - app.UseAntiforgery(); - app.UseMiddleware(LoggedInUser2); - }); - - context.Antiforgery - .Setup(a => a.IsRequestValidAsync(It.IsAny())) - .ReturnsAsync(false); - - var httpContext = new DefaultHttpContext(); - - await context.AppFunc(httpContext); - - Assert.Same(LoggedInUser2, context.Principal); - } - - [Fact] - public async Task PasiveAuthentication_Anonymous() - { - // Arrange - var context = Setup((app) => - { - app.Use(next => new AuthenticationHandlerMiddleware(next, null).Invoke); - app.UseAntiforgery(); - app.UseMiddleware(); - }); - - var httpContext = new DefaultHttpContext(); - - await context.AppFunc(httpContext); - - Assert.Null(context.Principal); - } - - [Fact] - public async Task PassiveAuthentication_LoggedIn_WithoutToken() - { - // Arrange - var context = Setup((app) => - { - app.UseMiddleware(LoggedInUser); - app.UseAntiforgery(); - app.UseMiddleware(); - }); - - context.Antiforgery - .Setup(a => a.ValidateRequestAsync(It.IsAny(), LoggedInUser)) - .Throws(new AntiforgeryValidationException("error")); - - var httpContext = new DefaultHttpContext(); - - await context.AppFunc(httpContext); - - Assert.Null(context.Principal); - } - - [Fact] - public async Task PassiveAuthentication_LoggedIn_WithValidToken() - { - // Arrange - var context = Setup((app) => - { - app.UseMiddleware(LoggedInUser); - app.UseAntiforgery(); - app.UseMiddleware(); - }); - - context.Antiforgery - .Setup(a => a.ValidateRequestAsync(It.IsAny(), LoggedInUser)) - .Returns(TaskCache.CompletedTask); - - var httpContext = new DefaultHttpContext(); - - await context.AppFunc(httpContext); - - Assert.Same(LoggedInUser, context.Principal); - } - - // A middleware after antiforgery in the pipeline can authenticate without going through token - // validation. - [Fact] - public async Task PassiveAuthentication_LoggedIn_WithoutToken_AuthenticatedBySubsequentMiddleware() - { - // Arrange - var context = Setup((app) => - { - app.UseMiddleware(LoggedInUser); - app.UseAntiforgery(); - app.UseMiddleware(LoggedInUser2); - app.UseMiddleware(); - }); - - var httpContext = new DefaultHttpContext(); - - await context.AppFunc(httpContext); - - Assert.Same(LoggedInUser2, context.Principal); - } - - private static IHttpAuthenticationFeature GetAuthenticationFeature(HttpContext httpContext) - { - var authentication = httpContext.Features.Get(); - if (authentication == null) - { - authentication = new HttpAuthenticationFeature(); - httpContext.Features.Set(authentication); - } - - return authentication; - } - - private static TestContext Setup(Action action) - { - var services = new ServiceCollection(); - services.AddLogging(); - services.AddOptions(); - - var antiforgery = new Mock(MockBehavior.Strict); - services.AddSingleton(antiforgery.Object); - - var result = new TestContext(); - result.Antiforgery = antiforgery; - - var app = new ApplicationBuilder(services.BuildServiceProvider()); - action(app); - - // Capture the logged in user 'after' the middleware so we can validate it. - app.Run(c => - { - result.Principal = GetAuthenticationFeature(c).User; - return TaskCache.CompletedTask; - }); - - result.AppFunc = app.Build(); - return result; - } - - private class TestContext - { - public Mock Antiforgery { get; set; } - - public RequestDelegate AppFunc { get; set; } - - public ClaimsPrincipal Principal { get; set; } - } - - private class AutomaticAuthenticationMiddleware - { - private readonly RequestDelegate _next; - private readonly ClaimsPrincipal _principal; - - public AutomaticAuthenticationMiddleware(RequestDelegate next, ClaimsPrincipal principal) - { - _next = next; - _principal = principal; - } - - public Task Invoke(HttpContext httpContext) - { - GetAuthenticationFeature(httpContext).User = _principal; - return _next(httpContext); - } - } - - private class AuthenticationHandlerMiddleware - { - private readonly RequestDelegate _next; - private readonly ClaimsPrincipal _principal; - - public AuthenticationHandlerMiddleware(RequestDelegate next, ClaimsPrincipal principal) - { - _next = next; - _principal = principal; - } - - public async Task Invoke(HttpContext httpContext) - { - var handler = new AuthenticationHandler(_principal); - await handler.InitializeAsync(httpContext); - - try - { - await _next(httpContext); - } - finally - { - await handler.TeardownAsync(); - } - } - } - - private class AuthenticationHandler : IAuthenticationHandler - { - private readonly ClaimsPrincipal _principal; - private IAuthenticationHandler _priorHandler; - private HttpContext _httpContext; - - public AuthenticationHandler(ClaimsPrincipal principal) - { - _principal = principal; - } - - public Task InitializeAsync(HttpContext httpContext) - { - _httpContext = httpContext; - - var authenticationFeature = GetAuthenticationFeature(_httpContext); - _priorHandler = authenticationFeature.Handler; - authenticationFeature.Handler = this; - - return TaskCache.CompletedTask; - } - - public Task TeardownAsync() - { - var authenticationFeature = GetAuthenticationFeature(_httpContext); - authenticationFeature.Handler = _priorHandler; - - return TaskCache.CompletedTask; - } - - public Task AuthenticateAsync(AuthenticateContext context) - { - if (_principal == null) - { - context.NotAuthenticated(); - } - else - { - context.Authenticated(_principal, null, null); - } - - return TaskCache.CompletedTask; - } - - public Task ChallengeAsync(ChallengeContext context) - { - throw new NotImplementedException(); - } - - public void GetDescriptions(DescribeSchemesContext context) - { - throw new NotImplementedException(); - } - - public Task SignInAsync(SignInContext context) - { - throw new NotImplementedException(); - } - - public Task SignOutAsync(SignOutContext context) - { - throw new NotImplementedException(); - } - } - - private class CallAuthenticateMiddleware - { - private readonly RequestDelegate _next; - - public CallAuthenticateMiddleware(RequestDelegate next) - { - _next = next; - } - - public async Task Invoke(HttpContext httpContext) - { - var authenticationFeature = GetAuthenticationFeature(httpContext); - - var authenticateContext = new AuthenticateContext("Test"); - await httpContext.Authentication.AuthenticateAsync(authenticateContext); - - if (authenticateContext.Accepted) - { - authenticationFeature.User = authenticateContext.Principal; - } - - await _next(httpContext); - } - } - } -} diff --git a/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/AntiforgeryAuthenticationHandlerTest.cs b/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/AntiforgeryAuthenticationHandlerTest.cs deleted file mode 100644 index 331cef1be4..0000000000 --- a/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/AntiforgeryAuthenticationHandlerTest.cs +++ /dev/null @@ -1,291 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System.Security.Claims; -using System.Threading.Tasks; -using Microsoft.AspNetCore.Http; -using Microsoft.AspNetCore.Http.Features.Authentication; -using Moq; -using Xunit; - -namespace Microsoft.AspNetCore.Antiforgery.Internal -{ - public class AntiforgeryAuthenticationHandlerTest - { - [Fact] - public async Task IntializeAsync_NoOp_WhenAnonymous() - { - // Arrange - var antiforgery = new Mock(MockBehavior.Strict); - var handler = new AntiforgeryAuthenticationHandler(antiforgery.Object); - - antiforgery - .Setup(a => a.IsRequestValidAsync(It.IsAny())) - .ReturnsAsync(false) - .Verifiable(); - - var httpContext = new DefaultHttpContext(); - - // Act - await handler.InitializeAsync(httpContext); - - // Assert - antiforgery.Verify(a => a.IsRequestValidAsync(It.IsAny()), Times.Never()); - } - - [Fact] - public async Task IntializeAsync_ValidatesRequest_WhenLoggedIn() - { - // Arrange - var antiforgery = new Mock(MockBehavior.Strict); - var handler = new AntiforgeryAuthenticationHandler(antiforgery.Object); - - antiforgery - .Setup(a => a.IsRequestValidAsync(It.IsAny())) - .ReturnsAsync(true) - .Verifiable(); - - var httpContext = new DefaultHttpContext(); - - var authenticationFeature = new HttpAuthenticationFeature(); - httpContext.Features.Set(authenticationFeature); - authenticationFeature.User = new ClaimsPrincipal(); - - // Act - await handler.InitializeAsync(httpContext); - - // Assert - antiforgery.Verify(a => a.IsRequestValidAsync(It.IsAny()), Times.Once()); - } - - [Fact] - public async Task IntializeAsync_ClearsUser_WhenInvalid() - { - // Arrange - var antiforgery = new Mock(MockBehavior.Strict); - var handler = new AntiforgeryAuthenticationHandler(antiforgery.Object); - - antiforgery - .Setup(a => a.IsRequestValidAsync(It.IsAny())) - .ReturnsAsync(false) - .Verifiable(); - - var httpContext = new DefaultHttpContext(); - - var authenticationFeature = new HttpAuthenticationFeature(); - httpContext.Features.Set(authenticationFeature); - authenticationFeature.User = new ClaimsPrincipal(); - - // Act - await handler.InitializeAsync(httpContext); - - // Assert - Assert.Null(authenticationFeature.User); - antiforgery.Verify(a => a.IsRequestValidAsync(It.IsAny()), Times.Once()); - } - - [Fact] - public async Task IntializeAsync_AttachesAuthorizationHandler() - { - // Arrange - var antiforgery = new Mock(MockBehavior.Strict); - var handler = new AntiforgeryAuthenticationHandler(antiforgery.Object); - - antiforgery - .Setup(a => a.IsRequestValidAsync(It.IsAny())) - .ReturnsAsync(false) - .Verifiable(); - - var httpContext = new DefaultHttpContext(); - - var authenticationFeature = new HttpAuthenticationFeature(); - httpContext.Features.Set(authenticationFeature); - - // Act - await handler.InitializeAsync(httpContext); - - // Assert - Assert.Same(handler, authenticationFeature.Handler); - antiforgery.Verify(a => a.IsRequestValidAsync(It.IsAny()), Times.Never()); - } - - [Fact] - public async Task AuthenticateAsync_NoPriorHandler_NoOp() - { - // Arrange - var antiforgery = new Mock(MockBehavior.Strict); - var handler = new AntiforgeryAuthenticationHandler(antiforgery.Object); - - antiforgery - .Setup(a => a.IsRequestValidAsync(It.IsAny())) - .ReturnsAsync(false) - .Verifiable(); - - antiforgery - .Setup(a => a.ValidateRequestAsync(It.IsAny(), It.IsAny())) - .Verifiable(); - - var httpContext = new DefaultHttpContext(); - - var authenticationFeature = new HttpAuthenticationFeature(); - httpContext.Features.Set(authenticationFeature); - - await handler.InitializeAsync(httpContext); - - var authenticateContext = new AuthenticateContext("Test"); - - // Act - await handler.AuthenticateAsync(authenticateContext); - - // Assert - Assert.False(authenticateContext.Accepted); - - antiforgery.Verify(a => a.IsRequestValidAsync(It.IsAny()), Times.Never()); - antiforgery.Verify( - a => a.ValidateRequestAsync(It.IsAny(), It.IsAny()), - Times.Never()); - } - - [Fact] - public async Task AuthenticateAsync_PriorHandlerDoesNotAuthenticate_NoOp() - { - // Arrange - var antiforgery = new Mock(MockBehavior.Strict); - var handler = new AntiforgeryAuthenticationHandler(antiforgery.Object); - - antiforgery - .Setup(a => a.IsRequestValidAsync(It.IsAny())) - .ReturnsAsync(false) - .Verifiable(); - - antiforgery - .Setup(a => a.ValidateRequestAsync(It.IsAny(), It.IsAny())) - .Verifiable(); - - var httpContext = new DefaultHttpContext(); - - var authenticationFeature = new HttpAuthenticationFeature(); - httpContext.Features.Set(authenticationFeature); - var priorHandler = new Mock(MockBehavior.Strict); - authenticationFeature.Handler = priorHandler.Object; - - priorHandler - .Setup(h => h.AuthenticateAsync(It.IsAny())) - .Returns(TaskCache.CompletedTask) - .Callback(c => c.NotAuthenticated()); - - await handler.InitializeAsync(httpContext); - - var authenticateContext = new AuthenticateContext("Test"); - - // Act - await handler.AuthenticateAsync(authenticateContext); - - // Assert - Assert.True(authenticateContext.Accepted); - Assert.Null(authenticateContext.Principal); - - antiforgery.Verify(a => a.IsRequestValidAsync(It.IsAny()), Times.Never()); - antiforgery.Verify( - a => a.ValidateRequestAsync(It.IsAny(), It.IsAny()), - Times.Never()); - } - - [Fact] - public async Task AuthenticateAsync_PriorHandlerSetsPrincipal_Valid() - { - // Arrange - var antiforgery = new Mock(MockBehavior.Strict); - var handler = new AntiforgeryAuthenticationHandler(antiforgery.Object); - - var principal = new ClaimsPrincipal(); - - antiforgery - .Setup(a => a.IsRequestValidAsync(It.IsAny())) - .ReturnsAsync(false) - .Verifiable(); - - antiforgery - .Setup(a => a.ValidateRequestAsync(It.IsAny(), principal)) - .Returns(TaskCache.CompletedTask) - .Verifiable(); - - var httpContext = new DefaultHttpContext(); - - var authenticationFeature = new HttpAuthenticationFeature(); - httpContext.Features.Set(authenticationFeature); - var priorHandler = new Mock(MockBehavior.Strict); - authenticationFeature.Handler = priorHandler.Object; - - priorHandler - .Setup(h => h.AuthenticateAsync(It.IsAny())) - .Returns(TaskCache.CompletedTask) - .Callback(c => c.Authenticated(principal, null, null)); - - await handler.InitializeAsync(httpContext); - - var authenticateContext = new AuthenticateContext("Test"); - - // Act - await handler.AuthenticateAsync(authenticateContext); - - // Assert - Assert.True(authenticateContext.Accepted); - Assert.Same(principal, authenticateContext.Principal); - - antiforgery.Verify(a => a.IsRequestValidAsync(It.IsAny()), Times.Never()); - antiforgery.Verify( - a => a.ValidateRequestAsync(It.IsAny(), principal), - Times.Once()); - } - - [Fact] - public async Task AuthenticateAsync_PriorHandlerSetsPrincipal_Invalid() - { - // Arrange - var antiforgery = new Mock(MockBehavior.Strict); - var handler = new AntiforgeryAuthenticationHandler(antiforgery.Object); - - var principal = new ClaimsPrincipal(); - - antiforgery - .Setup(a => a.IsRequestValidAsync(It.IsAny())) - .ReturnsAsync(false) - .Verifiable(); - - antiforgery - .Setup(a => a.ValidateRequestAsync(It.IsAny(), principal)) - .Throws(new AntiforgeryValidationException("invalid")) - .Verifiable(); - - var httpContext = new DefaultHttpContext(); - - var authenticationFeature = new HttpAuthenticationFeature(); - httpContext.Features.Set(authenticationFeature); - var priorHandler = new Mock(MockBehavior.Strict); - authenticationFeature.Handler = priorHandler.Object; - - priorHandler - .Setup(h => h.AuthenticateAsync(It.IsAny())) - .Returns(TaskCache.CompletedTask) - .Callback(c => c.Authenticated(principal, null, null)); - - await handler.InitializeAsync(httpContext); - - var authenticateContext = new AuthenticateContext("Test"); - - // Act - await handler.AuthenticateAsync(authenticateContext); - - // Assert - Assert.True(authenticateContext.Accepted); - Assert.Null(authenticateContext.Principal); - Assert.NotNull(authenticateContext.Error); - - antiforgery.Verify(a => a.IsRequestValidAsync(It.IsAny()), Times.Never()); - antiforgery.Verify( - a => a.ValidateRequestAsync(It.IsAny(), principal), - Times.Once()); - } - } -} diff --git a/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTest.cs b/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTest.cs index 0677d73a0d..45bd0236ba 100644 --- a/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTest.cs +++ b/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTest.cs @@ -15,22 +15,6 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal { public class DefaultAntiforgeryTest { - public static TheoryData SafeHttpMethods => new TheoryData() - { - "GeT", - "HEAD", - "options", - "TrAcE", - }; - - public static TheoryData UnsafeHttpMethods => new TheoryData() - { - "PUT", - "post", - "Delete", - "Custom", - }; - [Fact] public async Task ChecksSSL_ValidateRequestAsync_Throws() { @@ -51,26 +35,6 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal exception.Message); } - [Fact] - public async Task ChecksSSL_ValidateRequestAsync_WithPrincipal_Throws() - { - // Arrange - var httpContext = GetHttpContext(); - var options = new AntiforgeryOptions() - { - RequireSsl = true - }; - var antiforgery = GetAntiforgery(httpContext, options); - - // Act & Assert - var exception = await Assert.ThrowsAsync( - () => antiforgery.ValidateRequestAsync(httpContext, new ClaimsPrincipal())); - Assert.Equal( - @"The antiforgery system has the configuration value AntiforgeryOptions.RequireSsl = true, " + - "but the current request is not an SSL request.", - exception.Message); - } - [Fact] public async Task ChecksSSL_IsRequestValidAsync_Throws() { @@ -92,27 +56,6 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal exception.Message); } - [Fact] - public async Task ChecksSSL_IsRequestValidAsync_WithPrincipal_Throws() - { - // Arrange - var httpContext = GetHttpContext(); - var options = new AntiforgeryOptions() - { - RequireSsl = true - }; - - var antiforgery = GetAntiforgery(httpContext, options); - - // Act & Assert - var exception = await Assert.ThrowsAsync( - () => antiforgery.IsRequestValidAsync(httpContext, new ClaimsPrincipal())); - Assert.Equal( - @"The antiforgery system has the configuration value AntiforgeryOptions.RequireSsl = true, " + - "but the current request is not an SSL request.", - exception.Message); - } - [Fact] public void ChecksSSL_GetAndStoreTokens_Throws() { @@ -467,7 +410,6 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal context.TokenGenerator .Setup(o => o.TryValidateTokenSet( context.HttpContext, - It.IsAny(), context.TestTokenSet.OldCookieToken, context.TestTokenSet.RequestToken, out message)) @@ -502,7 +444,6 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal context.TokenGenerator .Setup(o => o.TryValidateTokenSet( context.HttpContext, - It.IsAny(), context.TestTokenSet.OldCookieToken, context.TestTokenSet.RequestToken, out message)) @@ -543,7 +484,6 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal context.TokenGenerator .Setup(o => o.TryValidateTokenSet( context.HttpContext, - It.IsAny(), antiforgeryFeature.CookieToken, antiforgeryFeature.RequestToken, out message)) @@ -569,7 +509,10 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal } [Theory] - [MemberData(nameof(SafeHttpMethods))] + [InlineData("GeT")] + [InlineData("HEAD")] + [InlineData("options")] + [InlineData("TrAcE")] public async Task IsRequestValidAsync_SkipsAntiforgery_ForSafeHttpMethods(string httpMethod) { // Arrange @@ -580,7 +523,6 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal context.TokenGenerator .Setup(o => o.TryValidateTokenSet( context.HttpContext, - It.IsAny(), It.IsAny(), It.IsAny(), out message)) @@ -597,7 +539,6 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal context.TokenGenerator .Verify(o => o.TryValidateTokenSet( context.HttpContext, - It.IsAny(), It.IsAny(), It.IsAny(), out message), @@ -605,7 +546,10 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal } [Theory] - [MemberData(nameof(UnsafeHttpMethods))] + [InlineData("PUT")] + [InlineData("post")] + [InlineData("Delete")] + [InlineData("Custom")] public async Task IsRequestValidAsync_ValidatesAntiforgery_ForNonSafeHttpMethods(string httpMethod) { // Arrange @@ -616,7 +560,6 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal context.TokenGenerator .Setup(o => o.TryValidateTokenSet( context.HttpContext, - It.IsAny(), It.IsAny(), It.IsAny(), out message)) @@ -633,68 +576,6 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal context.TokenGenerator.Verify(); } - [Fact] - public async Task IsRequestValidAsync_UsesPrincipalFromHttpContext() - { - // Arrange - var context = CreateMockContext(new AntiforgeryOptions()); - context.HttpContext.Request.Method = "POST"; - - var principal = new ClaimsPrincipal(); - context.HttpContext.User = principal; - - string message; - context.TokenGenerator - .Setup(o => o.TryValidateTokenSet( - context.HttpContext, - principal, - It.IsAny(), - It.IsAny(), - out message)) - .Returns(true) - .Verifiable(); - - var antiforgery = GetAntiforgery(context); - - // Act - var result = await antiforgery.IsRequestValidAsync(context.HttpContext); - - // Assert - Assert.True(result); - context.TokenGenerator.Verify(); - } - - [Fact] - public async Task IsRequestValidAsync_UsesPassedInPrincipal() - { - // Arrange - var context = CreateMockContext(new AntiforgeryOptions()); - context.HttpContext.Request.Method = "POST"; - - var principal = new ClaimsPrincipal(); - context.HttpContext.User = new ClaimsPrincipal(); // This should be ignored. - - string message; - context.TokenGenerator - .Setup(o => o.TryValidateTokenSet( - context.HttpContext, - principal, - It.IsAny(), - It.IsAny(), - out message)) - .Returns(true) - .Verifiable(); - - var antiforgery = GetAntiforgery(context); - - // Act - var result = await antiforgery.IsRequestValidAsync(context.HttpContext, principal); - - // Assert - Assert.True(result); - context.TokenGenerator.Verify(); - } - [Fact] public async Task ValidateRequestAsync_FromStore_Failure() { @@ -706,7 +587,6 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal context.TokenGenerator .Setup(o => o.TryValidateTokenSet( context.HttpContext, - It.IsAny(), context.TestTokenSet.OldCookieToken, context.TestTokenSet.RequestToken, out message)) @@ -739,7 +619,6 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal context.TokenGenerator .Setup(o => o.TryValidateTokenSet( context.HttpContext, - It.IsAny(), context.TestTokenSet.OldCookieToken, context.TestTokenSet.RequestToken, out message)) @@ -881,7 +760,6 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal context.TokenGenerator .Setup(o => o.TryValidateTokenSet( context.HttpContext, - It.IsAny(), antiforgeryFeature.CookieToken, antiforgeryFeature.RequestToken, out message)) @@ -905,129 +783,6 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal Times.Never); } - [Theory] - [MemberData(nameof(SafeHttpMethods))] - public async Task ValidateRequestAsync_SkipsAntiforgery_ForSafeHttpMethods(string httpMethod) - { - // Arrange - var context = CreateMockContext(new AntiforgeryOptions()); - context.HttpContext.Request.Method = httpMethod; - - string message; - context.TokenGenerator - .Setup(o => o.TryValidateTokenSet( - context.HttpContext, - It.IsAny(), - It.IsAny(), - It.IsAny(), - out message)) - .Returns(false) - .Verifiable(); - - var antiforgery = GetAntiforgery(context); - - // Act - await antiforgery.ValidateRequestAsync(context.HttpContext); - - // Assert - context.TokenGenerator - .Verify(o => o.TryValidateTokenSet( - context.HttpContext, - It.IsAny(), - It.IsAny(), - It.IsAny(), - out message), - Times.Never); - } - - [Theory] - [MemberData(nameof(UnsafeHttpMethods))] - public async Task ValidateRequestAsync_ValidatesAntiforgery_ForNonSafeHttpMethods(string httpMethod) - { - // Arrange - var context = CreateMockContext(new AntiforgeryOptions()); - context.HttpContext.Request.Method = httpMethod; - - string message; - context.TokenGenerator - .Setup(o => o.TryValidateTokenSet( - context.HttpContext, - It.IsAny(), - It.IsAny(), - It.IsAny(), - out message)) - .Returns(true) - .Verifiable(); - - var antiforgery = GetAntiforgery(context); - - // Act - await antiforgery.ValidateRequestAsync(context.HttpContext); - - // Assert - context.TokenGenerator.Verify(); - } - - [Fact] - public async Task ValidateRequestAsync_UsesPrincipalFromHttpContext() - { - // Arrange - var context = CreateMockContext(new AntiforgeryOptions()); - context.HttpContext.Request.Method = "POST"; - - var principal = new ClaimsPrincipal(); - context.HttpContext.User = principal; - - string message; - context.TokenGenerator - .Setup(o => o.TryValidateTokenSet( - context.HttpContext, - principal, - It.IsAny(), - It.IsAny(), - out message)) - .Returns(true) - .Verifiable(); - - var antiforgery = GetAntiforgery(context); - - // Act - await antiforgery.ValidateRequestAsync(context.HttpContext); - - // Assert - context.TokenGenerator.Verify(); - } - - [Fact] - public async Task ValidateRequestAsync_UsesPassedInPrincipal() - { - // Arrange - var context = CreateMockContext(new AntiforgeryOptions()); - context.HttpContext.Request.Method = "POST"; - - var principal = new ClaimsPrincipal(); - context.HttpContext.User = new ClaimsPrincipal(); // This should be ignored. - - string message; - context.TokenGenerator - .Setup(o => o.TryValidateTokenSet( - context.HttpContext, - principal, - It.IsAny(), - It.IsAny(), - out message)) - .Returns(true) - .Verifiable(); - - var antiforgery = GetAntiforgery(context); - - // Act - await antiforgery.ValidateRequestAsync(context.HttpContext, principal); - - // Assert - context.TokenGenerator.Verify(); - } - [Theory] [InlineData(false, "SAMEORIGIN")] [InlineData(true, null)] @@ -1267,7 +1022,6 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal mockGenerator .Setup(o => o.GenerateRequestToken( httpContext, - It.IsAny(), useOldCookie ? testTokenSet.OldCookieToken : testTokenSet.NewCookieToken)) .Returns(testTokenSet.RequestToken); diff --git a/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTokenGeneratorTest.cs b/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTokenGeneratorTest.cs index 94379071c5..981de8e94c 100644 --- a/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTokenGeneratorTest.cs +++ b/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTokenGeneratorTest.cs @@ -34,7 +34,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal // Arrange var cookieToken = new AntiforgeryToken() { IsCookieToken = false }; var httpContext = new DefaultHttpContext(); - var principal = new ClaimsPrincipal(new ClaimsIdentity()); + httpContext.User = new ClaimsPrincipal(new ClaimsIdentity()); Assert.False(httpContext.User.Identity.IsAuthenticated); var tokenProvider = new DefaultAntiforgeryTokenGenerator( @@ -43,7 +43,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal // Act & Assert ExceptionAssert.ThrowsArgument( - () => tokenProvider.GenerateRequestToken(httpContext, principal, cookieToken), + () => tokenProvider.GenerateRequestToken(httpContext, cookieToken), "cookieToken", "The antiforgery cookie token is invalid."); } @@ -54,7 +54,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal // Arrange var cookieToken = new AntiforgeryToken() { IsCookieToken = true }; var httpContext = new DefaultHttpContext(); - var principal = new ClaimsPrincipal(new ClaimsIdentity()); + httpContext.User = new ClaimsPrincipal(new ClaimsIdentity()); Assert.False(httpContext.User.Identity.IsAuthenticated); var tokenProvider = new DefaultAntiforgeryTokenGenerator( @@ -62,7 +62,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal additionalDataProvider: null); // Act - var fieldToken = tokenProvider.GenerateRequestToken(httpContext, principal, cookieToken); + var fieldToken = tokenProvider.GenerateRequestToken(httpContext, cookieToken); // Assert Assert.NotNull(fieldToken); @@ -83,7 +83,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal }; var httpContext = new DefaultHttpContext(); - var principal = new ClaimsPrincipal(new MyAuthenticatedIdentityWithoutUsername()); + httpContext.User = new ClaimsPrincipal(new MyAuthenticatedIdentityWithoutUsername()); var options = new AntiforgeryOptions(); var claimUidExtractor = new Mock().Object; @@ -94,7 +94,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal // Act & assert var exception = Assert.Throws( - () => tokenProvider.GenerateRequestToken(httpContext, principal, cookieToken)); + () => tokenProvider.GenerateRequestToken(httpContext, cookieToken)); Assert.Equal( "The provided identity of type " + $"'{typeof(MyAuthenticatedIdentityWithoutUsername).FullName}' " + @@ -114,7 +114,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal var cookieToken = new AntiforgeryToken() { IsCookieToken = true }; var httpContext = new DefaultHttpContext(); - var principal = new ClaimsPrincipal(new MyAuthenticatedIdentityWithoutUsername()); + httpContext.User = new ClaimsPrincipal(new MyAuthenticatedIdentityWithoutUsername()); var mockAdditionalDataProvider = new Mock(); mockAdditionalDataProvider.Setup(o => o.GetAdditionalData(httpContext)) @@ -127,7 +127,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal additionalDataProvider: mockAdditionalDataProvider.Object); // Act - var fieldToken = tokenProvider.GenerateRequestToken(httpContext, principal, cookieToken); + var fieldToken = tokenProvider.GenerateRequestToken(httpContext, cookieToken); // Assert Assert.NotNull(fieldToken); @@ -146,7 +146,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal var identity = GetAuthenticatedIdentity("some-identity"); var httpContext = new DefaultHttpContext(); - var principal = new ClaimsPrincipal(identity); + httpContext.User = new ClaimsPrincipal(identity); byte[] data = new byte[256 / 8]; using (var rng = RandomNumberGenerator.Create()) @@ -165,7 +165,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal additionalDataProvider: null); // Act - var fieldToken = tokenProvider.GenerateRequestToken(httpContext, principal, cookieToken); + var fieldToken = tokenProvider.GenerateRequestToken(httpContext, cookieToken); // Assert Assert.NotNull(fieldToken); @@ -189,7 +189,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal mockIdentity.Setup(o => o.Name) .Returns("my-username"); - var principal = new ClaimsPrincipal(mockIdentity.Object); + httpContext.User = new ClaimsPrincipal(mockIdentity.Object); var claimUidExtractor = new Mock().Object; @@ -198,7 +198,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal additionalDataProvider: null); // Act - var fieldToken = tokenProvider.GenerateRequestToken(httpContext, principal, cookieToken); + var fieldToken = tokenProvider.GenerateRequestToken(httpContext, cookieToken); // Assert Assert.NotNull(fieldToken); @@ -271,7 +271,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal { // Arrange var httpContext = new DefaultHttpContext(); - var principal = new ClaimsPrincipal(new ClaimsIdentity()); + httpContext.User = new ClaimsPrincipal(new ClaimsIdentity()); var fieldtoken = new AntiforgeryToken() { IsCookieToken = false }; @@ -282,7 +282,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal // Act & Assert string message; var ex = Assert.Throws( - () => tokenProvider.TryValidateTokenSet(httpContext, principal, null, fieldtoken, out message)); + () => tokenProvider.TryValidateTokenSet(httpContext, null, fieldtoken, out message)); var trimmed = ex.Message.Substring(0, ex.Message.IndexOf(Environment.NewLine)); Assert.Equal(@"The required antiforgery cookie token must be provided.", trimmed); @@ -293,7 +293,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal { // Arrange var httpContext = new DefaultHttpContext(); - var principal = new ClaimsPrincipal(new ClaimsIdentity()); + httpContext.User = new ClaimsPrincipal(new ClaimsIdentity()); var cookieToken = new AntiforgeryToken() { IsCookieToken = true }; @@ -305,7 +305,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal // Act & Assert string message; var ex = Assert.Throws( - () => tokenProvider.TryValidateTokenSet(httpContext, principal, cookieToken, null, out message)); + () => tokenProvider.TryValidateTokenSet(httpContext, cookieToken, null, out message)); var trimmed = ex.Message.Substring(0, ex.Message.IndexOf(Environment.NewLine)); Assert.Equal("The required antiforgery request token must be provided.", trimmed); @@ -316,7 +316,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal { // Arrange var httpContext = new DefaultHttpContext(); - var principal = new ClaimsPrincipal(new ClaimsIdentity()); + httpContext.User = new ClaimsPrincipal(new ClaimsIdentity()); var cookieToken = new AntiforgeryToken() { IsCookieToken = true }; var fieldtoken = new AntiforgeryToken() { IsCookieToken = false }; @@ -331,7 +331,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal // Act string message; - var result = tokenProvider.TryValidateTokenSet(httpContext, principal, fieldtoken, fieldtoken, out message); + var result = tokenProvider.TryValidateTokenSet(httpContext, fieldtoken, fieldtoken, out message); // Assert Assert.False(result); @@ -343,7 +343,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal { // Arrange var httpContext = new DefaultHttpContext(); - var principal = new ClaimsPrincipal(new ClaimsIdentity()); + httpContext.User = new ClaimsPrincipal(new ClaimsIdentity()); var cookieToken = new AntiforgeryToken() { IsCookieToken = true }; var fieldtoken = new AntiforgeryToken() { IsCookieToken = false }; @@ -358,7 +358,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal // Act string message; - var result = tokenProvider.TryValidateTokenSet(httpContext, principal, cookieToken, cookieToken, out message); + var result = tokenProvider.TryValidateTokenSet(httpContext, cookieToken, cookieToken, out message); // Assert Assert.False(result); @@ -370,7 +370,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal { // Arrange var httpContext = new DefaultHttpContext(); - var principal = new ClaimsPrincipal(new ClaimsIdentity()); + httpContext.User = new ClaimsPrincipal(new ClaimsIdentity()); var cookieToken = new AntiforgeryToken() { IsCookieToken = true }; var fieldtoken = new AntiforgeryToken() { IsCookieToken = false }; @@ -383,7 +383,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal // Act string message; - var result = tokenProvider.TryValidateTokenSet(httpContext, principal, cookieToken, fieldtoken, out message); + var result = tokenProvider.TryValidateTokenSet(httpContext, cookieToken, fieldtoken, out message); // Assert Assert.False(result); @@ -399,7 +399,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal // Arrange var httpContext = new DefaultHttpContext(); var identity = GetAuthenticatedIdentity(identityUsername); - var principal = new ClaimsPrincipal(identity); + httpContext.User = new ClaimsPrincipal(identity); var cookieToken = new AntiforgeryToken() { IsCookieToken = true }; var fieldtoken = new AntiforgeryToken() @@ -423,7 +423,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal // Act string message; - var result = tokenProvider.TryValidateTokenSet(httpContext, principal, cookieToken, fieldtoken, out message); + var result = tokenProvider.TryValidateTokenSet(httpContext, cookieToken, fieldtoken, out message); // Assert Assert.False(result); @@ -436,7 +436,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal // Arrange var httpContext = new DefaultHttpContext(); var identity = GetAuthenticatedIdentity("the-user"); - var principal = new ClaimsPrincipal(identity); + httpContext.User = new ClaimsPrincipal(identity); var cookieToken = new AntiforgeryToken() { IsCookieToken = true }; var fieldtoken = new AntiforgeryToken() @@ -461,7 +461,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal // Act string message; - var result = tokenProvider.TryValidateTokenSet(httpContext, principal, cookieToken, fieldtoken, out message); + var result = tokenProvider.TryValidateTokenSet(httpContext, cookieToken, fieldtoken, out message); // Assert Assert.False(result); @@ -474,7 +474,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal // Arrange var httpContext = new DefaultHttpContext(); var identity = new ClaimsIdentity(); - var principal = new ClaimsPrincipal(identity); + httpContext.User = new ClaimsPrincipal(identity); var cookieToken = new AntiforgeryToken() { IsCookieToken = true }; var fieldtoken = new AntiforgeryToken() @@ -498,7 +498,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal // Act string message; - var result = tokenProvider.TryValidateTokenSet(httpContext, principal, cookieToken, fieldtoken, out message); + var result = tokenProvider.TryValidateTokenSet(httpContext, cookieToken, fieldtoken, out message); // Assert Assert.False(result); @@ -511,7 +511,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal // Arrange var httpContext = new DefaultHttpContext(); var identity = new ClaimsIdentity(); - var principal = new ClaimsPrincipal(identity); + httpContext.User = new ClaimsPrincipal(identity); var cookieToken = new AntiforgeryToken() { IsCookieToken = true }; var fieldtoken = new AntiforgeryToken() @@ -532,7 +532,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal // Act string message; - var result = tokenProvider.TryValidateTokenSet(httpContext, principal, cookieToken, fieldtoken, out message); + var result = tokenProvider.TryValidateTokenSet(httpContext, cookieToken, fieldtoken, out message); // Assert Assert.True(result); @@ -545,7 +545,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal // Arrange var httpContext = new DefaultHttpContext(); var identity = GetAuthenticatedIdentity("the-user"); - var principal = new ClaimsPrincipal(identity); + httpContext.User = new ClaimsPrincipal(identity); var cookieToken = new AntiforgeryToken() { IsCookieToken = true }; var fieldtoken = new AntiforgeryToken() @@ -566,7 +566,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal // Act string message; - var result = tokenProvider.TryValidateTokenSet(httpContext, principal, cookieToken, fieldtoken, out message); + var result = tokenProvider.TryValidateTokenSet(httpContext, cookieToken, fieldtoken, out message); // Assert Assert.True(result); @@ -579,7 +579,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal // Arrange var httpContext = new DefaultHttpContext(); var identity = GetAuthenticatedIdentity("the-user"); - var principal = new ClaimsPrincipal(identity); + httpContext.User = new ClaimsPrincipal(identity); var cookieToken = new AntiforgeryToken() { IsCookieToken = true }; var fieldtoken = new AntiforgeryToken() @@ -599,7 +599,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal // Act string message; - var result = tokenProvider.TryValidateTokenSet(httpContext, principal, cookieToken, fieldtoken, out message); + var result = tokenProvider.TryValidateTokenSet(httpContext, cookieToken, fieldtoken, out message); // Assert Assert.True(result); From 1e90efdf32648051cb57b1681649edcf6ecfd78b Mon Sep 17 00:00:00 2001 From: Pranav K Date: Wed, 6 Apr 2016 09:47:42 -0700 Subject: [PATCH 119/296] Updating to release. --- NuGet.config | 2 +- build.ps1 | 2 +- build.sh | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/NuGet.config b/NuGet.config index 52bf414192..71b9724a09 100644 --- a/NuGet.config +++ b/NuGet.config @@ -1,7 +1,7 @@ - + diff --git a/build.ps1 b/build.ps1 index 8f2f99691a..cf8bff13bb 100644 --- a/build.ps1 +++ b/build.ps1 @@ -33,7 +33,7 @@ cd $PSScriptRoot $repoFolder = $PSScriptRoot $env:REPO_FOLDER = $repoFolder -$koreBuildZip="https://github.com/aspnet/KoreBuild/archive/dev.zip" +$koreBuildZip="https://github.com/aspnet/KoreBuild/archive/release.zip" if ($env:KOREBUILD_ZIP) { $koreBuildZip=$env:KOREBUILD_ZIP diff --git a/build.sh b/build.sh index f4208100eb..f88fe4052e 100755 --- a/build.sh +++ b/build.sh @@ -2,7 +2,7 @@ repoFolder="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" cd $repoFolder -koreBuildZip="https://github.com/aspnet/KoreBuild/archive/dev.zip" +koreBuildZip="https://github.com/aspnet/KoreBuild/archive/release.zip" if [ ! -z $KOREBUILD_ZIP ]; then koreBuildZip=$KOREBUILD_ZIP fi From 04a4772fe5dcd4d076699de9dd3ffedc232ef1cc Mon Sep 17 00:00:00 2001 From: Pranav K Date: Thu, 7 Apr 2016 15:50:42 -0700 Subject: [PATCH 120/296] Removing imports from src projects --- src/Microsoft.AspNetCore.Antiforgery/project.json | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/src/Microsoft.AspNetCore.Antiforgery/project.json b/src/Microsoft.AspNetCore.Antiforgery/project.json index 9d0fd780b5..5f259a5011 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/project.json +++ b/src/Microsoft.AspNetCore.Antiforgery/project.json @@ -24,14 +24,12 @@ "Microsoft.Extensions.ObjectPool": "1.0.0-*" }, "frameworks": { - "netstandard1.3": { - "imports": [ - "dotnet5.4" - ] - }, + "netstandard1.3": {}, "net451": { "frameworkAssemblies": { - "System.Runtime": { "type": "build"} + "System.Runtime": { + "type": "build" + } } } } From 330200874d15ed5742745fc9cc9bb80e2ea1a224 Mon Sep 17 00:00:00 2001 From: Kiran Challa Date: Fri, 8 Apr 2016 15:04:49 -0700 Subject: [PATCH 121/296] Changed DNX451 references to NET451 --- .../Internal/DefaultClaimUidExtractorTest.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultClaimUidExtractorTest.cs b/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultClaimUidExtractorTest.cs index 59e2d3a3ac..5b694ace88 100644 --- a/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultClaimUidExtractorTest.cs +++ b/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultClaimUidExtractorTest.cs @@ -60,7 +60,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal identity.AddClaim(new Claim(ClaimTypes.Email, "someone@antifrogery.com")); identity.AddClaim(new Claim(ClaimTypes.GivenName, "some")); identity.AddClaim(new Claim(ClaimTypes.Surname, "one")); -#if DNX451 +#if NET451 // CoreCLR doesn't support an 'empty' name identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, string.Empty)); #endif From 921af14e1fafaf8f0bfbc21180e4d8697f9e0d32 Mon Sep 17 00:00:00 2001 From: John Luo Date: Fri, 8 Apr 2016 10:51:48 -0700 Subject: [PATCH 122/296] Move web.config and use ANCM --- samples/AntiforgerySample/Startup.cs | 2 +- samples/AntiforgerySample/project.json | 25 +++++++------------- samples/AntiforgerySample/web.config | 9 +++++++ samples/AntiforgerySample/wwwroot/web.config | 9 ------- 4 files changed, 18 insertions(+), 27 deletions(-) create mode 100644 samples/AntiforgerySample/web.config delete mode 100644 samples/AntiforgerySample/wwwroot/web.config diff --git a/samples/AntiforgerySample/Startup.cs b/samples/AntiforgerySample/Startup.cs index df60314f9c..b227bb6c7c 100644 --- a/samples/AntiforgerySample/Startup.cs +++ b/samples/AntiforgerySample/Startup.cs @@ -71,7 +71,7 @@ namespace AntiforgerySample var host = new WebHostBuilder() .UseDefaultHostingConfiguration(args) .UseKestrel() - .UseIISPlatformHandlerUrl() + .UseIISIntegration() .UseStartup() .Build(); diff --git a/samples/AntiforgerySample/project.json b/samples/AntiforgerySample/project.json index fd999ad29b..67e82d719b 100644 --- a/samples/AntiforgerySample/project.json +++ b/samples/AntiforgerySample/project.json @@ -4,7 +4,7 @@ "Microsoft.AspNetCore.Antiforgery": "1.0.0-*", "Microsoft.AspNetCore.Http.Abstractions": "1.0.0-*", "Microsoft.AspNetCore.Http.Extensions": "1.0.0-*", - "Microsoft.AspNetCore.IISPlatformHandler": "1.0.0-*", + "Microsoft.AspNetCore.Server.IISIntegration": "1.0.0-*", "Microsoft.AspNetCore.Server.Kestrel": "1.0.0-*", "Microsoft.AspNetCore.StaticFiles": "1.0.0-*", "Microsoft.NETCore.Platforms": "1.0.1-*", @@ -13,28 +13,19 @@ "compilationOptions": { "emitEntryPoint": true }, - "commands": { - "web": "AntiforgerySample" - }, "frameworks": { "net451": {}, "netstandardapp1.5": { "imports": [ - "dnxcore50", - "portable-net451+win8" - ] + "dnxcore50" + ], + "dependencies": { + "NETStandard.Library": "1.5.0-*" + } } }, - "publishExclude": [ - "node_modules", - "bower_components", - "**.xproj", - "**.user", - "**.vspscc" - ], - "exclude": [ + "content": [ "wwwroot", - "node_modules", - "bower_components" + "web.config" ] } \ No newline at end of file diff --git a/samples/AntiforgerySample/web.config b/samples/AntiforgerySample/web.config new file mode 100644 index 0000000000..22a337cbe2 --- /dev/null +++ b/samples/AntiforgerySample/web.config @@ -0,0 +1,9 @@ + + + + + + + + + \ No newline at end of file diff --git a/samples/AntiforgerySample/wwwroot/web.config b/samples/AntiforgerySample/wwwroot/web.config deleted file mode 100644 index 9a0d90abf8..0000000000 --- a/samples/AntiforgerySample/wwwroot/web.config +++ /dev/null @@ -1,9 +0,0 @@ - - - - - - - - - \ No newline at end of file From 8570acbb731c4a2a5ccdcaa7a115b60617b4f725 Mon Sep 17 00:00:00 2001 From: Pavel Krymets Date: Fri, 15 Apr 2016 09:51:51 -0700 Subject: [PATCH 123/296] Migrate tests, tools and samples to portable --- samples/AntiforgerySample/project.json | 8 +++++--- .../project.json | 7 +++++-- .../Microsoft.AspNetCore.Antiforgery.Test/project.json | 10 +++++++--- 3 files changed, 17 insertions(+), 8 deletions(-) diff --git a/samples/AntiforgerySample/project.json b/samples/AntiforgerySample/project.json index 67e82d719b..52fd68c4cf 100644 --- a/samples/AntiforgerySample/project.json +++ b/samples/AntiforgerySample/project.json @@ -7,7 +7,6 @@ "Microsoft.AspNetCore.Server.IISIntegration": "1.0.0-*", "Microsoft.AspNetCore.Server.Kestrel": "1.0.0-*", "Microsoft.AspNetCore.StaticFiles": "1.0.0-*", - "Microsoft.NETCore.Platforms": "1.0.1-*", "Newtonsoft.Json": "8.0.3" }, "compilationOptions": { @@ -15,12 +14,15 @@ }, "frameworks": { "net451": {}, - "netstandardapp1.5": { + "netcoreapp1.0": { "imports": [ "dnxcore50" ], "dependencies": { - "NETStandard.Library": "1.5.0-*" + "Microsoft.NETCore.App": { + "version": "1.0.0-*", + "type": "platform" + } } } }, diff --git a/test/Microsoft.AspNetCore.Antiforgery.FunctionalTests/project.json b/test/Microsoft.AspNetCore.Antiforgery.FunctionalTests/project.json index c26724bfb1..95b3ebbe2a 100644 --- a/test/Microsoft.AspNetCore.Antiforgery.FunctionalTests/project.json +++ b/test/Microsoft.AspNetCore.Antiforgery.FunctionalTests/project.json @@ -6,12 +6,15 @@ }, "testRunner": "xunit", "frameworks": { - "netstandardapp1.5": { + "netcoreapp1.0": { "dependencies": { + "Microsoft.NETCore.App": { + "version": "1.0.0-*", + "type": "platform" + }, "moq.netcore": "4.4.0-beta8", "System.Net.Http": "4.0.1-*", "dotnet-test-xunit": "1.0.0-dev-*", - "NETStandard.Library": "1.5.0-*", "System.Diagnostics.Process": "4.1.0-*" }, "imports": [ diff --git a/test/Microsoft.AspNetCore.Antiforgery.Test/project.json b/test/Microsoft.AspNetCore.Antiforgery.Test/project.json index d9a5c2fd95..17e122bc2a 100644 --- a/test/Microsoft.AspNetCore.Antiforgery.Test/project.json +++ b/test/Microsoft.AspNetCore.Antiforgery.Test/project.json @@ -14,12 +14,16 @@ }, "testRunner": "xunit", "frameworks": { - "netstandardapp1.5": { + "netcoreapp1.0": { "dependencies": { + "Microsoft.NETCore.App": { + "version": "1.0.0-*", + "type": "platform" + }, "moq.netcore": "4.4.0-beta8", "dotnet-test-xunit": "1.0.0-dev-*", - "NETStandard.Library": "1.5.0-*", - "System.Diagnostics.Process": "4.1.0-*" + "System.Diagnostics.Process": "4.1.0-*", + "System.Diagnostics.TraceSource": "4.0.0-*" }, "imports": [ "dnxcore50", From fd81151d31098b8c21a29d241a16e9e3128a4699 Mon Sep 17 00:00:00 2001 From: Ryan Brandenburg Date: Mon, 18 Apr 2016 11:29:42 -0700 Subject: [PATCH 124/296] Preserve X-Frame-Options if it was already set --- .../Internal/DefaultAntiforgery.cs | 2 +- .../Internal/DefaultAntiforgeryTest.cs | 25 +++++++++++++++++++ 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgery.cs b/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgery.cs index 9227bd6b78..44310c5187 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgery.cs +++ b/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgery.cs @@ -248,7 +248,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal _tokenStore.SaveCookieToken(httpContext, cookieToken); } - if (!_options.SuppressXFrameOptionsHeader) + if (!_options.SuppressXFrameOptionsHeader && !httpContext.Response.Headers.ContainsKey("X-Frame-Options")) { // Adding X-Frame-Options header to prevent ClickJacking. See // http://tools.ietf.org/html/draft-ietf-websec-x-frame-options-10 diff --git a/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTest.cs b/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTest.cs index 45bd0236ba..335f2c91a2 100644 --- a/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTest.cs +++ b/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTest.cs @@ -783,6 +783,31 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal Times.Never); } + [Fact] + public void SetCookieTokenAndHeader_PreserveXFrameOptionsHeader() + { + // Arrange + var options = new AntiforgeryOptions(); + var antiforgeryFeature = new AntiforgeryFeature(); + var expectedHeaderValue = "DIFFERENTORIGIN"; + + // Generate a new cookie. + var context = CreateMockContext( + options, + useOldCookie: false, + isOldCookieValid: false, + antiforgeryFeature: antiforgeryFeature); + var antiforgery = GetAntiforgery(context); + context.HttpContext.Response.Headers["X-Frame-Options"] = expectedHeaderValue; + + // Act + antiforgery.SetCookieTokenAndHeader(context.HttpContext); + + // Assert + var xFrameOptions = context.HttpContext.Response.Headers["X-Frame-Options"]; + Assert.Equal(expectedHeaderValue, xFrameOptions); + } + [Theory] [InlineData(false, "SAMEORIGIN")] [InlineData(true, null)] From eabe83a72db137afb5cb2d645151233b3f76444b Mon Sep 17 00:00:00 2001 From: Ryan Brandenburg Date: Mon, 18 Apr 2016 12:23:48 -0700 Subject: [PATCH 125/296] Prevent null-ref and log exceptions form Serializer --- .../Internal/AntiforgeryLoggerExtensions.cs | 10 +++++ .../Internal/DefaultAntiforgery.cs | 14 ++++--- .../Internal/DefaultAntiforgeryTest.cs | 41 ++++++++++++++++++- 3 files changed, 59 insertions(+), 6 deletions(-) diff --git a/src/Microsoft.AspNetCore.Antiforgery/Internal/AntiforgeryLoggerExtensions.cs b/src/Microsoft.AspNetCore.Antiforgery/Internal/AntiforgeryLoggerExtensions.cs index aae0b3176e..5e115bb76a 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/Internal/AntiforgeryLoggerExtensions.cs +++ b/src/Microsoft.AspNetCore.Antiforgery/Internal/AntiforgeryLoggerExtensions.cs @@ -14,6 +14,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal private static readonly Action _missingRequestToken; private static readonly Action _newCookieToken; private static readonly Action _reusedCookieToken; + private static readonly Action _tokenDeserializeException; static AntiforgeryLoggerExtensions() { @@ -42,6 +43,10 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal LogLevel.Debug, 6, "An antiforgery cookie token was reused."); + _tokenDeserializeException = LoggerMessage.Define( + LogLevel.Error, + 7, + "An exception was thrown while deserializing the token."); } public static void ValidationFailed(this ILogger logger, string message) @@ -73,5 +78,10 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal { _reusedCookieToken(logger, null); } + + public static void TokenDeserializeException(this ILogger logger, Exception exception) + { + _tokenDeserializeException(logger, exception); + } } } diff --git a/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgery.cs b/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgery.cs index 44310c5187..eeb92cf777 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgery.cs +++ b/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgery.cs @@ -5,7 +5,6 @@ using System; using System.Diagnostics; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; -using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; @@ -329,15 +328,20 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal try { var serializedToken = _tokenStore.GetCookieToken(httpContext); - var token = _tokenSerializer.Deserialize(serializedToken); - return token; + if (serializedToken != null) + { + var token = _tokenSerializer.Deserialize(serializedToken); + return token; + } } - catch + catch (Exception ex) { // ignore failures since we'll just generate a new token - return null; + _logger.TokenDeserializeException(ex); } + + return null; } private IAntiforgeryFeature GetTokensInternal(HttpContext httpContext) diff --git a/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTest.cs b/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTest.cs index 335f2c91a2..09de9243d5 100644 --- a/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTest.cs +++ b/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTest.cs @@ -928,6 +928,43 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal Times.Never); } + [Fact] + public void SetCookieTokenAndHeader_NullCookieToken() + { + // Arrange + var antiforgeryFeature = new AntiforgeryFeature + { + HaveDeserializedCookieToken = false, + HaveGeneratedNewCookieToken = false, + HaveStoredNewCookieToken = true, + NewCookieToken = new AntiforgeryToken(), + NewCookieTokenString = "serialized-cookie-token-from-context", + NewRequestToken = new AntiforgeryToken(), + NewRequestTokenString = "serialized-form-token-from-context", + }; + var context = CreateMockContext( + new AntiforgeryOptions(), + useOldCookie: false, + isOldCookieValid: false, + antiforgeryFeature: antiforgeryFeature); + var testTokenSet = new TestTokenSet + { + OldCookieTokenString = null + }; + + var nullTokenStore = GetTokenStore(context.HttpContext, testTokenSet, false); + var antiforgery = GetAntiforgery( + context.HttpContext, + tokenGenerator: context.TokenGenerator.Object, + tokenStore: nullTokenStore.Object); + + // Act + antiforgery.SetCookieTokenAndHeader(context.HttpContext); + + // Assert + context.TokenSerializer.Verify(s => s.Deserialize(null), Times.Never); + } + private DefaultAntiforgery GetAntiforgery( HttpContext httpContext, AntiforgeryOptions options = null, @@ -1053,7 +1090,9 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal mockGenerator .Setup(o => o.GenerateCookieToken()) .Returns(useOldCookie ? testTokenSet.OldCookieToken : testTokenSet.NewCookieToken); - + mockGenerator + .Setup(o => o.IsCookieTokenValid(null)) + .Returns(false); mockGenerator .Setup(o => o.IsCookieTokenValid(testTokenSet.OldCookieToken)) .Returns(isOldCookieValid); From a35e5a02c346b6dfd28f0896e29984cc32b6131d Mon Sep 17 00:00:00 2001 From: Pavel Krymets Date: Mon, 18 Apr 2016 17:07:34 -0700 Subject: [PATCH 126/296] Bring Microsoft.NETCore.Platforms dependency back --- samples/AntiforgerySample/project.json | 1 + .../project.json | 1 + test/Microsoft.AspNetCore.Antiforgery.Test/project.json | 1 + 3 files changed, 3 insertions(+) diff --git a/samples/AntiforgerySample/project.json b/samples/AntiforgerySample/project.json index 52fd68c4cf..4ff0ec051e 100644 --- a/samples/AntiforgerySample/project.json +++ b/samples/AntiforgerySample/project.json @@ -1,6 +1,7 @@ { "version": "1.0.0-*", "dependencies": { + "Microsoft.NETCore.Platforms": "1.0.1-*", "Microsoft.AspNetCore.Antiforgery": "1.0.0-*", "Microsoft.AspNetCore.Http.Abstractions": "1.0.0-*", "Microsoft.AspNetCore.Http.Extensions": "1.0.0-*", diff --git a/test/Microsoft.AspNetCore.Antiforgery.FunctionalTests/project.json b/test/Microsoft.AspNetCore.Antiforgery.FunctionalTests/project.json index 95b3ebbe2a..f9a95e6ff6 100644 --- a/test/Microsoft.AspNetCore.Antiforgery.FunctionalTests/project.json +++ b/test/Microsoft.AspNetCore.Antiforgery.FunctionalTests/project.json @@ -1,5 +1,6 @@ { "dependencies": { + "Microsoft.NETCore.Platforms": "1.0.1-*", "AntiforgerySample": "1.0.0-*", "Microsoft.AspNetCore.TestHost": "1.0.0-*", "Microsoft.AspNetCore.Testing": "1.0.0-*" diff --git a/test/Microsoft.AspNetCore.Antiforgery.Test/project.json b/test/Microsoft.AspNetCore.Antiforgery.Test/project.json index 17e122bc2a..482a06a14e 100644 --- a/test/Microsoft.AspNetCore.Antiforgery.Test/project.json +++ b/test/Microsoft.AspNetCore.Antiforgery.Test/project.json @@ -4,6 +4,7 @@ "keyFile": "../../tools/Key.snk" }, "dependencies": { + "Microsoft.NETCore.Platforms": "1.0.1-*", "Microsoft.AspNetCore.Antiforgery": "1.0.0-*", "Microsoft.AspNetCore.Http": "1.0.0-*", "Microsoft.AspNetCore.Testing": "1.0.0-*", From 9aad34e7113ae0dee77bab3086c00b53a8d8cf59 Mon Sep 17 00:00:00 2001 From: Pranav K Date: Tue, 19 Apr 2016 14:53:51 -0700 Subject: [PATCH 127/296] Use latest build of dotnet-test-xunit --- .../project.json | 2 +- test/Microsoft.AspNetCore.Antiforgery.Test/project.json | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/test/Microsoft.AspNetCore.Antiforgery.FunctionalTests/project.json b/test/Microsoft.AspNetCore.Antiforgery.FunctionalTests/project.json index f9a95e6ff6..90cacdd79a 100644 --- a/test/Microsoft.AspNetCore.Antiforgery.FunctionalTests/project.json +++ b/test/Microsoft.AspNetCore.Antiforgery.FunctionalTests/project.json @@ -15,7 +15,7 @@ }, "moq.netcore": "4.4.0-beta8", "System.Net.Http": "4.0.1-*", - "dotnet-test-xunit": "1.0.0-dev-*", + "dotnet-test-xunit": "1.0.0-*", "System.Diagnostics.Process": "4.1.0-*" }, "imports": [ diff --git a/test/Microsoft.AspNetCore.Antiforgery.Test/project.json b/test/Microsoft.AspNetCore.Antiforgery.Test/project.json index 482a06a14e..93b122584d 100644 --- a/test/Microsoft.AspNetCore.Antiforgery.Test/project.json +++ b/test/Microsoft.AspNetCore.Antiforgery.Test/project.json @@ -22,7 +22,7 @@ "type": "platform" }, "moq.netcore": "4.4.0-beta8", - "dotnet-test-xunit": "1.0.0-dev-*", + "dotnet-test-xunit": "1.0.0-*", "System.Diagnostics.Process": "4.1.0-*", "System.Diagnostics.TraceSource": "4.0.0-*" }, From 2656c528c31f2a1e270c33b27aec161fffe76b51 Mon Sep 17 00:00:00 2001 From: BrennanConroy Date: Mon, 25 Apr 2016 11:44:56 -0700 Subject: [PATCH 128/296] Update web.config and add publish tool --- samples/AntiforgerySample/project.json | 11 ++++++++++- samples/AntiforgerySample/web.config | 2 +- 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/samples/AntiforgerySample/project.json b/samples/AntiforgerySample/project.json index 4ff0ec051e..a6bf3398de 100644 --- a/samples/AntiforgerySample/project.json +++ b/samples/AntiforgerySample/project.json @@ -30,5 +30,14 @@ "content": [ "wwwroot", "web.config" - ] + ], + "tools": { + "Microsoft.AspNetCore.Server.IISIntegration.Tools": { + "version": "1.0.0-*", + "imports": "portable-net45+wp80+win8+wpa81+dnxcore50" + } + }, + "scripts": { + "postpublish": "dotnet publish-iis --publish-folder %publish:OutputPath% --framework %publish:FullTargetFramework%" + } } \ No newline at end of file diff --git a/samples/AntiforgerySample/web.config b/samples/AntiforgerySample/web.config index 22a337cbe2..f7ac679334 100644 --- a/samples/AntiforgerySample/web.config +++ b/samples/AntiforgerySample/web.config @@ -4,6 +4,6 @@ - + \ No newline at end of file From 3aa2febb6f0bee81aaab4337ba5102b90dcebd9f Mon Sep 17 00:00:00 2001 From: John Luo Date: Wed, 27 Apr 2016 15:39:07 -0700 Subject: [PATCH 129/296] Remove references to UseDefaultHostingConfiguration --- samples/AntiforgerySample/Startup.cs | 1 - 1 file changed, 1 deletion(-) diff --git a/samples/AntiforgerySample/Startup.cs b/samples/AntiforgerySample/Startup.cs index b227bb6c7c..1eff1c760d 100644 --- a/samples/AntiforgerySample/Startup.cs +++ b/samples/AntiforgerySample/Startup.cs @@ -69,7 +69,6 @@ namespace AntiforgerySample public static void Main(string[] args) { var host = new WebHostBuilder() - .UseDefaultHostingConfiguration(args) .UseKestrel() .UseIISIntegration() .UseStartup() From 05602d36db427647780a4c020041f328d9a3fefd Mon Sep 17 00:00:00 2001 From: Pranav K Date: Mon, 2 May 2016 11:27:05 -0700 Subject: [PATCH 130/296] Fix build warnings --- samples/AntiforgerySample/project.json | 12 +++++++----- .../project.json | 18 ++++++++++-------- .../project.json | 2 +- .../project.json | 4 ++-- 4 files changed, 20 insertions(+), 16 deletions(-) diff --git a/samples/AntiforgerySample/project.json b/samples/AntiforgerySample/project.json index a6bf3398de..ac3852ae2f 100644 --- a/samples/AntiforgerySample/project.json +++ b/samples/AntiforgerySample/project.json @@ -10,7 +10,7 @@ "Microsoft.AspNetCore.StaticFiles": "1.0.0-*", "Newtonsoft.Json": "8.0.3" }, - "compilationOptions": { + "buildOptions": { "emitEntryPoint": true }, "frameworks": { @@ -27,10 +27,12 @@ } } }, - "content": [ - "wwwroot", - "web.config" - ], + "publishOptions": { + "include": [ + "wwwroot", + "web.config" + ] + }, "tools": { "Microsoft.AspNetCore.Server.IISIntegration.Tools": { "version": "1.0.0-*", diff --git a/src/Microsoft.AspNetCore.Antiforgery/project.json b/src/Microsoft.AspNetCore.Antiforgery/project.json index 5f259a5011..b5a59d28df 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/project.json +++ b/src/Microsoft.AspNetCore.Antiforgery/project.json @@ -1,11 +1,7 @@ { "description": "An antiforgery system for ASP.NET Core designed to generate and validate tokens to prevent Cross-Site Request Forgery attacks.", - "tags": [ - "aspnetcore", - "antiforgery" - ], "version": "1.0.0-*", - "compilationOptions": { + "buildOptions": { "warningsAsErrors": true, "keyFile": "../../tools/Key.snk", "nowarn": [ @@ -13,9 +9,15 @@ ], "xmlDoc": true }, - "repository": { - "type": "git", - "url": "git://github.com/aspnet/antiforgery" + "packOptions": { + "repository": { + "type": "git", + "url": "git://github.com/aspnet/antiforgery" + }, + "tags": [ + "aspnetcore", + "antiforgery" + ] }, "dependencies": { "Microsoft.AspNetCore.DataProtection": "1.0.0-*", diff --git a/test/Microsoft.AspNetCore.Antiforgery.FunctionalTests/project.json b/test/Microsoft.AspNetCore.Antiforgery.FunctionalTests/project.json index 90cacdd79a..4dc6f4d698 100644 --- a/test/Microsoft.AspNetCore.Antiforgery.FunctionalTests/project.json +++ b/test/Microsoft.AspNetCore.Antiforgery.FunctionalTests/project.json @@ -1,5 +1,6 @@ { "dependencies": { + "dotnet-test-xunit": "1.0.0-*", "Microsoft.NETCore.Platforms": "1.0.1-*", "AntiforgerySample": "1.0.0-*", "Microsoft.AspNetCore.TestHost": "1.0.0-*", @@ -15,7 +16,6 @@ }, "moq.netcore": "4.4.0-beta8", "System.Net.Http": "4.0.1-*", - "dotnet-test-xunit": "1.0.0-*", "System.Diagnostics.Process": "4.1.0-*" }, "imports": [ diff --git a/test/Microsoft.AspNetCore.Antiforgery.Test/project.json b/test/Microsoft.AspNetCore.Antiforgery.Test/project.json index 93b122584d..3e742a23c2 100644 --- a/test/Microsoft.AspNetCore.Antiforgery.Test/project.json +++ b/test/Microsoft.AspNetCore.Antiforgery.Test/project.json @@ -1,9 +1,10 @@ { - "compilationOptions": { + "buildOptions": { "warningsAsErrors": true, "keyFile": "../../tools/Key.snk" }, "dependencies": { + "dotnet-test-xunit": "1.0.0-*", "Microsoft.NETCore.Platforms": "1.0.1-*", "Microsoft.AspNetCore.Antiforgery": "1.0.0-*", "Microsoft.AspNetCore.Http": "1.0.0-*", @@ -22,7 +23,6 @@ "type": "platform" }, "moq.netcore": "4.4.0-beta8", - "dotnet-test-xunit": "1.0.0-*", "System.Diagnostics.Process": "4.1.0-*", "System.Diagnostics.TraceSource": "4.0.0-*" }, From 3595452af7d2b13258dcaf40e408513c3da25003 Mon Sep 17 00:00:00 2001 From: Kiran Challa Date: Wed, 18 May 2016 16:54:13 -0700 Subject: [PATCH 131/296] Change priority for request token source lookup. Header token now takes priority over form field token. --- .../Internal/DefaultAntiforgeryTokenStore.cs | 16 ++-- .../DefaultAntiforgeryTokenStoreTest.cs | 96 +++++++------------ 2 files changed, 45 insertions(+), 67 deletions(-) diff --git a/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgeryTokenStore.cs b/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgeryTokenStore.cs index cd20eea956..17c2e1465a 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgeryTokenStore.cs +++ b/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgeryTokenStore.cs @@ -44,8 +44,16 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal var cookieToken = httpContext.Request.Cookies[_options.CookieName]; + // We want to delay reading the form as much as possible, for example in case of large file uploads, + // request token could be part of the header. StringValues requestToken; - if (httpContext.Request.HasFormContentType) + if (_options.HeaderName != null) + { + requestToken = httpContext.Request.Headers[_options.HeaderName]; + } + + // Fall back to reading form instead + if (requestToken.Count == 0 && httpContext.Request.HasFormContentType) { // Check the content-type before accessing the form collection to make sure // we report errors gracefully. @@ -53,12 +61,6 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal requestToken = form[_options.FormFieldName]; } - // Fall back to header if the form value was not provided. - if (requestToken.Count == 0 && _options.HeaderName != null) - { - requestToken = httpContext.Request.Headers[_options.HeaderName]; - } - return new AntiforgeryTokenSet(requestToken, cookieToken, _options.FormFieldName, _options.HeaderName); } diff --git a/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTokenStoreTest.cs b/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTokenStoreTest.cs index 2b1f6152a3..09c27585fe 100644 --- a/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTokenStoreTest.cs +++ b/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTokenStoreTest.cs @@ -3,6 +3,7 @@ using System; using System.Collections.Generic; +using System.Threading; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.Internal; @@ -99,39 +100,15 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal } [Fact] - public async Task GetRequestTokens_NonFormContentType_HeaderDisabled_ReturnsNullToken() - { - // Arrange - var httpContext = GetHttpContext("cookie-name", "cookie-value"); - httpContext.Request.ContentType = "application/json"; - - // Will not be accessed - httpContext.Request.Form = null; - - var options = new AntiforgeryOptions() - { - CookieName = "cookie-name", - FormFieldName = "form-field-name", - HeaderName = null, - }; - - var tokenStore = new DefaultAntiforgeryTokenStore(new TestOptionsManager(options)); - - // Act - var tokenSet = await tokenStore.GetRequestTokensAsync(httpContext); - - // Assert - Assert.Equal("cookie-value", tokenSet.CookieToken); - Assert.Null(tokenSet.RequestToken); - } - - [Fact] - public async Task GetRequestTokens_FormContentType_FallbackHeaderToken() + public async Task GetRequestTokens_HeaderTokenTakensPriority_OverFormToken() { // Arrange var httpContext = GetHttpContext("cookie-name", "cookie-value"); httpContext.Request.ContentType = "application/x-www-form-urlencoded"; - httpContext.Request.Form = FormCollection.Empty; + httpContext.Request.Form = new FormCollection(new Dictionary + { + { "form-field-name", "form-value" }, + }); // header value has priority. httpContext.Request.Headers.Add("header-name", "header-value"); var options = new AntiforgeryOptions() @@ -151,6 +128,34 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal Assert.Equal("header-value", tokens.RequestToken); } + [Fact] + public async Task GetRequestTokens_NoHeaderToken_FallsBackToFormToken() + { + // Arrange + var httpContext = GetHttpContext("cookie-name", "cookie-value"); + httpContext.Request.ContentType = "application/x-www-form-urlencoded"; + httpContext.Request.Form = new FormCollection(new Dictionary + { + { "form-field-name", "form-value" }, + }); + + var options = new AntiforgeryOptions() + { + CookieName = "cookie-name", + FormFieldName = "form-field-name", + HeaderName = "header-name", + }; + + var tokenStore = new DefaultAntiforgeryTokenStore(new TestOptionsManager(options)); + + // Act + var tokens = await tokenStore.GetRequestTokensAsync(httpContext); + + // Assert + Assert.Equal("cookie-value", tokens.CookieToken); + Assert.Equal("form-value", tokens.RequestToken); + } + [Fact] public async Task GetRequestTokens_NonFormContentType_UsesHeaderToken() { @@ -180,7 +185,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal } [Fact] - public async Task GetRequestTokens_NonFormContentType_NoHeaderToken_ReturnsNullToken() + public async Task GetRequestTokens_NoHeaderToken_NonFormContentType_ReturnsNullToken() { // Arrange var httpContext = GetHttpContext("cookie-name", "cookie-value"); @@ -207,7 +212,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal } [Fact] - public async Task GetRequestTokens_BothFieldsEmpty_ReturnsNullTokens() + public async Task GetRequestTokens_BothHeaderValueAndFormFieldsEmpty_ReturnsNullTokens() { // Arrange var httpContext = GetHttpContext("cookie-name", "cookie-value"); @@ -231,35 +236,6 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal Assert.Null(tokenSet.RequestToken); } - [Fact] - public async Task GetFormToken_FormFieldIsValid_ReturnsToken() - { - // Arrange - var httpContext = GetHttpContext("cookie-name", "cookie-value"); - httpContext.Request.ContentType = "application/x-www-form-urlencoded"; - httpContext.Request.Form = new FormCollection(new Dictionary - { - { "form-field-name", "form-value" }, - }); - httpContext.Request.Headers.Add("header-name", "header-value"); // form value has priority. - - var options = new AntiforgeryOptions() - { - CookieName = "cookie-name", - FormFieldName = "form-field-name", - HeaderName = "header-name", - }; - - var tokenStore = new DefaultAntiforgeryTokenStore(new TestOptionsManager(options)); - - // Act - var tokens = await tokenStore.GetRequestTokensAsync(httpContext); - - // Assert - Assert.Equal("cookie-value", tokens.CookieToken); - Assert.Equal("form-value", tokens.RequestToken); - } - [Theory] [InlineData(true, true)] [InlineData(false, null)] From 54d9860eeae05baf39006b499c9c7af3f1350814 Mon Sep 17 00:00:00 2001 From: "N. Taylor Mullen" Date: Thu, 26 May 2016 10:06:26 -0700 Subject: [PATCH 132/296] Rename `ServiceCollectionExtensions` to `AntiforgeryServiceCollectionExtensions`. #84 --- ...nExtensions.cs => AntiforgeryServiceCollectionExtensions.cs} | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) rename src/Microsoft.AspNetCore.Antiforgery/{ServiceCollectionExtensions.cs => AntiforgeryServiceCollectionExtensions.cs} (98%) diff --git a/src/Microsoft.AspNetCore.Antiforgery/ServiceCollectionExtensions.cs b/src/Microsoft.AspNetCore.Antiforgery/AntiforgeryServiceCollectionExtensions.cs similarity index 98% rename from src/Microsoft.AspNetCore.Antiforgery/ServiceCollectionExtensions.cs rename to src/Microsoft.AspNetCore.Antiforgery/AntiforgeryServiceCollectionExtensions.cs index c16ac5c255..a82851b3e2 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/ServiceCollectionExtensions.cs +++ b/src/Microsoft.AspNetCore.Antiforgery/AntiforgeryServiceCollectionExtensions.cs @@ -13,7 +13,7 @@ namespace Microsoft.Extensions.DependencyInjection /// /// Extension methods for setting up antiforgery services in an . /// - public static class ServiceCollectionExtensions + public static class AntiforgeryServiceCollectionExtensions { /// /// Adds antiforgery services to the specified . From 9ac13d94c4a50bf8d8397c27b0c87787dd420e4b Mon Sep 17 00:00:00 2001 From: Cesar Blum Silveira Date: Fri, 27 May 2016 11:45:20 -0700 Subject: [PATCH 133/296] Fix OSX build on Travis. --- .travis.yml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.travis.yml b/.travis.yml index dd00cf00cc..0f6e51b48a 100644 --- a/.travis.yml +++ b/.travis.yml @@ -22,6 +22,8 @@ branches: - release - dev - /^(.*\/)?ci-.*$/ +before_install: + - if test "$TRAVIS_OS_NAME" == "osx"; then brew update; brew install openssl; brew link --force openssl; fi script: - ./build.sh --quiet verify notifications: From dd86306ec6d54acde50e1c6e7b11ee8a4a7485c9 Mon Sep 17 00:00:00 2001 From: Cesar Blum Silveira Date: Fri, 27 May 2016 17:47:50 -0700 Subject: [PATCH 134/296] Fix test pass. --- .../project.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/Microsoft.AspNetCore.Antiforgery.FunctionalTests/project.json b/test/Microsoft.AspNetCore.Antiforgery.FunctionalTests/project.json index 4dc6f4d698..f7d1b59a8a 100644 --- a/test/Microsoft.AspNetCore.Antiforgery.FunctionalTests/project.json +++ b/test/Microsoft.AspNetCore.Antiforgery.FunctionalTests/project.json @@ -15,7 +15,7 @@ "type": "platform" }, "moq.netcore": "4.4.0-beta8", - "System.Net.Http": "4.0.1-*", + "System.Net.Http": "4.1.0-*", "System.Diagnostics.Process": "4.1.0-*" }, "imports": [ From 3f78743011578533d28682e78eb5f62df7dc2288 Mon Sep 17 00:00:00 2001 From: jacalvar Date: Fri, 3 Jun 2016 13:08:13 -0700 Subject: [PATCH 135/296] Update Json.NET to 9.0.1-beta1 --- samples/AntiforgerySample/project.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/samples/AntiforgerySample/project.json b/samples/AntiforgerySample/project.json index ac3852ae2f..328c800623 100644 --- a/samples/AntiforgerySample/project.json +++ b/samples/AntiforgerySample/project.json @@ -8,7 +8,7 @@ "Microsoft.AspNetCore.Server.IISIntegration": "1.0.0-*", "Microsoft.AspNetCore.Server.Kestrel": "1.0.0-*", "Microsoft.AspNetCore.StaticFiles": "1.0.0-*", - "Newtonsoft.Json": "8.0.3" + "Newtonsoft.Json": "9.0.1-beta1" }, "buildOptions": { "emitEntryPoint": true From d8c1ac7c06a485479e72b1d04024472080ad7abb Mon Sep 17 00:00:00 2001 From: jacalvar Date: Fri, 3 Jun 2016 13:08:13 -0700 Subject: [PATCH 136/296] Remove unncessary imports --- samples/AntiforgerySample/project.json | 8 +------- 1 file changed, 1 insertion(+), 7 deletions(-) diff --git a/samples/AntiforgerySample/project.json b/samples/AntiforgerySample/project.json index 328c800623..6a231a4aa3 100644 --- a/samples/AntiforgerySample/project.json +++ b/samples/AntiforgerySample/project.json @@ -16,9 +16,6 @@ "frameworks": { "net451": {}, "netcoreapp1.0": { - "imports": [ - "dnxcore50" - ], "dependencies": { "Microsoft.NETCore.App": { "version": "1.0.0-*", @@ -34,10 +31,7 @@ ] }, "tools": { - "Microsoft.AspNetCore.Server.IISIntegration.Tools": { - "version": "1.0.0-*", - "imports": "portable-net45+wp80+win8+wpa81+dnxcore50" - } + "Microsoft.AspNetCore.Server.IISIntegration.Tools": "1.0.0-*" }, "scripts": { "postpublish": "dotnet publish-iis --publish-folder %publish:OutputPath% --framework %publish:FullTargetFramework%" From f0fc335cc0adb527660a9111e965754a4692e5c8 Mon Sep 17 00:00:00 2001 From: "N. Taylor Mullen" Date: Mon, 13 Jun 2016 15:29:57 -0700 Subject: [PATCH 137/296] Remove direct Microsoft.NETCore.Platforms dependency. - Microsoft.NETCore.App now pulls this package in. aspnet/Coherence-Signed#344 --- samples/AntiforgerySample/project.json | 1 - .../project.json | 1 - test/Microsoft.AspNetCore.Antiforgery.Test/project.json | 1 - 3 files changed, 3 deletions(-) diff --git a/samples/AntiforgerySample/project.json b/samples/AntiforgerySample/project.json index 6a231a4aa3..c985cfbf73 100644 --- a/samples/AntiforgerySample/project.json +++ b/samples/AntiforgerySample/project.json @@ -1,7 +1,6 @@ { "version": "1.0.0-*", "dependencies": { - "Microsoft.NETCore.Platforms": "1.0.1-*", "Microsoft.AspNetCore.Antiforgery": "1.0.0-*", "Microsoft.AspNetCore.Http.Abstractions": "1.0.0-*", "Microsoft.AspNetCore.Http.Extensions": "1.0.0-*", diff --git a/test/Microsoft.AspNetCore.Antiforgery.FunctionalTests/project.json b/test/Microsoft.AspNetCore.Antiforgery.FunctionalTests/project.json index f7d1b59a8a..697584f296 100644 --- a/test/Microsoft.AspNetCore.Antiforgery.FunctionalTests/project.json +++ b/test/Microsoft.AspNetCore.Antiforgery.FunctionalTests/project.json @@ -1,7 +1,6 @@ { "dependencies": { "dotnet-test-xunit": "1.0.0-*", - "Microsoft.NETCore.Platforms": "1.0.1-*", "AntiforgerySample": "1.0.0-*", "Microsoft.AspNetCore.TestHost": "1.0.0-*", "Microsoft.AspNetCore.Testing": "1.0.0-*" diff --git a/test/Microsoft.AspNetCore.Antiforgery.Test/project.json b/test/Microsoft.AspNetCore.Antiforgery.Test/project.json index 3e742a23c2..d08777394a 100644 --- a/test/Microsoft.AspNetCore.Antiforgery.Test/project.json +++ b/test/Microsoft.AspNetCore.Antiforgery.Test/project.json @@ -5,7 +5,6 @@ }, "dependencies": { "dotnet-test-xunit": "1.0.0-*", - "Microsoft.NETCore.Platforms": "1.0.1-*", "Microsoft.AspNetCore.Antiforgery": "1.0.0-*", "Microsoft.AspNetCore.Http": "1.0.0-*", "Microsoft.AspNetCore.Testing": "1.0.0-*", From c790b9f9519983d0b87033a78a4edf3585581459 Mon Sep 17 00:00:00 2001 From: Pranav K Date: Tue, 14 Jun 2016 16:23:07 -0700 Subject: [PATCH 138/296] Updating to release. --- NuGet.config | 2 +- build.ps1 | 2 +- build.sh | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/NuGet.config b/NuGet.config index 52bf414192..71b9724a09 100644 --- a/NuGet.config +++ b/NuGet.config @@ -1,7 +1,7 @@ - + diff --git a/build.ps1 b/build.ps1 index 8f2f99691a..cf8bff13bb 100644 --- a/build.ps1 +++ b/build.ps1 @@ -33,7 +33,7 @@ cd $PSScriptRoot $repoFolder = $PSScriptRoot $env:REPO_FOLDER = $repoFolder -$koreBuildZip="https://github.com/aspnet/KoreBuild/archive/dev.zip" +$koreBuildZip="https://github.com/aspnet/KoreBuild/archive/release.zip" if ($env:KOREBUILD_ZIP) { $koreBuildZip=$env:KOREBUILD_ZIP diff --git a/build.sh b/build.sh index f4208100eb..f88fe4052e 100755 --- a/build.sh +++ b/build.sh @@ -2,7 +2,7 @@ repoFolder="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" cd $repoFolder -koreBuildZip="https://github.com/aspnet/KoreBuild/archive/dev.zip" +koreBuildZip="https://github.com/aspnet/KoreBuild/archive/release.zip" if [ ! -z $KOREBUILD_ZIP ]; then koreBuildZip=$KOREBUILD_ZIP fi From 69bf6ea08d7f9fe8d0c60d8b655fd3db12195010 Mon Sep 17 00:00:00 2001 From: jacalvar Date: Mon, 13 Jun 2016 14:24:20 -0700 Subject: [PATCH 139/296] Update Json.NET to 9.0.1 --- samples/AntiforgerySample/project.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/samples/AntiforgerySample/project.json b/samples/AntiforgerySample/project.json index c985cfbf73..371c7c2a82 100644 --- a/samples/AntiforgerySample/project.json +++ b/samples/AntiforgerySample/project.json @@ -7,7 +7,7 @@ "Microsoft.AspNetCore.Server.IISIntegration": "1.0.0-*", "Microsoft.AspNetCore.Server.Kestrel": "1.0.0-*", "Microsoft.AspNetCore.StaticFiles": "1.0.0-*", - "Newtonsoft.Json": "9.0.1-beta1" + "Newtonsoft.Json": "9.0.1" }, "buildOptions": { "emitEntryPoint": true From dad4522ef3c240b3ef6f13d515b7cccf26e8dd8b Mon Sep 17 00:00:00 2001 From: Pranav K Date: Thu, 16 Jun 2016 10:17:28 -0700 Subject: [PATCH 140/296] Updating to dev versions --- samples/AntiforgerySample/project.json | 14 +++++++------- src/Microsoft.AspNetCore.Antiforgery/project.json | 10 +++++----- .../project.json | 6 +++--- .../project.json | 12 ++++++------ 4 files changed, 21 insertions(+), 21 deletions(-) diff --git a/samples/AntiforgerySample/project.json b/samples/AntiforgerySample/project.json index 371c7c2a82..5111cd45d8 100644 --- a/samples/AntiforgerySample/project.json +++ b/samples/AntiforgerySample/project.json @@ -1,12 +1,12 @@ { - "version": "1.0.0-*", + "version": "1.1.0-*", "dependencies": { - "Microsoft.AspNetCore.Antiforgery": "1.0.0-*", - "Microsoft.AspNetCore.Http.Abstractions": "1.0.0-*", - "Microsoft.AspNetCore.Http.Extensions": "1.0.0-*", - "Microsoft.AspNetCore.Server.IISIntegration": "1.0.0-*", - "Microsoft.AspNetCore.Server.Kestrel": "1.0.0-*", - "Microsoft.AspNetCore.StaticFiles": "1.0.0-*", + "Microsoft.AspNetCore.Antiforgery": "1.1.0-*", + "Microsoft.AspNetCore.Http.Abstractions": "1.1.0-*", + "Microsoft.AspNetCore.Http.Extensions": "1.1.0-*", + "Microsoft.AspNetCore.Server.IISIntegration": "1.1.0-*", + "Microsoft.AspNetCore.Server.Kestrel": "1.1.0-*", + "Microsoft.AspNetCore.StaticFiles": "1.1.0-*", "Newtonsoft.Json": "9.0.1" }, "buildOptions": { diff --git a/src/Microsoft.AspNetCore.Antiforgery/project.json b/src/Microsoft.AspNetCore.Antiforgery/project.json index b5a59d28df..aca798f236 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/project.json +++ b/src/Microsoft.AspNetCore.Antiforgery/project.json @@ -1,6 +1,6 @@ { "description": "An antiforgery system for ASP.NET Core designed to generate and validate tokens to prevent Cross-Site Request Forgery attacks.", - "version": "1.0.0-*", + "version": "1.1.0-*", "buildOptions": { "warningsAsErrors": true, "keyFile": "../../tools/Key.snk", @@ -20,10 +20,10 @@ ] }, "dependencies": { - "Microsoft.AspNetCore.DataProtection": "1.0.0-*", - "Microsoft.AspNetCore.Http.Abstractions": "1.0.0-*", - "Microsoft.AspNetCore.WebUtilities": "1.0.0-*", - "Microsoft.Extensions.ObjectPool": "1.0.0-*" + "Microsoft.AspNetCore.DataProtection": "1.1.0-*", + "Microsoft.AspNetCore.Http.Abstractions": "1.1.0-*", + "Microsoft.AspNetCore.WebUtilities": "1.1.0-*", + "Microsoft.Extensions.ObjectPool": "1.1.0-*" }, "frameworks": { "netstandard1.3": {}, diff --git a/test/Microsoft.AspNetCore.Antiforgery.FunctionalTests/project.json b/test/Microsoft.AspNetCore.Antiforgery.FunctionalTests/project.json index 697584f296..7cabf480a7 100644 --- a/test/Microsoft.AspNetCore.Antiforgery.FunctionalTests/project.json +++ b/test/Microsoft.AspNetCore.Antiforgery.FunctionalTests/project.json @@ -1,9 +1,9 @@ { "dependencies": { "dotnet-test-xunit": "1.0.0-*", - "AntiforgerySample": "1.0.0-*", - "Microsoft.AspNetCore.TestHost": "1.0.0-*", - "Microsoft.AspNetCore.Testing": "1.0.0-*" + "AntiforgerySample": "1.1.0-*", + "Microsoft.AspNetCore.TestHost": "1.1.0-*", + "Microsoft.AspNetCore.Testing": "1.1.0-*" }, "testRunner": "xunit", "frameworks": { diff --git a/test/Microsoft.AspNetCore.Antiforgery.Test/project.json b/test/Microsoft.AspNetCore.Antiforgery.Test/project.json index d08777394a..be7721fa2a 100644 --- a/test/Microsoft.AspNetCore.Antiforgery.Test/project.json +++ b/test/Microsoft.AspNetCore.Antiforgery.Test/project.json @@ -5,12 +5,12 @@ }, "dependencies": { "dotnet-test-xunit": "1.0.0-*", - "Microsoft.AspNetCore.Antiforgery": "1.0.0-*", - "Microsoft.AspNetCore.Http": "1.0.0-*", - "Microsoft.AspNetCore.Testing": "1.0.0-*", - "Microsoft.Extensions.DependencyInjection": "1.0.0-*", - "Microsoft.Extensions.Logging": "1.0.0-*", - "Microsoft.Extensions.WebEncoders": "1.0.0-*", + "Microsoft.AspNetCore.Antiforgery": "1.1.0-*", + "Microsoft.AspNetCore.Http": "1.1.0-*", + "Microsoft.AspNetCore.Testing": "1.1.0-*", + "Microsoft.Extensions.DependencyInjection": "1.1.0-*", + "Microsoft.Extensions.Logging": "1.1.0-*", + "Microsoft.Extensions.WebEncoders": "1.1.0-*", "xunit": "2.1.0-*" }, "testRunner": "xunit", From b4822f90af15b94315ac6bef04d828e434afd97d Mon Sep 17 00:00:00 2001 From: Pranav K Date: Mon, 27 Jun 2016 13:50:14 -0700 Subject: [PATCH 141/296] Updating NuGet.config --- NuGet.config | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/NuGet.config b/NuGet.config index 71b9724a09..adbb3c1710 100644 --- a/NuGet.config +++ b/NuGet.config @@ -1,7 +1,8 @@ - + + - + \ No newline at end of file From 646cb6ea21a95abcb8d2d90f42afb7decf631ad1 Mon Sep 17 00:00:00 2001 From: Pranav K Date: Mon, 27 Jun 2016 13:51:09 -0700 Subject: [PATCH 142/296] Updating json files to pin versions and build files to pin KoreBuild --- build.ps1 | 2 +- build.sh | 2 +- samples/AntiforgerySample/project.json | 14 ++++++------- .../project.json | 10 +++++----- .../project.json | 12 +++++------ .../project.json | 20 +++++++++---------- 6 files changed, 30 insertions(+), 30 deletions(-) diff --git a/build.ps1 b/build.ps1 index cf8bff13bb..6d49c4dccd 100644 --- a/build.ps1 +++ b/build.ps1 @@ -33,7 +33,7 @@ cd $PSScriptRoot $repoFolder = $PSScriptRoot $env:REPO_FOLDER = $repoFolder -$koreBuildZip="https://github.com/aspnet/KoreBuild/archive/release.zip" +$koreBuildZip="https://github.com/aspnet/KoreBuild/archive/1.0.0.zip" if ($env:KOREBUILD_ZIP) { $koreBuildZip=$env:KOREBUILD_ZIP diff --git a/build.sh b/build.sh index f88fe4052e..a55d3ebc12 100755 --- a/build.sh +++ b/build.sh @@ -2,7 +2,7 @@ repoFolder="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" cd $repoFolder -koreBuildZip="https://github.com/aspnet/KoreBuild/archive/release.zip" +koreBuildZip="https://github.com/aspnet/KoreBuild/archive/1.0.0.zip" if [ ! -z $KOREBUILD_ZIP ]; then koreBuildZip=$KOREBUILD_ZIP fi diff --git a/samples/AntiforgerySample/project.json b/samples/AntiforgerySample/project.json index 371c7c2a82..0db978e1aa 100644 --- a/samples/AntiforgerySample/project.json +++ b/samples/AntiforgerySample/project.json @@ -1,12 +1,12 @@ { "version": "1.0.0-*", "dependencies": { - "Microsoft.AspNetCore.Antiforgery": "1.0.0-*", - "Microsoft.AspNetCore.Http.Abstractions": "1.0.0-*", - "Microsoft.AspNetCore.Http.Extensions": "1.0.0-*", - "Microsoft.AspNetCore.Server.IISIntegration": "1.0.0-*", - "Microsoft.AspNetCore.Server.Kestrel": "1.0.0-*", - "Microsoft.AspNetCore.StaticFiles": "1.0.0-*", + "Microsoft.AspNetCore.Antiforgery": "1.0.0", + "Microsoft.AspNetCore.Http.Abstractions": "1.0.0", + "Microsoft.AspNetCore.Http.Extensions": "1.0.0", + "Microsoft.AspNetCore.Server.IISIntegration": "1.0.0", + "Microsoft.AspNetCore.Server.Kestrel": "1.0.0", + "Microsoft.AspNetCore.StaticFiles": "1.0.0", "Newtonsoft.Json": "9.0.1" }, "buildOptions": { @@ -17,7 +17,7 @@ "netcoreapp1.0": { "dependencies": { "Microsoft.NETCore.App": { - "version": "1.0.0-*", + "version": "1.0.0", "type": "platform" } } diff --git a/src/Microsoft.AspNetCore.Antiforgery/project.json b/src/Microsoft.AspNetCore.Antiforgery/project.json index b5a59d28df..8895e4786f 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/project.json +++ b/src/Microsoft.AspNetCore.Antiforgery/project.json @@ -1,6 +1,6 @@ { "description": "An antiforgery system for ASP.NET Core designed to generate and validate tokens to prevent Cross-Site Request Forgery attacks.", - "version": "1.0.0-*", + "version": "1.0.0", "buildOptions": { "warningsAsErrors": true, "keyFile": "../../tools/Key.snk", @@ -20,10 +20,10 @@ ] }, "dependencies": { - "Microsoft.AspNetCore.DataProtection": "1.0.0-*", - "Microsoft.AspNetCore.Http.Abstractions": "1.0.0-*", - "Microsoft.AspNetCore.WebUtilities": "1.0.0-*", - "Microsoft.Extensions.ObjectPool": "1.0.0-*" + "Microsoft.AspNetCore.DataProtection": "1.0.0", + "Microsoft.AspNetCore.Http.Abstractions": "1.0.0", + "Microsoft.AspNetCore.WebUtilities": "1.0.0", + "Microsoft.Extensions.ObjectPool": "1.0.0" }, "frameworks": { "netstandard1.3": {}, diff --git a/test/Microsoft.AspNetCore.Antiforgery.FunctionalTests/project.json b/test/Microsoft.AspNetCore.Antiforgery.FunctionalTests/project.json index 697584f296..af7e15fbd2 100644 --- a/test/Microsoft.AspNetCore.Antiforgery.FunctionalTests/project.json +++ b/test/Microsoft.AspNetCore.Antiforgery.FunctionalTests/project.json @@ -1,21 +1,21 @@ { "dependencies": { - "dotnet-test-xunit": "1.0.0-*", + "dotnet-test-xunit": "1.0.0-rc3-000000-00", "AntiforgerySample": "1.0.0-*", - "Microsoft.AspNetCore.TestHost": "1.0.0-*", - "Microsoft.AspNetCore.Testing": "1.0.0-*" + "Microsoft.AspNetCore.TestHost": "1.0.0", + "Microsoft.AspNetCore.Testing": "1.0.0-rtm-21431" }, "testRunner": "xunit", "frameworks": { "netcoreapp1.0": { "dependencies": { "Microsoft.NETCore.App": { - "version": "1.0.0-*", + "version": "1.0.0", "type": "platform" }, "moq.netcore": "4.4.0-beta8", - "System.Net.Http": "4.1.0-*", - "System.Diagnostics.Process": "4.1.0-*" + "System.Net.Http": "4.1.0", + "System.Diagnostics.Process": "4.1.0" }, "imports": [ "dnxcore50", diff --git a/test/Microsoft.AspNetCore.Antiforgery.Test/project.json b/test/Microsoft.AspNetCore.Antiforgery.Test/project.json index d08777394a..e01cf5f848 100644 --- a/test/Microsoft.AspNetCore.Antiforgery.Test/project.json +++ b/test/Microsoft.AspNetCore.Antiforgery.Test/project.json @@ -4,13 +4,13 @@ "keyFile": "../../tools/Key.snk" }, "dependencies": { - "dotnet-test-xunit": "1.0.0-*", - "Microsoft.AspNetCore.Antiforgery": "1.0.0-*", - "Microsoft.AspNetCore.Http": "1.0.0-*", - "Microsoft.AspNetCore.Testing": "1.0.0-*", - "Microsoft.Extensions.DependencyInjection": "1.0.0-*", - "Microsoft.Extensions.Logging": "1.0.0-*", - "Microsoft.Extensions.WebEncoders": "1.0.0-*", + "dotnet-test-xunit": "1.0.0-rc3-000000-00", + "Microsoft.AspNetCore.Antiforgery": "1.0.0", + "Microsoft.AspNetCore.Http": "1.0.0", + "Microsoft.AspNetCore.Testing": "1.0.0-rtm-21431", + "Microsoft.Extensions.DependencyInjection": "1.0.0", + "Microsoft.Extensions.Logging": "1.0.0", + "Microsoft.Extensions.WebEncoders": "1.0.0", "xunit": "2.1.0-*" }, "testRunner": "xunit", @@ -18,12 +18,12 @@ "netcoreapp1.0": { "dependencies": { "Microsoft.NETCore.App": { - "version": "1.0.0-*", + "version": "1.0.0", "type": "platform" }, "moq.netcore": "4.4.0-beta8", - "System.Diagnostics.Process": "4.1.0-*", - "System.Diagnostics.TraceSource": "4.0.0-*" + "System.Diagnostics.Process": "4.1.0", + "System.Diagnostics.TraceSource": "4.0.0" }, "imports": [ "dnxcore50", From 5c04f0a8313a890fe2e7bb3d1d27fe98e5a9f8f5 Mon Sep 17 00:00:00 2001 From: Chris Date: Tue, 28 Jun 2016 14:42:04 -0700 Subject: [PATCH 143/296] Use Angular lib instead of angular map file in sample (#92) --- samples/AntiforgerySample/wwwroot/Index.html | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/samples/AntiforgerySample/wwwroot/Index.html b/samples/AntiforgerySample/wwwroot/Index.html index ca705a4666..8d130b34c2 100644 --- a/samples/AntiforgerySample/wwwroot/Index.html +++ b/samples/AntiforgerySample/wwwroot/Index.html @@ -38,10 +38,10 @@ - + - \ No newline at end of file + From d529378a4601d4f5a2da7399d953dd904a619850 Mon Sep 17 00:00:00 2001 From: Pranav K Date: Wed, 29 Jun 2016 12:32:06 -0700 Subject: [PATCH 144/296] Updating to RTM builds of dotnet-test-xunit and Moq --- .../AntiforgerySampleTest.cs | 1 - .../project.json | 17 +++++------------ .../DefaultAntiforgeryTokenStoreTest.cs | 1 - .../project.json | 16 ++++------------ 4 files changed, 9 insertions(+), 26 deletions(-) diff --git a/test/Microsoft.AspNetCore.Antiforgery.FunctionalTests/AntiforgerySampleTest.cs b/test/Microsoft.AspNetCore.Antiforgery.FunctionalTests/AntiforgerySampleTest.cs index 9fd2a497b9..d49d8df723 100644 --- a/test/Microsoft.AspNetCore.Antiforgery.FunctionalTests/AntiforgerySampleTest.cs +++ b/test/Microsoft.AspNetCore.Antiforgery.FunctionalTests/AntiforgerySampleTest.cs @@ -1,7 +1,6 @@ // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. -using System; using System.Collections.Generic; using System.Linq; using System.Net; diff --git a/test/Microsoft.AspNetCore.Antiforgery.FunctionalTests/project.json b/test/Microsoft.AspNetCore.Antiforgery.FunctionalTests/project.json index 7cabf480a7..286e29b607 100644 --- a/test/Microsoft.AspNetCore.Antiforgery.FunctionalTests/project.json +++ b/test/Microsoft.AspNetCore.Antiforgery.FunctionalTests/project.json @@ -1,9 +1,10 @@ { "dependencies": { - "dotnet-test-xunit": "1.0.0-*", + "dotnet-test-xunit": "2.2.0-*", "AntiforgerySample": "1.1.0-*", "Microsoft.AspNetCore.TestHost": "1.1.0-*", - "Microsoft.AspNetCore.Testing": "1.1.0-*" + "Moq": "4.6.25-*", + "xunit": "2.2.0-*" }, "testRunner": "xunit", "frameworks": { @@ -13,19 +14,11 @@ "version": "1.0.0-*", "type": "platform" }, - "moq.netcore": "4.4.0-beta8", - "System.Net.Http": "4.1.0-*", - "System.Diagnostics.Process": "4.1.0-*" + "System.Net.Http": "4.1.0-*" }, - "imports": [ - "dnxcore50", - "portable-net451+win8" - ] + "imports": "dotnet5.4" }, "net451": { - "dependencies": { - "Moq": "4.2.1312.1622" - }, "frameworkAssemblies": { "System.Net.Http": "" } diff --git a/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTokenStoreTest.cs b/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTokenStoreTest.cs index 09c27585fe..adf466aa05 100644 --- a/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTokenStoreTest.cs +++ b/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTokenStoreTest.cs @@ -3,7 +3,6 @@ using System; using System.Collections.Generic; -using System.Threading; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.Internal; diff --git a/test/Microsoft.AspNetCore.Antiforgery.Test/project.json b/test/Microsoft.AspNetCore.Antiforgery.Test/project.json index be7721fa2a..f86077f3c1 100644 --- a/test/Microsoft.AspNetCore.Antiforgery.Test/project.json +++ b/test/Microsoft.AspNetCore.Antiforgery.Test/project.json @@ -4,14 +4,15 @@ "keyFile": "../../tools/Key.snk" }, "dependencies": { - "dotnet-test-xunit": "1.0.0-*", + "dotnet-test-xunit": "2.2.0-*", "Microsoft.AspNetCore.Antiforgery": "1.1.0-*", "Microsoft.AspNetCore.Http": "1.1.0-*", "Microsoft.AspNetCore.Testing": "1.1.0-*", "Microsoft.Extensions.DependencyInjection": "1.1.0-*", "Microsoft.Extensions.Logging": "1.1.0-*", "Microsoft.Extensions.WebEncoders": "1.1.0-*", - "xunit": "2.1.0-*" + "Moq": "4.6.25-*", + "xunit": "2.2.0-*" }, "testRunner": "xunit", "frameworks": { @@ -21,22 +22,13 @@ "version": "1.0.0-*", "type": "platform" }, - "moq.netcore": "4.4.0-beta8", - "System.Diagnostics.Process": "4.1.0-*", "System.Diagnostics.TraceSource": "4.0.0-*" }, - "imports": [ - "dnxcore50", - "portable-net451+win8" - ] + "imports": "dotnet5.4" }, "net451": { "frameworkAssemblies": { "System.Threading.Tasks": "" - }, - "dependencies": { - "Moq": "4.2.1312.1622", - "xunit.runner.console": "2.1.0" } } } From e9f26ec4b69d7419dc65dd70bfcb0cf6e9880ddb Mon Sep 17 00:00:00 2001 From: Doug Bunting Date: Wed, 6 Jul 2016 21:43:13 -0700 Subject: [PATCH 145/296] One build to rule them all - well, at least VS and command-line builds will share output - part of aspnet/Coherence-Signed#277 --- samples/AntiforgerySample/AntiforgerySample.xproj | 4 ++-- .../Microsoft.AspNetCore.Antiforgery.xproj | 4 ++-- .../Microsoft.AspNetCore.Antiforgery.FunctionalTests.xproj | 4 ++-- .../Microsoft.AspNetCore.Antiforgery.Test.xproj | 4 ++-- 4 files changed, 8 insertions(+), 8 deletions(-) diff --git a/samples/AntiforgerySample/AntiforgerySample.xproj b/samples/AntiforgerySample/AntiforgerySample.xproj index 254d0c3d03..df07bd9b50 100644 --- a/samples/AntiforgerySample/AntiforgerySample.xproj +++ b/samples/AntiforgerySample/AntiforgerySample.xproj @@ -7,8 +7,8 @@ af9e0784-5edb-494f-b46c-1a8da785c49c - ..\..\artifacts\obj\$(MSBuildProjectName) - ..\..\artifacts\bin\ + .\obj + .\bin\ 2.0 diff --git a/src/Microsoft.AspNetCore.Antiforgery/Microsoft.AspNetCore.Antiforgery.xproj b/src/Microsoft.AspNetCore.Antiforgery/Microsoft.AspNetCore.Antiforgery.xproj index cfd5f9890c..3799efa7b6 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/Microsoft.AspNetCore.Antiforgery.xproj +++ b/src/Microsoft.AspNetCore.Antiforgery/Microsoft.AspNetCore.Antiforgery.xproj @@ -7,8 +7,8 @@ 46fb03fb-7a44-4106-bdde-d6f5417544ab - ..\..\artifacts\obj\$(MSBuildProjectName) - ..\..\artifacts\bin\ + .\obj + .\bin\ 2.0 diff --git a/test/Microsoft.AspNetCore.Antiforgery.FunctionalTests/Microsoft.AspNetCore.Antiforgery.FunctionalTests.xproj b/test/Microsoft.AspNetCore.Antiforgery.FunctionalTests/Microsoft.AspNetCore.Antiforgery.FunctionalTests.xproj index 8ecb47ec07..1901f0cc82 100644 --- a/test/Microsoft.AspNetCore.Antiforgery.FunctionalTests/Microsoft.AspNetCore.Antiforgery.FunctionalTests.xproj +++ b/test/Microsoft.AspNetCore.Antiforgery.FunctionalTests/Microsoft.AspNetCore.Antiforgery.FunctionalTests.xproj @@ -7,8 +7,8 @@ 8b288810-5a96-4af5-9836-8ba2d2953203 - ..\..\artifacts\obj\$(MSBuildProjectName) - ..\..\artifacts\bin\ + .\obj + .\bin\ 2.0 diff --git a/test/Microsoft.AspNetCore.Antiforgery.Test/Microsoft.AspNetCore.Antiforgery.Test.xproj b/test/Microsoft.AspNetCore.Antiforgery.Test/Microsoft.AspNetCore.Antiforgery.Test.xproj index b016f46aac..87bf4fd855 100644 --- a/test/Microsoft.AspNetCore.Antiforgery.Test/Microsoft.AspNetCore.Antiforgery.Test.xproj +++ b/test/Microsoft.AspNetCore.Antiforgery.Test/Microsoft.AspNetCore.Antiforgery.Test.xproj @@ -7,8 +7,8 @@ 415e83f8-6002-47e4-aa8e-cd5169c06f28 - ..\..\artifacts\obj\$(MSBuildProjectName) - ..\..\artifacts\bin\ + .\obj + .\bin\ 2.0 From 571fddbd1d71ab1f4e81481ff176928636a1f123 Mon Sep 17 00:00:00 2001 From: Pranav K Date: Tue, 19 Jul 2016 11:13:05 -0700 Subject: [PATCH 146/296] Pin the version of dotnet-test-xunit to 1.0.0-rc3-00000-01 --- .../project.json | 2 +- test/Microsoft.AspNetCore.Antiforgery.Test/project.json | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/test/Microsoft.AspNetCore.Antiforgery.FunctionalTests/project.json b/test/Microsoft.AspNetCore.Antiforgery.FunctionalTests/project.json index af7e15fbd2..3fa1f1cd07 100644 --- a/test/Microsoft.AspNetCore.Antiforgery.FunctionalTests/project.json +++ b/test/Microsoft.AspNetCore.Antiforgery.FunctionalTests/project.json @@ -1,6 +1,6 @@ { "dependencies": { - "dotnet-test-xunit": "1.0.0-rc3-000000-00", + "dotnet-test-xunit": "1.0.0-rc3-000000-01", "AntiforgerySample": "1.0.0-*", "Microsoft.AspNetCore.TestHost": "1.0.0", "Microsoft.AspNetCore.Testing": "1.0.0-rtm-21431" diff --git a/test/Microsoft.AspNetCore.Antiforgery.Test/project.json b/test/Microsoft.AspNetCore.Antiforgery.Test/project.json index e01cf5f848..3e00cf48ac 100644 --- a/test/Microsoft.AspNetCore.Antiforgery.Test/project.json +++ b/test/Microsoft.AspNetCore.Antiforgery.Test/project.json @@ -4,7 +4,7 @@ "keyFile": "../../tools/Key.snk" }, "dependencies": { - "dotnet-test-xunit": "1.0.0-rc3-000000-00", + "dotnet-test-xunit": "1.0.0-rc3-000000-01", "Microsoft.AspNetCore.Antiforgery": "1.0.0", "Microsoft.AspNetCore.Http": "1.0.0", "Microsoft.AspNetCore.Testing": "1.0.0-rtm-21431", From 0de846182b3bcdd8b4af7d4af3febe8adc8baec2 Mon Sep 17 00:00:00 2001 From: BrennanConroy Date: Tue, 2 Aug 2016 13:15:53 -0700 Subject: [PATCH 147/296] Update .travis.yml --- .travis.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.travis.yml b/.travis.yml index 0f6e51b48a..32307f33df 100644 --- a/.travis.yml +++ b/.travis.yml @@ -23,7 +23,7 @@ branches: - dev - /^(.*\/)?ci-.*$/ before_install: - - if test "$TRAVIS_OS_NAME" == "osx"; then brew update; brew install openssl; brew link --force openssl; fi + - if test "$TRAVIS_OS_NAME" == "osx"; then brew update; brew install openssl; ln -s /usr/local/opt/openssl/lib/libcrypto.1.0.0.dylib /usr/local/lib/; ln -s /usr/local/opt/openssl/lib/libssl.1.0.0.dylib /usr/local/lib/; fi script: - ./build.sh --quiet verify notifications: @@ -31,4 +31,4 @@ notifications: secure: "dzKsW/YJVie2UeYKMlKFA9dcHv0WpF4IKd7z/yEhV96eB5e2Pls+vtQFUP86Wg/fcqeLHAmb0GazXnomPg2cX13ihz+mF0hCvA58UTczNpwwfTZd7VHQe9Ti93Zoo49HkTFBbIDMns9eUxhcEo4T4lC85dG4ZRz7v8X6/Nlr71PMIGYI29Uyur/1oPrnNI7DBweOY4Z1Xhl5cfaSPd945VM8QPHeM494XGmgldGpIZs+LjZbA8S3xxB0YaxpAwGKO4gWSXL2fP4y1z5rFEY1JZamPaedA3dICVi3BVDjJ4l3sn3fEBxOAv8QwjHvSu0xWK/MAIX/SmY7ScgIND+UMjGFTaeZLYN18hJDm+a4mAx/tPaqsOGAKm9F/aVQAzP0g4z+VAVDz1iqxDWe+x/cK4DPjUbLXpP6Y6jtrVES/TkKNuLNA/NUOp+vDPXieDaQAmeU2l6M2el1PscQPtla6KIS1oDDiuHeWC/b4suCAJVsads25y7KyncmmwYE1Tgh1sUJa+Vk9c/hxiIuDJQUWxmi/4BGjDYO29y60jc2niimzvQ3sV2x+Rh81zJaLWXNYdIgugzQpe4nG8wQDbLuEAlfINBt7cIxw3MK3ov4MV5MVRaDVMEm0A5yIN9Mz83USPkuXxfhGtOo6YU1Ny/D2bjc9LI7lGHbjQtFlJa6U6c=" on_success: always on_failure: always - on_start: always \ No newline at end of file + on_start: always From b086b5b1653706ace79defd3fa26d35612ba5879 Mon Sep 17 00:00:00 2001 From: Pranav K Date: Mon, 8 Aug 2016 12:22:35 -0700 Subject: [PATCH 148/296] Updating to Moq \ Castle.Core that does not require imports --- .../project.json | 5 ++--- test/Microsoft.AspNetCore.Antiforgery.Test/project.json | 5 ++--- 2 files changed, 4 insertions(+), 6 deletions(-) diff --git a/test/Microsoft.AspNetCore.Antiforgery.FunctionalTests/project.json b/test/Microsoft.AspNetCore.Antiforgery.FunctionalTests/project.json index 286e29b607..fe3193563b 100644 --- a/test/Microsoft.AspNetCore.Antiforgery.FunctionalTests/project.json +++ b/test/Microsoft.AspNetCore.Antiforgery.FunctionalTests/project.json @@ -3,7 +3,7 @@ "dotnet-test-xunit": "2.2.0-*", "AntiforgerySample": "1.1.0-*", "Microsoft.AspNetCore.TestHost": "1.1.0-*", - "Moq": "4.6.25-*", + "Moq": "4.6.36-*", "xunit": "2.2.0-*" }, "testRunner": "xunit", @@ -15,8 +15,7 @@ "type": "platform" }, "System.Net.Http": "4.1.0-*" - }, - "imports": "dotnet5.4" + } }, "net451": { "frameworkAssemblies": { diff --git a/test/Microsoft.AspNetCore.Antiforgery.Test/project.json b/test/Microsoft.AspNetCore.Antiforgery.Test/project.json index f86077f3c1..c0654a5ad4 100644 --- a/test/Microsoft.AspNetCore.Antiforgery.Test/project.json +++ b/test/Microsoft.AspNetCore.Antiforgery.Test/project.json @@ -11,7 +11,7 @@ "Microsoft.Extensions.DependencyInjection": "1.1.0-*", "Microsoft.Extensions.Logging": "1.1.0-*", "Microsoft.Extensions.WebEncoders": "1.1.0-*", - "Moq": "4.6.25-*", + "Moq": "4.6.36-*", "xunit": "2.2.0-*" }, "testRunner": "xunit", @@ -23,8 +23,7 @@ "type": "platform" }, "System.Diagnostics.TraceSource": "4.0.0-*" - }, - "imports": "dotnet5.4" + } }, "net451": { "frameworkAssemblies": { From 0bdfef691377e84ee2f37ffc8183523c86763223 Mon Sep 17 00:00:00 2001 From: Pranav K Date: Tue, 9 Aug 2016 14:55:51 -0700 Subject: [PATCH 149/296] Switching to dotnet.myget.org feed --- NuGet.config | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/NuGet.config b/NuGet.config index 52bf414192..0fd623ffdd 100644 --- a/NuGet.config +++ b/NuGet.config @@ -1,7 +1,7 @@ - + - + From 761d0e6290e85ffcbde2780833606dc7935821f0 Mon Sep 17 00:00:00 2001 From: Pranav K Date: Fri, 12 Aug 2016 10:15:32 -0700 Subject: [PATCH 150/296] Updating to dotnet.myget.org --- NuGet.config | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/NuGet.config b/NuGet.config index adbb3c1710..9f4165645a 100644 --- a/NuGet.config +++ b/NuGet.config @@ -2,7 +2,7 @@ - + \ No newline at end of file From a44275b732068f8488155c18107145739212baa9 Mon Sep 17 00:00:00 2001 From: "N. Taylor Mullen" Date: Wed, 17 Aug 2016 12:23:57 -0700 Subject: [PATCH 151/296] Update projects to 1.0.1. --- samples/AntiforgerySample/project.json | 2 +- src/Microsoft.AspNetCore.Antiforgery/project.json | 2 +- test/Microsoft.AspNetCore.Antiforgery.Test/project.json | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/samples/AntiforgerySample/project.json b/samples/AntiforgerySample/project.json index 0db978e1aa..967f769d3b 100644 --- a/samples/AntiforgerySample/project.json +++ b/samples/AntiforgerySample/project.json @@ -1,7 +1,7 @@ { "version": "1.0.0-*", "dependencies": { - "Microsoft.AspNetCore.Antiforgery": "1.0.0", + "Microsoft.AspNetCore.Antiforgery": "1.0.1", "Microsoft.AspNetCore.Http.Abstractions": "1.0.0", "Microsoft.AspNetCore.Http.Extensions": "1.0.0", "Microsoft.AspNetCore.Server.IISIntegration": "1.0.0", diff --git a/src/Microsoft.AspNetCore.Antiforgery/project.json b/src/Microsoft.AspNetCore.Antiforgery/project.json index 8895e4786f..8cd3de0097 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/project.json +++ b/src/Microsoft.AspNetCore.Antiforgery/project.json @@ -1,6 +1,6 @@ { "description": "An antiforgery system for ASP.NET Core designed to generate and validate tokens to prevent Cross-Site Request Forgery attacks.", - "version": "1.0.0", + "version": "1.0.1", "buildOptions": { "warningsAsErrors": true, "keyFile": "../../tools/Key.snk", diff --git a/test/Microsoft.AspNetCore.Antiforgery.Test/project.json b/test/Microsoft.AspNetCore.Antiforgery.Test/project.json index 3e00cf48ac..4f68a8e0ee 100644 --- a/test/Microsoft.AspNetCore.Antiforgery.Test/project.json +++ b/test/Microsoft.AspNetCore.Antiforgery.Test/project.json @@ -5,7 +5,7 @@ }, "dependencies": { "dotnet-test-xunit": "1.0.0-rc3-000000-01", - "Microsoft.AspNetCore.Antiforgery": "1.0.0", + "Microsoft.AspNetCore.Antiforgery": "1.0.1", "Microsoft.AspNetCore.Http": "1.0.0", "Microsoft.AspNetCore.Testing": "1.0.0-rtm-21431", "Microsoft.Extensions.DependencyInjection": "1.0.0", From cdf84eb87ea61722ef4ba3d6ecd62e30c4891031 Mon Sep 17 00:00:00 2001 From: "N. Taylor Mullen" Date: Tue, 2 Aug 2016 10:50:12 -0700 Subject: [PATCH 152/296] Change SHA256 algorithm to work on FIPS-compliant machines. #95 --- .../Internal/AntiforgeryOptionsSetup.cs | 2 +- .../AntiforgerySerializationContext.cs | 2 +- .../Internal/CryptographyAlgorithms.cs | 38 +++++++++++++++++++ 3 files changed, 40 insertions(+), 2 deletions(-) create mode 100644 src/Microsoft.AspNetCore.Antiforgery/Internal/CryptographyAlgorithms.cs diff --git a/src/Microsoft.AspNetCore.Antiforgery/Internal/AntiforgeryOptionsSetup.cs b/src/Microsoft.AspNetCore.Antiforgery/Internal/AntiforgeryOptionsSetup.cs index 1c5a3fa4b8..29c3780786 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/Internal/AntiforgeryOptionsSetup.cs +++ b/src/Microsoft.AspNetCore.Antiforgery/Internal/AntiforgeryOptionsSetup.cs @@ -28,7 +28,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal private static string ComputeCookieName(string applicationId) { - using (var sha256 = SHA256.Create()) + using (var sha256 = CryptographyAlgorithms.CreateSHA256()) { var hash = sha256.ComputeHash(Encoding.UTF8.GetBytes(applicationId)); var subHash = hash.Take(8).ToArray(); diff --git a/src/Microsoft.AspNetCore.Antiforgery/Internal/AntiforgerySerializationContext.cs b/src/Microsoft.AspNetCore.Antiforgery/Internal/AntiforgerySerializationContext.cs index 5347f6651a..6d697fa0da 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/Internal/AntiforgerySerializationContext.cs +++ b/src/Microsoft.AspNetCore.Antiforgery/Internal/AntiforgerySerializationContext.cs @@ -88,7 +88,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal { if (_sha256 == null) { - _sha256 = SHA256.Create(); + _sha256 = CryptographyAlgorithms.CreateSHA256(); } return _sha256; diff --git a/src/Microsoft.AspNetCore.Antiforgery/Internal/CryptographyAlgorithms.cs b/src/Microsoft.AspNetCore.Antiforgery/Internal/CryptographyAlgorithms.cs new file mode 100644 index 0000000000..95df639b9c --- /dev/null +++ b/src/Microsoft.AspNetCore.Antiforgery/Internal/CryptographyAlgorithms.cs @@ -0,0 +1,38 @@ +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System.Security.Cryptography; + +namespace Microsoft.AspNetCore.Antiforgery.Internal +{ + public static class CryptographyAlgorithms + { +#if NETSTANDARD1_3 + public static SHA256 CreateSHA256() + { + var sha256 = SHA256.Create(); + + return sha256; + } +#else + public static SHA256 CreateSHA256() + { + SHA256 sha256; + + try + { + sha256 = SHA256.Create(); + } + // SHA256.Create is documented to throw this exception on FIPS compliant machines. + // See: https://msdn.microsoft.com/en-us/library/z08hz7ad%28v=vs.110%29.aspx?f=255&MSPPError=-2147217396 + catch (System.Reflection.TargetInvocationException) + { + // Fallback to a FIPS compliant SHA256 algorithm. + sha256 = new SHA256CryptoServiceProvider(); + } + + return sha256; + } +#endif + } +} From c3476cf327bcadb59911c5629d39d9f911806642 Mon Sep 17 00:00:00 2001 From: Doug Bunting Date: Sat, 3 Sep 2016 22:13:14 -0700 Subject: [PATCH 153/296] Increase .travis.yml consistency between repos - aspnet/Universe#349 - minimize `dotnet` setup time; no need for caching --- .travis.yml | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/.travis.yml b/.travis.yml index 32307f33df..20ad23da42 100644 --- a/.travis.yml +++ b/.travis.yml @@ -10,6 +10,10 @@ addons: - libssl-dev - libunwind8 - zlib1g +env: + global: + - DOTNET_SKIP_FIRST_TIME_EXPERIENCE: true + - DOTNET_CLI_TELEMETRY_OPTOUT: 1 mono: - 4.0.5 os: From ad90db343c437283d809dab12f89b51116a25151 Mon Sep 17 00:00:00 2001 From: Kiran Challa Date: Thu, 1 Sep 2016 09:54:10 -0700 Subject: [PATCH 154/296] [Fixes #101] Cookie path is always / in IIS --- .../Internal/DefaultAntiforgeryTokenStore.cs | 5 ++- .../DefaultAntiforgeryTokenStoreTest.cs | 44 +++++++++++++++++-- 2 files changed, 44 insertions(+), 5 deletions(-) diff --git a/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgeryTokenStore.cs b/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgeryTokenStore.cs index 17c2e1465a..896961bb41 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgeryTokenStore.cs +++ b/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgeryTokenStore.cs @@ -69,8 +69,9 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal Debug.Assert(httpContext != null); Debug.Assert(token != null); - var options = new CookieOptions() { HttpOnly = true }; - + var options = new CookieOptions(); + options.HttpOnly = true; + options.Path = httpContext.Request.PathBase; // Note: don't use "newCookie.Secure = _options.RequireSSL;" since the default // value of newCookie.Secure is poulated out of band. if (_options.RequireSsl) diff --git a/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTokenStoreTest.cs b/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTokenStoreTest.cs index adf466aa05..c48c0c9ead 100644 --- a/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTokenStoreTest.cs +++ b/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTokenStoreTest.cs @@ -245,10 +245,13 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal bool defaultCookieSecureValue = expectedCookieSecureFlag ?? false; // pulled from config; set by ctor var cookies = new MockResponseCookieCollection(); - var mockHttpContext = new Mock(); - mockHttpContext + var httpContext = new Mock(); + httpContext .Setup(o => o.Response.Cookies) .Returns(cookies); + httpContext + .SetupGet(hc => hc.Request.PathBase) + .Returns("/"); var options = new AntiforgeryOptions() { @@ -259,7 +262,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal var tokenStore = new DefaultAntiforgeryTokenStore(new TestOptionsManager(options)); // Act - tokenStore.SaveCookieToken(mockHttpContext.Object, token); + tokenStore.SaveCookieToken(httpContext.Object, token); // Assert Assert.Equal(1, cookies.Count); @@ -270,6 +273,41 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal Assert.Equal(defaultCookieSecureValue, cookies.Options.Secure); } + [Theory] + [InlineData("/")] + [InlineData("/vdir1")] + [InlineData("/vdir1/vdir2")] + public void SaveCookieToken_SetsCookieWithApproriatePathBase(string requestPathBase) + { + // Arrange + var token = "serialized-value"; + var cookies = new MockResponseCookieCollection(); + var httpContext = new Mock(); + httpContext + .Setup(hc => hc.Response.Cookies) + .Returns(cookies); + httpContext + .SetupGet(hc => hc.Request.PathBase) + .Returns(requestPathBase); + httpContext + .SetupGet(hc => hc.Request.Path) + .Returns("/index.html"); + var options = new AntiforgeryOptions(); + options.CookieName = _cookieName; + var tokenStore = new DefaultAntiforgeryTokenStore(new TestOptionsManager(options)); + + // Act + tokenStore.SaveCookieToken(httpContext.Object, token); + + // Assert + Assert.Equal(1, cookies.Count); + Assert.NotNull(cookies); + Assert.Equal(_cookieName, cookies.Key); + Assert.Equal("serialized-value", cookies.Value); + Assert.True(cookies.Options.HttpOnly); + Assert.Equal(requestPathBase, cookies.Options.Path); + } + private HttpContext GetHttpContext(string cookieName, string cookieValue) { var cookies = new RequestCookieCollection(new Dictionary From fb8795e247bae04fb259c154d363e0bfab75fb1d Mon Sep 17 00:00:00 2001 From: Pranav K Date: Wed, 28 Sep 2016 11:49:26 -0700 Subject: [PATCH 155/296] Updating partner package versions --- samples/AntiforgerySample/project.json | 2 +- src/Microsoft.AspNetCore.Antiforgery/project.json | 3 ++- .../project.json | 7 +++---- test/Microsoft.AspNetCore.Antiforgery.Test/project.json | 4 ++-- 4 files changed, 8 insertions(+), 8 deletions(-) diff --git a/samples/AntiforgerySample/project.json b/samples/AntiforgerySample/project.json index 5111cd45d8..9c3fadf0c0 100644 --- a/samples/AntiforgerySample/project.json +++ b/samples/AntiforgerySample/project.json @@ -17,7 +17,7 @@ "netcoreapp1.0": { "dependencies": { "Microsoft.NETCore.App": { - "version": "1.0.0-*", + "version": "1.1.0-*", "type": "platform" } } diff --git a/src/Microsoft.AspNetCore.Antiforgery/project.json b/src/Microsoft.AspNetCore.Antiforgery/project.json index aca798f236..259531cafe 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/project.json +++ b/src/Microsoft.AspNetCore.Antiforgery/project.json @@ -23,7 +23,8 @@ "Microsoft.AspNetCore.DataProtection": "1.1.0-*", "Microsoft.AspNetCore.Http.Abstractions": "1.1.0-*", "Microsoft.AspNetCore.WebUtilities": "1.1.0-*", - "Microsoft.Extensions.ObjectPool": "1.1.0-*" + "Microsoft.Extensions.ObjectPool": "1.1.0-*", + "NETStandard.Library": "1.6.1-*" }, "frameworks": { "netstandard1.3": {}, diff --git a/test/Microsoft.AspNetCore.Antiforgery.FunctionalTests/project.json b/test/Microsoft.AspNetCore.Antiforgery.FunctionalTests/project.json index fe3193563b..73cfc7b4c4 100644 --- a/test/Microsoft.AspNetCore.Antiforgery.FunctionalTests/project.json +++ b/test/Microsoft.AspNetCore.Antiforgery.FunctionalTests/project.json @@ -1,7 +1,7 @@ { "dependencies": { - "dotnet-test-xunit": "2.2.0-*", "AntiforgerySample": "1.1.0-*", + "dotnet-test-xunit": "2.2.0-*", "Microsoft.AspNetCore.TestHost": "1.1.0-*", "Moq": "4.6.36-*", "xunit": "2.2.0-*" @@ -11,10 +11,9 @@ "netcoreapp1.0": { "dependencies": { "Microsoft.NETCore.App": { - "version": "1.0.0-*", + "version": "1.1.0-*", "type": "platform" - }, - "System.Net.Http": "4.1.0-*" + } } }, "net451": { diff --git a/test/Microsoft.AspNetCore.Antiforgery.Test/project.json b/test/Microsoft.AspNetCore.Antiforgery.Test/project.json index c0654a5ad4..4a1effd185 100644 --- a/test/Microsoft.AspNetCore.Antiforgery.Test/project.json +++ b/test/Microsoft.AspNetCore.Antiforgery.Test/project.json @@ -19,10 +19,10 @@ "netcoreapp1.0": { "dependencies": { "Microsoft.NETCore.App": { - "version": "1.0.0-*", + "version": "1.1.0-*", "type": "platform" }, - "System.Diagnostics.TraceSource": "4.0.0-*" + "System.Diagnostics.TraceSource": "4.3.0-*" } }, "net451": { From e191420cae95fd3e776f86ae89ab9f208cc630cd Mon Sep 17 00:00:00 2001 From: Pranav K Date: Wed, 12 Oct 2016 13:44:46 -0700 Subject: [PATCH 156/296] Updating to netcoreapp1.1 --- samples/AntiforgerySample/project.json | 2 +- .../project.json | 2 +- test/Microsoft.AspNetCore.Antiforgery.Test/project.json | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/samples/AntiforgerySample/project.json b/samples/AntiforgerySample/project.json index 9c3fadf0c0..dd24a3b97b 100644 --- a/samples/AntiforgerySample/project.json +++ b/samples/AntiforgerySample/project.json @@ -14,7 +14,7 @@ }, "frameworks": { "net451": {}, - "netcoreapp1.0": { + "netcoreapp1.1": { "dependencies": { "Microsoft.NETCore.App": { "version": "1.1.0-*", diff --git a/test/Microsoft.AspNetCore.Antiforgery.FunctionalTests/project.json b/test/Microsoft.AspNetCore.Antiforgery.FunctionalTests/project.json index 73cfc7b4c4..984fb8ddd8 100644 --- a/test/Microsoft.AspNetCore.Antiforgery.FunctionalTests/project.json +++ b/test/Microsoft.AspNetCore.Antiforgery.FunctionalTests/project.json @@ -8,7 +8,7 @@ }, "testRunner": "xunit", "frameworks": { - "netcoreapp1.0": { + "netcoreapp1.1": { "dependencies": { "Microsoft.NETCore.App": { "version": "1.1.0-*", diff --git a/test/Microsoft.AspNetCore.Antiforgery.Test/project.json b/test/Microsoft.AspNetCore.Antiforgery.Test/project.json index 4a1effd185..ac8572cba9 100644 --- a/test/Microsoft.AspNetCore.Antiforgery.Test/project.json +++ b/test/Microsoft.AspNetCore.Antiforgery.Test/project.json @@ -16,7 +16,7 @@ }, "testRunner": "xunit", "frameworks": { - "netcoreapp1.0": { + "netcoreapp1.1": { "dependencies": { "Microsoft.NETCore.App": { "version": "1.1.0-*", From 0d00259099e371776064fba71be2cdf4f800f201 Mon Sep 17 00:00:00 2001 From: Pranav K Date: Wed, 12 Oct 2016 16:07:12 -0700 Subject: [PATCH 157/296] Revert "Updating to netcoreapp1.1" This reverts commit e191420cae95fd3e776f86ae89ab9f208cc630cd. --- samples/AntiforgerySample/project.json | 2 +- .../project.json | 2 +- test/Microsoft.AspNetCore.Antiforgery.Test/project.json | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/samples/AntiforgerySample/project.json b/samples/AntiforgerySample/project.json index dd24a3b97b..9c3fadf0c0 100644 --- a/samples/AntiforgerySample/project.json +++ b/samples/AntiforgerySample/project.json @@ -14,7 +14,7 @@ }, "frameworks": { "net451": {}, - "netcoreapp1.1": { + "netcoreapp1.0": { "dependencies": { "Microsoft.NETCore.App": { "version": "1.1.0-*", diff --git a/test/Microsoft.AspNetCore.Antiforgery.FunctionalTests/project.json b/test/Microsoft.AspNetCore.Antiforgery.FunctionalTests/project.json index 984fb8ddd8..73cfc7b4c4 100644 --- a/test/Microsoft.AspNetCore.Antiforgery.FunctionalTests/project.json +++ b/test/Microsoft.AspNetCore.Antiforgery.FunctionalTests/project.json @@ -8,7 +8,7 @@ }, "testRunner": "xunit", "frameworks": { - "netcoreapp1.1": { + "netcoreapp1.0": { "dependencies": { "Microsoft.NETCore.App": { "version": "1.1.0-*", diff --git a/test/Microsoft.AspNetCore.Antiforgery.Test/project.json b/test/Microsoft.AspNetCore.Antiforgery.Test/project.json index ac8572cba9..4a1effd185 100644 --- a/test/Microsoft.AspNetCore.Antiforgery.Test/project.json +++ b/test/Microsoft.AspNetCore.Antiforgery.Test/project.json @@ -16,7 +16,7 @@ }, "testRunner": "xunit", "frameworks": { - "netcoreapp1.1": { + "netcoreapp1.0": { "dependencies": { "Microsoft.NETCore.App": { "version": "1.1.0-*", From c5c94d88c86a56240f08ae819e4d5b51bd3450a8 Mon Sep 17 00:00:00 2001 From: Pranav K Date: Thu, 13 Oct 2016 11:11:20 -0700 Subject: [PATCH 158/296] Updating to netcoreapp1.1 --- samples/AntiforgerySample/project.json | 2 +- .../project.json | 2 +- test/Microsoft.AspNetCore.Antiforgery.Test/project.json | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/samples/AntiforgerySample/project.json b/samples/AntiforgerySample/project.json index 9c3fadf0c0..dd24a3b97b 100644 --- a/samples/AntiforgerySample/project.json +++ b/samples/AntiforgerySample/project.json @@ -14,7 +14,7 @@ }, "frameworks": { "net451": {}, - "netcoreapp1.0": { + "netcoreapp1.1": { "dependencies": { "Microsoft.NETCore.App": { "version": "1.1.0-*", diff --git a/test/Microsoft.AspNetCore.Antiforgery.FunctionalTests/project.json b/test/Microsoft.AspNetCore.Antiforgery.FunctionalTests/project.json index 73cfc7b4c4..984fb8ddd8 100644 --- a/test/Microsoft.AspNetCore.Antiforgery.FunctionalTests/project.json +++ b/test/Microsoft.AspNetCore.Antiforgery.FunctionalTests/project.json @@ -8,7 +8,7 @@ }, "testRunner": "xunit", "frameworks": { - "netcoreapp1.0": { + "netcoreapp1.1": { "dependencies": { "Microsoft.NETCore.App": { "version": "1.1.0-*", diff --git a/test/Microsoft.AspNetCore.Antiforgery.Test/project.json b/test/Microsoft.AspNetCore.Antiforgery.Test/project.json index 4a1effd185..ac8572cba9 100644 --- a/test/Microsoft.AspNetCore.Antiforgery.Test/project.json +++ b/test/Microsoft.AspNetCore.Antiforgery.Test/project.json @@ -16,7 +16,7 @@ }, "testRunner": "xunit", "frameworks": { - "netcoreapp1.0": { + "netcoreapp1.1": { "dependencies": { "Microsoft.NETCore.App": { "version": "1.1.0-*", From 01557cd176ac1a8c43e6e70039acb8e7830f13c2 Mon Sep 17 00:00:00 2001 From: Pranav K Date: Mon, 17 Oct 2016 09:48:36 -0700 Subject: [PATCH 159/296] Branching for 1.1.0-preview1 --- NuGet.config | 4 ++-- build.ps1 | 2 +- build.sh | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/NuGet.config b/NuGet.config index 0fd623ffdd..ad973186eb 100644 --- a/NuGet.config +++ b/NuGet.config @@ -1,7 +1,7 @@ - + - + diff --git a/build.ps1 b/build.ps1 index 8f2f99691a..787f63ac02 100644 --- a/build.ps1 +++ b/build.ps1 @@ -33,7 +33,7 @@ cd $PSScriptRoot $repoFolder = $PSScriptRoot $env:REPO_FOLDER = $repoFolder -$koreBuildZip="https://github.com/aspnet/KoreBuild/archive/dev.zip" +$koreBuildZip="https://github.com/aspnet/KoreBuild/archive/rel/1.1.0-preview1.zip" if ($env:KOREBUILD_ZIP) { $koreBuildZip=$env:KOREBUILD_ZIP diff --git a/build.sh b/build.sh index f4208100eb..355c682856 100755 --- a/build.sh +++ b/build.sh @@ -2,7 +2,7 @@ repoFolder="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" cd $repoFolder -koreBuildZip="https://github.com/aspnet/KoreBuild/archive/dev.zip" +koreBuildZip="https://github.com/aspnet/KoreBuild/archive/rel/1.1.0-preview1.zip" if [ ! -z $KOREBUILD_ZIP ]; then koreBuildZip=$KOREBUILD_ZIP fi From 72bc9c0f2c8606a150b159786be4b718e29598fc Mon Sep 17 00:00:00 2001 From: chris2093 Date: Wed, 19 Oct 2016 07:54:52 -0700 Subject: [PATCH 160/296] Update DefaultAntiforgeryTokenStore.cs (#106) Corrected comment typo --- .../Internal/DefaultAntiforgeryTokenStore.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgeryTokenStore.cs b/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgeryTokenStore.cs index 896961bb41..4b30e8ced9 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgeryTokenStore.cs +++ b/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgeryTokenStore.cs @@ -73,7 +73,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal options.HttpOnly = true; options.Path = httpContext.Request.PathBase; // Note: don't use "newCookie.Secure = _options.RequireSSL;" since the default - // value of newCookie.Secure is poulated out of band. + // value of newCookie.Secure is populated out of band. if (_options.RequireSsl) { options.Secure = true; @@ -82,4 +82,4 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal httpContext.Response.Cookies.Append(_options.CookieName, token, options); } } -} \ No newline at end of file +} From 08cb67b7e45c88eaba26a6c68b9f82a5608582d6 Mon Sep 17 00:00:00 2001 From: Kiran Challa Date: Mon, 31 Oct 2016 16:43:09 -0700 Subject: [PATCH 161/296] [Fixes #104] Expose cookie options via Antiforgery options --- .../AntiforgeryOptions.cs | 13 ++++ .../Internal/DefaultAntiforgeryTokenStore.cs | 3 +- .../DefaultAntiforgeryTokenStoreTest.cs | 70 +++++++++++++++++++ 3 files changed, 85 insertions(+), 1 deletion(-) diff --git a/src/Microsoft.AspNetCore.Antiforgery/AntiforgeryOptions.cs b/src/Microsoft.AspNetCore.Antiforgery/AntiforgeryOptions.cs index 2c05e1dc1c..98f4968c1e 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/AntiforgeryOptions.cs +++ b/src/Microsoft.AspNetCore.Antiforgery/AntiforgeryOptions.cs @@ -2,6 +2,7 @@ // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; +using Microsoft.AspNetCore.Http; namespace Microsoft.AspNetCore.Antiforgery { @@ -45,6 +46,18 @@ namespace Microsoft.AspNetCore.Antiforgery } } + /// + /// The path set on the cookie. If it's null, the "path" attribute on the cookie is set to current + /// request's value. + /// + public PathString? CookiePath { get; set; } + + /// + /// The domain set on the cookie. By default its null which results in the "domain" attribute not being + /// set. + /// + public string CookieDomain { get; set; } + /// /// Specifies the name of the antiforgery token field that is used by the antiforgery system. /// diff --git a/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgeryTokenStore.cs b/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgeryTokenStore.cs index 4b30e8ced9..9e3658fa93 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgeryTokenStore.cs +++ b/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgeryTokenStore.cs @@ -71,7 +71,8 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal var options = new CookieOptions(); options.HttpOnly = true; - options.Path = httpContext.Request.PathBase; + options.Path = _options.CookiePath ?? httpContext.Request.PathBase; + options.Domain = _options.CookieDomain; // Note: don't use "newCookie.Secure = _options.RequireSSL;" since the default // value of newCookie.Secure is populated out of band. if (_options.RequireSsl) diff --git a/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTokenStoreTest.cs b/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTokenStoreTest.cs index c48c0c9ead..fb6927f535 100644 --- a/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTokenStoreTest.cs +++ b/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTokenStoreTest.cs @@ -308,6 +308,76 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal Assert.Equal(requestPathBase, cookies.Options.Path); } + [Fact] + public void SaveCookieToken_NonNullAntiforgeryOptionsCookiePath_UsesOptionsCookiePath() + { + // Arrange + var expectedCookiePath = "/"; + var requestPathBase = "/vdir1"; + var token = "serialized-value"; + var cookies = new MockResponseCookieCollection(); + var httpContext = new Mock(); + httpContext + .Setup(hc => hc.Response.Cookies) + .Returns(cookies); + httpContext + .SetupGet(hc => hc.Request.PathBase) + .Returns(requestPathBase); + httpContext + .SetupGet(hc => hc.Request.Path) + .Returns("/index.html"); + var options = new AntiforgeryOptions(); + options.CookieName = _cookieName; + options.CookiePath = expectedCookiePath; + var tokenStore = new DefaultAntiforgeryTokenStore(new TestOptionsManager(options)); + + // Act + tokenStore.SaveCookieToken(httpContext.Object, token); + + // Assert + Assert.Equal(1, cookies.Count); + Assert.NotNull(cookies); + Assert.Equal(_cookieName, cookies.Key); + Assert.Equal("serialized-value", cookies.Value); + Assert.True(cookies.Options.HttpOnly); + Assert.Equal(expectedCookiePath, cookies.Options.Path); + } + + [Fact] + public void SaveCookieToken_NonNullAntiforgeryOptionsCookieDomain_UsesOptionsCookieDomain() + { + // Arrange + var expectedCookieDomain = "microsoft.com"; + var token = "serialized-value"; + var cookies = new MockResponseCookieCollection(); + var httpContext = new Mock(); + httpContext + .Setup(hc => hc.Response.Cookies) + .Returns(cookies); + httpContext + .SetupGet(hc => hc.Request.PathBase) + .Returns("/vdir1"); + httpContext + .SetupGet(hc => hc.Request.Path) + .Returns("/index.html"); + var options = new AntiforgeryOptions(); + options.CookieName = _cookieName; + options.CookieDomain = expectedCookieDomain; + var tokenStore = new DefaultAntiforgeryTokenStore(new TestOptionsManager(options)); + + // Act + tokenStore.SaveCookieToken(httpContext.Object, token); + + // Assert + Assert.Equal(1, cookies.Count); + Assert.NotNull(cookies); + Assert.Equal(_cookieName, cookies.Key); + Assert.Equal("serialized-value", cookies.Value); + Assert.True(cookies.Options.HttpOnly); + Assert.Equal("/vdir1", cookies.Options.Path); + Assert.Equal(expectedCookieDomain, cookies.Options.Domain); + } + private HttpContext GetHttpContext(string cookieName, string cookieValue) { var cookies = new RequestCookieCollection(new Dictionary From 3fc090e2fee47884af7968031e40876fcb6549ae Mon Sep 17 00:00:00 2001 From: Kiran Challa Date: Thu, 27 Oct 2016 17:18:50 -0700 Subject: [PATCH 162/296] [Fixes #105] Disable caching when response uses antiforgery --- .../IAntiforgery.cs | 3 +- .../Internal/AntiforgeryLoggerExtensions.cs | 11 + .../Internal/DefaultAntiforgery.cs | 46 +++ .../project.json | 1 + .../Internal/DefaultAntiforgeryTest.cs | 272 ++++++++++++++++++ .../project.json | 1 + 6 files changed, 333 insertions(+), 1 deletion(-) diff --git a/src/Microsoft.AspNetCore.Antiforgery/IAntiforgery.cs b/src/Microsoft.AspNetCore.Antiforgery/IAntiforgery.cs index 6ac2e44e37..d6dd05aeae 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/IAntiforgery.cs +++ b/src/Microsoft.AspNetCore.Antiforgery/IAntiforgery.cs @@ -14,7 +14,8 @@ namespace Microsoft.AspNetCore.Antiforgery { /// /// Generates an for this request and stores the cookie token - /// in the response. + /// in the response. This operation also sets the "Cache-control" and "Pragma" headers to "no-cache" and + /// the "X-Frame-Options" header to "SAMEORIGIN". /// /// The associated with the current request. /// An with tokens for the response. diff --git a/src/Microsoft.AspNetCore.Antiforgery/Internal/AntiforgeryLoggerExtensions.cs b/src/Microsoft.AspNetCore.Antiforgery/Internal/AntiforgeryLoggerExtensions.cs index 5e115bb76a..7dd43069db 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/Internal/AntiforgeryLoggerExtensions.cs +++ b/src/Microsoft.AspNetCore.Antiforgery/Internal/AntiforgeryLoggerExtensions.cs @@ -15,6 +15,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal private static readonly Action _newCookieToken; private static readonly Action _reusedCookieToken; private static readonly Action _tokenDeserializeException; + private static readonly Action _responseCacheHeadersOverridenToNoCache; static AntiforgeryLoggerExtensions() { @@ -47,6 +48,11 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal LogLevel.Error, 7, "An exception was thrown while deserializing the token."); + _responseCacheHeadersOverridenToNoCache = LoggerMessage.Define( + LogLevel.Warning, + 8, + "The 'Cache-Control' and 'Pragma' headers have been overridden and set to 'no-cache' to prevent " + + "caching of this response. Any response that uses antiforgery should not be cached."); } public static void ValidationFailed(this ILogger logger, string message) @@ -83,5 +89,10 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal { _tokenDeserializeException(logger, exception); } + + public static void ResponseCacheHeadersOverridenToNoCache(this ILogger logger) + { + _responseCacheHeadersOverridenToNoCache(logger, null); + } } } diff --git a/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgery.cs b/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgery.cs index eeb92cf777..755d8ae2f1 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgery.cs +++ b/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgery.cs @@ -7,6 +7,7 @@ using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; +using Microsoft.Net.Http.Headers; namespace Microsoft.AspNetCore.Antiforgery.Internal { @@ -66,6 +67,10 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal } } + // Explicitly set the cache headers to 'no-cache'. This could override any user set value but this is fine + // as a response with antiforgery token must never be cached. + SetDoNotCacheHeaders(httpContext); + return tokenSet; } @@ -237,6 +242,10 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal { _logger.ReusedCookieToken(); } + + // Explicitly set the cache headers to 'no-cache'. This could override any user set value but this is fine + // as a response with antiforgery token must never be cached. + SetDoNotCacheHeaders(httpContext); } private void SaveCookieTokenAndHeader(HttpContext httpContext, string cookieToken) @@ -358,6 +367,43 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal return antiforgeryFeature; } + private void SetDoNotCacheHeaders(HttpContext httpContext) + { + // Since antifogery token generation is not very obvious to the end users (ex: MVC's form tag generates them + // by default), log a warning to let users know of the change in behavior to any cache headers they might + // have set explicitly. + LogCacheHeaderOverrideWarning(httpContext.Response); + + httpContext.Response.Headers[HeaderNames.CacheControl] = "no-cache"; + httpContext.Response.Headers[HeaderNames.Pragma] = "no-cache"; + } + + private void LogCacheHeaderOverrideWarning(HttpResponse response) + { + var logWarning = false; + CacheControlHeaderValue cacheControlHeaderValue; + if (CacheControlHeaderValue.TryParse(response.Headers[HeaderNames.CacheControl], out cacheControlHeaderValue)) + { + if (!cacheControlHeaderValue.NoCache) + { + logWarning = true; + } + } + + var pragmaHeader = response.Headers[HeaderNames.Pragma]; + if (!logWarning + && !string.IsNullOrEmpty(pragmaHeader) + && string.Compare(pragmaHeader, "no-cache", ignoreCase: true) != 0) + { + logWarning = true; + } + + if (logWarning) + { + _logger.ResponseCacheHeadersOverridenToNoCache(); + } + } + private AntiforgeryTokenSet Serialize(IAntiforgeryFeature antiforgeryFeature) { // Should only be called after new tokens have been generated. diff --git a/src/Microsoft.AspNetCore.Antiforgery/project.json b/src/Microsoft.AspNetCore.Antiforgery/project.json index 259531cafe..5c9b5608f8 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/project.json +++ b/src/Microsoft.AspNetCore.Antiforgery/project.json @@ -22,6 +22,7 @@ "dependencies": { "Microsoft.AspNetCore.DataProtection": "1.1.0-*", "Microsoft.AspNetCore.Http.Abstractions": "1.1.0-*", + "Microsoft.AspNetCore.Http.Extensions": "1.1.0-*", "Microsoft.AspNetCore.WebUtilities": "1.1.0-*", "Microsoft.Extensions.ObjectPool": "1.1.0-*", "NETStandard.Library": "1.6.1-*" diff --git a/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTest.cs b/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTest.cs index 09de9243d5..943eb94cb4 100644 --- a/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTest.cs +++ b/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTest.cs @@ -2,12 +2,15 @@ // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; +using System.Linq; using System.Security.Claims; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Logging.Testing; using Microsoft.Extensions.Options; +using Microsoft.Net.Http.Headers; using Moq; using Xunit; @@ -15,6 +18,10 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal { public class DefaultAntiforgeryTest { + private const string ResponseCacheHeadersOverrideWarningMessage = + "The 'Cache-Control' and 'Pragma' headers have been overridden and set to 'no-cache' to prevent caching " + + "of this response. Any response that uses antiforgery should not be cached."; + [Fact] public async Task ChecksSSL_ValidateRequestAsync_Throws() { @@ -275,6 +282,67 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal Assert.Equal(context.TestTokenSet.FormTokenString, antiforgeryFeature.NewRequestTokenString); } + [Fact] + public void GetAndStoreTokens_ExistingValidCookieToken_NotOverriden_AndSetsDoNotCacheHeaders() + { + // Arrange + var antiforgeryFeature = new AntiforgeryFeature(); + var context = CreateMockContext( + new AntiforgeryOptions(), + useOldCookie: true, + isOldCookieValid: true, + antiforgeryFeature: antiforgeryFeature); + var antiforgery = GetAntiforgery(context); + + // Act + var tokenSet = antiforgery.GetAndStoreTokens(context.HttpContext); + + // Assert + // We shouldn't have saved the cookie because it already existed. + context.TokenStore.Verify( + t => t.SaveCookieToken(It.IsAny(), It.IsAny()), + Times.Never); + + Assert.Null(tokenSet.CookieToken); + Assert.Equal(context.TestTokenSet.FormTokenString, tokenSet.RequestToken); + + Assert.NotNull(antiforgeryFeature); + Assert.Equal(context.TestTokenSet.OldCookieToken, antiforgeryFeature.CookieToken); + Assert.Equal("no-cache", context.HttpContext.Response.Headers[HeaderNames.CacheControl]); + Assert.Equal("no-cache", context.HttpContext.Response.Headers[HeaderNames.Pragma]); + } + + [Fact] + public void GetAndStoreTokens_ExistingCachingHeaders_Overriden() + { + // Arrange + var antiforgeryFeature = new AntiforgeryFeature(); + var context = CreateMockContext( + new AntiforgeryOptions(), + useOldCookie: true, + isOldCookieValid: true, + antiforgeryFeature: antiforgeryFeature); + var antiforgery = GetAntiforgery(context); + context.HttpContext.Response.Headers["Cache-Control"] = "public"; + + // Act + var tokenSet = antiforgery.GetAndStoreTokens(context.HttpContext); + + // Assert + // We shouldn't have saved the cookie because it already existed. + context.TokenStore.Verify( + t => t.SaveCookieToken(It.IsAny(), It.IsAny()), + Times.Never); + + Assert.Null(tokenSet.CookieToken); + Assert.Equal(context.TestTokenSet.FormTokenString, tokenSet.RequestToken); + + Assert.NotNull(antiforgeryFeature); + Assert.Equal(context.TestTokenSet.OldCookieToken, antiforgeryFeature.CookieToken); + Assert.Equal("no-cache", context.HttpContext.Response.Headers[HeaderNames.CacheControl]); + Assert.Equal("no-cache", context.HttpContext.Response.Headers[HeaderNames.Pragma]); + } + [Fact] public void GetAndStoreTokens_NoExistingCookieToken_Saved() { @@ -309,6 +377,36 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal Assert.True(antiforgeryFeature.HaveStoredNewCookieToken); } + [Fact] + public void GetAndStoreTokens_NoExistingCookieToken_Saved_AndSetsDoNotCacheHeaders() + { + // Arrange + var antiforgeryFeature = new AntiforgeryFeature(); + var context = CreateMockContext( + new AntiforgeryOptions(), + useOldCookie: false, + isOldCookieValid: false, + antiforgeryFeature: antiforgeryFeature); + var antiforgery = GetAntiforgery(context); + + // Act + var tokenSet = antiforgery.GetAndStoreTokens(context.HttpContext); + + // Assert + context.TokenStore.Verify( + t => t.SaveCookieToken(It.IsAny(), context.TestTokenSet.NewCookieTokenString), + Times.Once); + + Assert.Equal(context.TestTokenSet.NewCookieTokenString, tokenSet.CookieToken); + Assert.Equal(context.TestTokenSet.FormTokenString, tokenSet.RequestToken); + + Assert.NotNull(antiforgeryFeature); + Assert.True(antiforgeryFeature.HaveDeserializedCookieToken); + Assert.Equal(context.TestTokenSet.OldCookieToken, antiforgeryFeature.CookieToken); + Assert.Equal("no-cache", context.HttpContext.Response.Headers[HeaderNames.CacheControl]); + Assert.Equal("no-cache", context.HttpContext.Response.Headers[HeaderNames.Pragma]); + } + [Fact] public void GetAndStoreTokens_DoesNotSerializeTwice() { @@ -808,6 +906,76 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal Assert.Equal(expectedHeaderValue, xFrameOptions); } + [Fact] + public void SetCookieTokenAndHeader_NewCookieToken_SetsDoNotCacheHeaders() + { + // Arrange + var options = new AntiforgeryOptions(); + var antiforgeryFeature = new AntiforgeryFeature(); + + // Generate a new cookie. + var context = CreateMockContext( + options, + useOldCookie: false, + isOldCookieValid: false, + antiforgeryFeature: antiforgeryFeature); + var antiforgery = GetAntiforgery(context); + + // Act + antiforgery.SetCookieTokenAndHeader(context.HttpContext); + + // Assert + Assert.Equal("no-cache", context.HttpContext.Response.Headers["Cache-Control"]); + Assert.Equal("no-cache", context.HttpContext.Response.Headers["Pragma"]); + } + + [Fact] + public void SetCookieTokenAndHeader_ValidOldCookieToken_SetsDoNotCacheHeaders() + { + // Arrange + var options = new AntiforgeryOptions(); + var antiforgeryFeature = new AntiforgeryFeature(); + + // Generate a new cookie. + var context = CreateMockContext( + options, + useOldCookie: true, + isOldCookieValid: true, + antiforgeryFeature: antiforgeryFeature); + var antiforgery = GetAntiforgery(context); + + // Act + antiforgery.SetCookieTokenAndHeader(context.HttpContext); + + // Assert + Assert.Equal("no-cache", context.HttpContext.Response.Headers["Cache-Control"]); + Assert.Equal("no-cache", context.HttpContext.Response.Headers["Pragma"]); + } + + [Fact] + public void SetCookieTokenAndHeader_OverridesExistingCachingHeaders() + { + // Arrange + var options = new AntiforgeryOptions(); + var antiforgeryFeature = new AntiforgeryFeature(); + + // Generate a new cookie. + var context = CreateMockContext( + options, + useOldCookie: true, + isOldCookieValid: true, + antiforgeryFeature: antiforgeryFeature); + var antiforgery = GetAntiforgery(context); + context.HttpContext.Response.Headers["Cache-Control"] = "public"; + + // Act + antiforgery.SetCookieTokenAndHeader(context.HttpContext); + + // Assert + Assert.Equal("no-cache", context.HttpContext.Response.Headers["Cache-Control"]); + Assert.Equal("no-cache", context.HttpContext.Response.Headers["Pragma"]); + } + [Theory] [InlineData(false, "SAMEORIGIN")] [InlineData(true, null)] @@ -965,6 +1133,110 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal context.TokenSerializer.Verify(s => s.Deserialize(null), Times.Never); } + [Fact] + public void GetAndStoreTokens_DoesNotLogWarning_IfNoExistingCacheHeadersPresent() + { + // Arrange + var testSink = new TestSink(); + var loggerFactory = new Mock(); + loggerFactory + .Setup(lf => lf.CreateLogger(typeof(DefaultAntiforgery).FullName)) + .Returns(new TestLogger("test logger", testSink, enabled: true)); + var services = new ServiceCollection(); + services.AddSingleton(loggerFactory.Object); + var antiforgeryFeature = new AntiforgeryFeature(); + var context = CreateMockContext( + new AntiforgeryOptions(), + useOldCookie: false, + isOldCookieValid: false, + antiforgeryFeature: antiforgeryFeature); + context.HttpContext.RequestServices = services.BuildServiceProvider(); + var antiforgery = GetAntiforgery(context); + + // Act + var tokenSet = antiforgery.GetAndStoreTokens(context.HttpContext); + + // Assert + var hasWarningMessage = testSink.Writes + .Where(wc => wc.LogLevel == LogLevel.Warning) + .Select(wc => wc.State?.ToString()) + .Contains(ResponseCacheHeadersOverrideWarningMessage); + Assert.False(hasWarningMessage); + } + + [Theory] + [InlineData("Cache-Control", "Public")] + [InlineData("Cache-Control", "PuBlic")] + [InlineData("Cache-Control", "Private")] + [InlineData("Cache-Control", "PriVate")] + [InlineData("Cache-Control", "No-Store")] + [InlineData("Cache-Control", "No-store")] + [InlineData("Pragma", "Foo")] + public void GetAndStoreTokens_LogsWarning_NonNoCacheHeadersAlreadyPresent(string headerName, string headerValue) + { + // Arrange + var testSink = new TestSink(); + var loggerFactory = new Mock(); + loggerFactory + .Setup(lf => lf.CreateLogger(typeof(DefaultAntiforgery).FullName)) + .Returns(new TestLogger("test logger", testSink, enabled: true)); + var services = new ServiceCollection(); + services.AddSingleton(loggerFactory.Object); + var antiforgeryFeature = new AntiforgeryFeature(); + var context = CreateMockContext( + new AntiforgeryOptions(), + useOldCookie: false, + isOldCookieValid: false, + antiforgeryFeature: antiforgeryFeature); + context.HttpContext.RequestServices = services.BuildServiceProvider(); + var antiforgery = GetAntiforgery(context); + context.HttpContext.Response.Headers[headerName] = headerValue; + + // Act + var tokenSet = antiforgery.GetAndStoreTokens(context.HttpContext); + + // Assert + var hasWarningMessage = testSink.Writes + .Where(wc => wc.LogLevel == LogLevel.Warning) + .Select(wc => wc.State?.ToString()) + .Contains(ResponseCacheHeadersOverrideWarningMessage); + Assert.True(hasWarningMessage); + } + + [Theory] + [InlineData("Cache-Control", "no-cache")] + [InlineData("Pragma", "no-cache")] + public void GetAndStoreTokens_DoesNotLogsWarning_ForNoCacheHeaders_AlreadyPresent(string headerName, string headerValue) + { + // Arrange + var testSink = new TestSink(); + var loggerFactory = new Mock(); + loggerFactory + .Setup(lf => lf.CreateLogger(typeof(DefaultAntiforgery).FullName)) + .Returns(new TestLogger("test logger", testSink, enabled: true)); + var services = new ServiceCollection(); + services.AddSingleton(loggerFactory.Object); + var antiforgeryFeature = new AntiforgeryFeature(); + var context = CreateMockContext( + new AntiforgeryOptions(), + useOldCookie: false, + isOldCookieValid: false, + antiforgeryFeature: antiforgeryFeature); + context.HttpContext.RequestServices = services.BuildServiceProvider(); + var antiforgery = GetAntiforgery(context); + context.HttpContext.Response.Headers[headerName] = headerValue; + + // Act + var tokenSet = antiforgery.GetAndStoreTokens(context.HttpContext); + + // Assert + var hasWarningMessage = testSink.Writes + .Where(wc => wc.LogLevel == LogLevel.Warning) + .Select(wc => wc.State?.ToString()) + .Contains(ResponseCacheHeadersOverrideWarningMessage); + Assert.False(hasWarningMessage); + } + private DefaultAntiforgery GetAntiforgery( HttpContext httpContext, AntiforgeryOptions options = null, diff --git a/test/Microsoft.AspNetCore.Antiforgery.Test/project.json b/test/Microsoft.AspNetCore.Antiforgery.Test/project.json index ac8572cba9..c8cff04a99 100644 --- a/test/Microsoft.AspNetCore.Antiforgery.Test/project.json +++ b/test/Microsoft.AspNetCore.Antiforgery.Test/project.json @@ -10,6 +10,7 @@ "Microsoft.AspNetCore.Testing": "1.1.0-*", "Microsoft.Extensions.DependencyInjection": "1.1.0-*", "Microsoft.Extensions.Logging": "1.1.0-*", + "Microsoft.Extensions.Logging.Testing": "1.1.0-*", "Microsoft.Extensions.WebEncoders": "1.1.0-*", "Moq": "4.6.36-*", "xunit": "2.2.0-*" From 968ea59ce4d4dd08c813140144f6a251f8b9a3c3 Mon Sep 17 00:00:00 2001 From: jacalvar Date: Fri, 4 Nov 2016 10:18:51 -0700 Subject: [PATCH 163/296] Created public API baselines --- .../baseline.net45.json | 1875 +++++++++++++++++ .../baseline.netcore.json | 1875 +++++++++++++++++ 2 files changed, 3750 insertions(+) create mode 100644 src/Microsoft.AspNetCore.Antiforgery/baseline.net45.json create mode 100644 src/Microsoft.AspNetCore.Antiforgery/baseline.netcore.json diff --git a/src/Microsoft.AspNetCore.Antiforgery/baseline.net45.json b/src/Microsoft.AspNetCore.Antiforgery/baseline.net45.json new file mode 100644 index 0000000000..9117fb75fd --- /dev/null +++ b/src/Microsoft.AspNetCore.Antiforgery/baseline.net45.json @@ -0,0 +1,1875 @@ +{ + "AssemblyIdentity": "Microsoft.AspNetCore.Antiforgery, Version=1.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60", + "Types": [ + { + "Name": "Microsoft.Extensions.DependencyInjection.AntiforgeryServiceCollectionExtensions", + "Visibility": "Public", + "Kind": "Class", + "Abstract": true, + "Static": true, + "Sealed": true, + "ImplementedInterfaces": [], + "Members": [ + { + "Kind": "Method", + "Name": "AddAntiforgery", + "Parameters": [ + { + "Name": "services", + "Type": "Microsoft.Extensions.DependencyInjection.IServiceCollection" + } + ], + "ReturnType": "Microsoft.Extensions.DependencyInjection.IServiceCollection", + "Static": true, + "Extension": true, + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "AddAntiforgery", + "Parameters": [ + { + "Name": "services", + "Type": "Microsoft.Extensions.DependencyInjection.IServiceCollection" + }, + { + "Name": "setupAction", + "Type": "System.Action" + } + ], + "ReturnType": "Microsoft.Extensions.DependencyInjection.IServiceCollection", + "Static": true, + "Extension": true, + "Visibility": "Public", + "GenericParameter": [] + } + ], + "GenericParameters": [] + }, + { + "Name": "Microsoft.AspNetCore.Antiforgery.AntiforgeryOptions", + "Visibility": "Public", + "Kind": "Class", + "ImplementedInterfaces": [], + "Members": [ + { + "Kind": "Method", + "Name": "get_CookieName", + "Parameters": [], + "ReturnType": "System.String", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "set_CookieName", + "Parameters": [ + { + "Name": "value", + "Type": "System.String" + } + ], + "ReturnType": "System.Void", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "get_FormFieldName", + "Parameters": [], + "ReturnType": "System.String", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "set_FormFieldName", + "Parameters": [ + { + "Name": "value", + "Type": "System.String" + } + ], + "ReturnType": "System.Void", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "get_HeaderName", + "Parameters": [], + "ReturnType": "System.String", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "set_HeaderName", + "Parameters": [ + { + "Name": "value", + "Type": "System.String" + } + ], + "ReturnType": "System.Void", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "get_RequireSsl", + "Parameters": [], + "ReturnType": "System.Boolean", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "set_RequireSsl", + "Parameters": [ + { + "Name": "value", + "Type": "System.Boolean" + } + ], + "ReturnType": "System.Void", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "get_SuppressXFrameOptionsHeader", + "Parameters": [], + "ReturnType": "System.Boolean", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "set_SuppressXFrameOptionsHeader", + "Parameters": [ + { + "Name": "value", + "Type": "System.Boolean" + } + ], + "ReturnType": "System.Void", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Constructor", + "Name": ".ctor", + "Parameters": [], + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Field", + "Name": "DefaultCookiePrefix", + "Parameters": [], + "ReturnType": "System.String", + "Static": true, + "ReadOnly": true, + "Visibility": "Public", + "GenericParameter": [] + } + ], + "GenericParameters": [] + }, + { + "Name": "Microsoft.AspNetCore.Antiforgery.AntiforgeryTokenSet", + "Visibility": "Public", + "Kind": "Class", + "ImplementedInterfaces": [], + "Members": [ + { + "Kind": "Method", + "Name": "get_RequestToken", + "Parameters": [], + "ReturnType": "System.String", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "get_FormFieldName", + "Parameters": [], + "ReturnType": "System.String", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "get_HeaderName", + "Parameters": [], + "ReturnType": "System.String", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "get_CookieToken", + "Parameters": [], + "ReturnType": "System.String", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Constructor", + "Name": ".ctor", + "Parameters": [ + { + "Name": "requestToken", + "Type": "System.String" + }, + { + "Name": "cookieToken", + "Type": "System.String" + }, + { + "Name": "formFieldName", + "Type": "System.String" + }, + { + "Name": "headerName", + "Type": "System.String" + } + ], + "Visibility": "Public", + "GenericParameter": [] + } + ], + "GenericParameters": [] + }, + { + "Name": "Microsoft.AspNetCore.Antiforgery.AntiforgeryValidationException", + "Visibility": "Public", + "Kind": "Class", + "BaseType": "System.Exception", + "ImplementedInterfaces": [], + "Members": [ + { + "Kind": "Constructor", + "Name": ".ctor", + "Parameters": [ + { + "Name": "message", + "Type": "System.String" + } + ], + "Visibility": "Public", + "GenericParameter": [] + } + ], + "GenericParameters": [] + }, + { + "Name": "Microsoft.AspNetCore.Antiforgery.IAntiforgery", + "Visibility": "Public", + "Kind": "Interface", + "Abstract": true, + "ImplementedInterfaces": [], + "Members": [ + { + "Kind": "Method", + "Name": "GetAndStoreTokens", + "Parameters": [ + { + "Name": "httpContext", + "Type": "Microsoft.AspNetCore.Http.HttpContext" + } + ], + "ReturnType": "Microsoft.AspNetCore.Antiforgery.AntiforgeryTokenSet", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "GetTokens", + "Parameters": [ + { + "Name": "httpContext", + "Type": "Microsoft.AspNetCore.Http.HttpContext" + } + ], + "ReturnType": "Microsoft.AspNetCore.Antiforgery.AntiforgeryTokenSet", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "IsRequestValidAsync", + "Parameters": [ + { + "Name": "httpContext", + "Type": "Microsoft.AspNetCore.Http.HttpContext" + } + ], + "ReturnType": "System.Threading.Tasks.Task", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "ValidateRequestAsync", + "Parameters": [ + { + "Name": "httpContext", + "Type": "Microsoft.AspNetCore.Http.HttpContext" + } + ], + "ReturnType": "System.Threading.Tasks.Task", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "SetCookieTokenAndHeader", + "Parameters": [ + { + "Name": "httpContext", + "Type": "Microsoft.AspNetCore.Http.HttpContext" + } + ], + "ReturnType": "System.Void", + "GenericParameter": [] + } + ], + "GenericParameters": [] + }, + { + "Name": "Microsoft.AspNetCore.Antiforgery.IAntiforgeryAdditionalDataProvider", + "Visibility": "Public", + "Kind": "Interface", + "Abstract": true, + "ImplementedInterfaces": [], + "Members": [ + { + "Kind": "Method", + "Name": "GetAdditionalData", + "Parameters": [ + { + "Name": "context", + "Type": "Microsoft.AspNetCore.Http.HttpContext" + } + ], + "ReturnType": "System.String", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "ValidateAdditionalData", + "Parameters": [ + { + "Name": "context", + "Type": "Microsoft.AspNetCore.Http.HttpContext" + }, + { + "Name": "additionalData", + "Type": "System.String" + } + ], + "ReturnType": "System.Boolean", + "GenericParameter": [] + } + ], + "GenericParameters": [] + }, + { + "Name": "Microsoft.AspNetCore.Antiforgery.Internal.AntiforgeryFeature", + "Visibility": "Public", + "Kind": "Class", + "ImplementedInterfaces": [ + "Microsoft.AspNetCore.Antiforgery.Internal.IAntiforgeryFeature" + ], + "Members": [ + { + "Kind": "Method", + "Name": "get_HaveDeserializedCookieToken", + "Parameters": [], + "ReturnType": "System.Boolean", + "Sealed": true, + "Virtual": true, + "ImplementedInterface": "Microsoft.AspNetCore.Antiforgery.Internal.IAntiforgeryFeature", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "set_HaveDeserializedCookieToken", + "Parameters": [ + { + "Name": "value", + "Type": "System.Boolean" + } + ], + "ReturnType": "System.Void", + "Sealed": true, + "Virtual": true, + "ImplementedInterface": "Microsoft.AspNetCore.Antiforgery.Internal.IAntiforgeryFeature", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "get_CookieToken", + "Parameters": [], + "ReturnType": "Microsoft.AspNetCore.Antiforgery.Internal.AntiforgeryToken", + "Sealed": true, + "Virtual": true, + "ImplementedInterface": "Microsoft.AspNetCore.Antiforgery.Internal.IAntiforgeryFeature", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "set_CookieToken", + "Parameters": [ + { + "Name": "value", + "Type": "Microsoft.AspNetCore.Antiforgery.Internal.AntiforgeryToken" + } + ], + "ReturnType": "System.Void", + "Sealed": true, + "Virtual": true, + "ImplementedInterface": "Microsoft.AspNetCore.Antiforgery.Internal.IAntiforgeryFeature", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "get_HaveDeserializedRequestToken", + "Parameters": [], + "ReturnType": "System.Boolean", + "Sealed": true, + "Virtual": true, + "ImplementedInterface": "Microsoft.AspNetCore.Antiforgery.Internal.IAntiforgeryFeature", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "set_HaveDeserializedRequestToken", + "Parameters": [ + { + "Name": "value", + "Type": "System.Boolean" + } + ], + "ReturnType": "System.Void", + "Sealed": true, + "Virtual": true, + "ImplementedInterface": "Microsoft.AspNetCore.Antiforgery.Internal.IAntiforgeryFeature", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "get_RequestToken", + "Parameters": [], + "ReturnType": "Microsoft.AspNetCore.Antiforgery.Internal.AntiforgeryToken", + "Sealed": true, + "Virtual": true, + "ImplementedInterface": "Microsoft.AspNetCore.Antiforgery.Internal.IAntiforgeryFeature", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "set_RequestToken", + "Parameters": [ + { + "Name": "value", + "Type": "Microsoft.AspNetCore.Antiforgery.Internal.AntiforgeryToken" + } + ], + "ReturnType": "System.Void", + "Sealed": true, + "Virtual": true, + "ImplementedInterface": "Microsoft.AspNetCore.Antiforgery.Internal.IAntiforgeryFeature", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "get_HaveGeneratedNewCookieToken", + "Parameters": [], + "ReturnType": "System.Boolean", + "Sealed": true, + "Virtual": true, + "ImplementedInterface": "Microsoft.AspNetCore.Antiforgery.Internal.IAntiforgeryFeature", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "set_HaveGeneratedNewCookieToken", + "Parameters": [ + { + "Name": "value", + "Type": "System.Boolean" + } + ], + "ReturnType": "System.Void", + "Sealed": true, + "Virtual": true, + "ImplementedInterface": "Microsoft.AspNetCore.Antiforgery.Internal.IAntiforgeryFeature", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "get_NewCookieToken", + "Parameters": [], + "ReturnType": "Microsoft.AspNetCore.Antiforgery.Internal.AntiforgeryToken", + "Sealed": true, + "Virtual": true, + "ImplementedInterface": "Microsoft.AspNetCore.Antiforgery.Internal.IAntiforgeryFeature", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "set_NewCookieToken", + "Parameters": [ + { + "Name": "value", + "Type": "Microsoft.AspNetCore.Antiforgery.Internal.AntiforgeryToken" + } + ], + "ReturnType": "System.Void", + "Sealed": true, + "Virtual": true, + "ImplementedInterface": "Microsoft.AspNetCore.Antiforgery.Internal.IAntiforgeryFeature", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "get_NewCookieTokenString", + "Parameters": [], + "ReturnType": "System.String", + "Sealed": true, + "Virtual": true, + "ImplementedInterface": "Microsoft.AspNetCore.Antiforgery.Internal.IAntiforgeryFeature", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "set_NewCookieTokenString", + "Parameters": [ + { + "Name": "value", + "Type": "System.String" + } + ], + "ReturnType": "System.Void", + "Sealed": true, + "Virtual": true, + "ImplementedInterface": "Microsoft.AspNetCore.Antiforgery.Internal.IAntiforgeryFeature", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "get_NewRequestToken", + "Parameters": [], + "ReturnType": "Microsoft.AspNetCore.Antiforgery.Internal.AntiforgeryToken", + "Sealed": true, + "Virtual": true, + "ImplementedInterface": "Microsoft.AspNetCore.Antiforgery.Internal.IAntiforgeryFeature", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "set_NewRequestToken", + "Parameters": [ + { + "Name": "value", + "Type": "Microsoft.AspNetCore.Antiforgery.Internal.AntiforgeryToken" + } + ], + "ReturnType": "System.Void", + "Sealed": true, + "Virtual": true, + "ImplementedInterface": "Microsoft.AspNetCore.Antiforgery.Internal.IAntiforgeryFeature", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "get_NewRequestTokenString", + "Parameters": [], + "ReturnType": "System.String", + "Sealed": true, + "Virtual": true, + "ImplementedInterface": "Microsoft.AspNetCore.Antiforgery.Internal.IAntiforgeryFeature", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "set_NewRequestTokenString", + "Parameters": [ + { + "Name": "value", + "Type": "System.String" + } + ], + "ReturnType": "System.Void", + "Sealed": true, + "Virtual": true, + "ImplementedInterface": "Microsoft.AspNetCore.Antiforgery.Internal.IAntiforgeryFeature", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "get_HaveStoredNewCookieToken", + "Parameters": [], + "ReturnType": "System.Boolean", + "Sealed": true, + "Virtual": true, + "ImplementedInterface": "Microsoft.AspNetCore.Antiforgery.Internal.IAntiforgeryFeature", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "set_HaveStoredNewCookieToken", + "Parameters": [ + { + "Name": "value", + "Type": "System.Boolean" + } + ], + "ReturnType": "System.Void", + "Sealed": true, + "Virtual": true, + "ImplementedInterface": "Microsoft.AspNetCore.Antiforgery.Internal.IAntiforgeryFeature", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Constructor", + "Name": ".ctor", + "Parameters": [], + "Visibility": "Public", + "GenericParameter": [] + } + ], + "GenericParameters": [] + }, + { + "Name": "Microsoft.AspNetCore.Antiforgery.Internal.AntiforgeryOptionsSetup", + "Visibility": "Public", + "Kind": "Class", + "BaseType": "Microsoft.Extensions.Options.ConfigureOptions", + "ImplementedInterfaces": [], + "Members": [ + { + "Kind": "Method", + "Name": "ConfigureOptions", + "Parameters": [ + { + "Name": "options", + "Type": "Microsoft.AspNetCore.Antiforgery.AntiforgeryOptions" + }, + { + "Name": "dataProtectionOptions", + "Type": "Microsoft.AspNetCore.DataProtection.DataProtectionOptions" + } + ], + "ReturnType": "System.Void", + "Static": true, + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Constructor", + "Name": ".ctor", + "Parameters": [ + { + "Name": "dataProtectionOptionsAccessor", + "Type": "Microsoft.Extensions.Options.IOptions" + } + ], + "Visibility": "Public", + "GenericParameter": [] + } + ], + "GenericParameters": [] + }, + { + "Name": "Microsoft.AspNetCore.Antiforgery.Internal.AntiforgerySerializationContext", + "Visibility": "Public", + "Kind": "Class", + "ImplementedInterfaces": [], + "Members": [ + { + "Kind": "Method", + "Name": "get_Stream", + "Parameters": [], + "ReturnType": "System.IO.MemoryStream", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "get_Reader", + "Parameters": [], + "ReturnType": "System.IO.BinaryReader", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "get_Writer", + "Parameters": [], + "ReturnType": "System.IO.BinaryWriter", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "get_Sha256", + "Parameters": [], + "ReturnType": "System.Security.Cryptography.SHA256", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "GetChars", + "Parameters": [ + { + "Name": "count", + "Type": "System.Int32" + } + ], + "ReturnType": "System.Char[]", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "Reset", + "Parameters": [], + "ReturnType": "System.Void", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Constructor", + "Name": ".ctor", + "Parameters": [], + "Visibility": "Public", + "GenericParameter": [] + } + ], + "GenericParameters": [] + }, + { + "Name": "Microsoft.AspNetCore.Antiforgery.Internal.AntiforgerySerializationContextPooledObjectPolicy", + "Visibility": "Public", + "Kind": "Class", + "ImplementedInterfaces": [ + "Microsoft.Extensions.ObjectPool.IPooledObjectPolicy" + ], + "Members": [ + { + "Kind": "Method", + "Name": "Create", + "Parameters": [], + "ReturnType": "Microsoft.AspNetCore.Antiforgery.Internal.AntiforgerySerializationContext", + "Sealed": true, + "Virtual": true, + "ImplementedInterface": "Microsoft.Extensions.ObjectPool.IPooledObjectPolicy", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "Return", + "Parameters": [ + { + "Name": "obj", + "Type": "Microsoft.AspNetCore.Antiforgery.Internal.AntiforgerySerializationContext" + } + ], + "ReturnType": "System.Boolean", + "Sealed": true, + "Virtual": true, + "ImplementedInterface": "Microsoft.Extensions.ObjectPool.IPooledObjectPolicy", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Constructor", + "Name": ".ctor", + "Parameters": [], + "Visibility": "Public", + "GenericParameter": [] + } + ], + "GenericParameters": [] + }, + { + "Name": "Microsoft.AspNetCore.Antiforgery.Internal.AntiforgeryToken", + "Visibility": "Public", + "Kind": "Class", + "Sealed": true, + "ImplementedInterfaces": [], + "Members": [ + { + "Kind": "Method", + "Name": "get_AdditionalData", + "Parameters": [], + "ReturnType": "System.String", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "set_AdditionalData", + "Parameters": [ + { + "Name": "value", + "Type": "System.String" + } + ], + "ReturnType": "System.Void", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "get_ClaimUid", + "Parameters": [], + "ReturnType": "Microsoft.AspNetCore.Antiforgery.Internal.BinaryBlob", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "set_ClaimUid", + "Parameters": [ + { + "Name": "value", + "Type": "Microsoft.AspNetCore.Antiforgery.Internal.BinaryBlob" + } + ], + "ReturnType": "System.Void", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "get_IsCookieToken", + "Parameters": [], + "ReturnType": "System.Boolean", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "set_IsCookieToken", + "Parameters": [ + { + "Name": "value", + "Type": "System.Boolean" + } + ], + "ReturnType": "System.Void", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "get_SecurityToken", + "Parameters": [], + "ReturnType": "Microsoft.AspNetCore.Antiforgery.Internal.BinaryBlob", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "set_SecurityToken", + "Parameters": [ + { + "Name": "value", + "Type": "Microsoft.AspNetCore.Antiforgery.Internal.BinaryBlob" + } + ], + "ReturnType": "System.Void", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "get_Username", + "Parameters": [], + "ReturnType": "System.String", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "set_Username", + "Parameters": [ + { + "Name": "value", + "Type": "System.String" + } + ], + "ReturnType": "System.Void", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Constructor", + "Name": ".ctor", + "Parameters": [], + "Visibility": "Public", + "GenericParameter": [] + } + ], + "GenericParameters": [] + }, + { + "Name": "Microsoft.AspNetCore.Antiforgery.Internal.BinaryBlob", + "Visibility": "Public", + "Kind": "Class", + "Sealed": true, + "ImplementedInterfaces": [ + "System.IEquatable" + ], + "Members": [ + { + "Kind": "Method", + "Name": "get_BitLength", + "Parameters": [], + "ReturnType": "System.Int32", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "Equals", + "Parameters": [ + { + "Name": "obj", + "Type": "System.Object" + } + ], + "ReturnType": "System.Boolean", + "Virtual": true, + "Override": true, + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "Equals", + "Parameters": [ + { + "Name": "other", + "Type": "Microsoft.AspNetCore.Antiforgery.Internal.BinaryBlob" + } + ], + "ReturnType": "System.Boolean", + "Sealed": true, + "Virtual": true, + "ImplementedInterface": "System.IEquatable", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "GetData", + "Parameters": [], + "ReturnType": "System.Byte[]", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "GetHashCode", + "Parameters": [], + "ReturnType": "System.Int32", + "Virtual": true, + "Override": true, + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Constructor", + "Name": ".ctor", + "Parameters": [ + { + "Name": "bitLength", + "Type": "System.Int32" + } + ], + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Constructor", + "Name": ".ctor", + "Parameters": [ + { + "Name": "bitLength", + "Type": "System.Int32" + }, + { + "Name": "data", + "Type": "System.Byte[]" + } + ], + "Visibility": "Public", + "GenericParameter": [] + } + ], + "GenericParameters": [] + }, + { + "Name": "Microsoft.AspNetCore.Antiforgery.Internal.DefaultAntiforgery", + "Visibility": "Public", + "Kind": "Class", + "ImplementedInterfaces": [ + "Microsoft.AspNetCore.Antiforgery.IAntiforgery" + ], + "Members": [ + { + "Kind": "Method", + "Name": "GetAndStoreTokens", + "Parameters": [ + { + "Name": "httpContext", + "Type": "Microsoft.AspNetCore.Http.HttpContext" + } + ], + "ReturnType": "Microsoft.AspNetCore.Antiforgery.AntiforgeryTokenSet", + "Sealed": true, + "Virtual": true, + "ImplementedInterface": "Microsoft.AspNetCore.Antiforgery.IAntiforgery", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "GetTokens", + "Parameters": [ + { + "Name": "httpContext", + "Type": "Microsoft.AspNetCore.Http.HttpContext" + } + ], + "ReturnType": "Microsoft.AspNetCore.Antiforgery.AntiforgeryTokenSet", + "Sealed": true, + "Virtual": true, + "ImplementedInterface": "Microsoft.AspNetCore.Antiforgery.IAntiforgery", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "IsRequestValidAsync", + "Parameters": [ + { + "Name": "httpContext", + "Type": "Microsoft.AspNetCore.Http.HttpContext" + } + ], + "ReturnType": "System.Threading.Tasks.Task", + "Sealed": true, + "Virtual": true, + "ImplementedInterface": "Microsoft.AspNetCore.Antiforgery.IAntiforgery", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "ValidateRequestAsync", + "Parameters": [ + { + "Name": "httpContext", + "Type": "Microsoft.AspNetCore.Http.HttpContext" + } + ], + "ReturnType": "System.Threading.Tasks.Task", + "Sealed": true, + "Virtual": true, + "ImplementedInterface": "Microsoft.AspNetCore.Antiforgery.IAntiforgery", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "SetCookieTokenAndHeader", + "Parameters": [ + { + "Name": "httpContext", + "Type": "Microsoft.AspNetCore.Http.HttpContext" + } + ], + "ReturnType": "System.Void", + "Sealed": true, + "Virtual": true, + "ImplementedInterface": "Microsoft.AspNetCore.Antiforgery.IAntiforgery", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Constructor", + "Name": ".ctor", + "Parameters": [ + { + "Name": "antiforgeryOptionsAccessor", + "Type": "Microsoft.Extensions.Options.IOptions" + }, + { + "Name": "tokenGenerator", + "Type": "Microsoft.AspNetCore.Antiforgery.Internal.IAntiforgeryTokenGenerator" + }, + { + "Name": "tokenSerializer", + "Type": "Microsoft.AspNetCore.Antiforgery.Internal.IAntiforgeryTokenSerializer" + }, + { + "Name": "tokenStore", + "Type": "Microsoft.AspNetCore.Antiforgery.Internal.IAntiforgeryTokenStore" + }, + { + "Name": "loggerFactory", + "Type": "Microsoft.Extensions.Logging.ILoggerFactory" + } + ], + "Visibility": "Public", + "GenericParameter": [] + } + ], + "GenericParameters": [] + }, + { + "Name": "Microsoft.AspNetCore.Antiforgery.Internal.DefaultAntiforgeryAdditionalDataProvider", + "Visibility": "Public", + "Kind": "Class", + "ImplementedInterfaces": [ + "Microsoft.AspNetCore.Antiforgery.IAntiforgeryAdditionalDataProvider" + ], + "Members": [ + { + "Kind": "Method", + "Name": "GetAdditionalData", + "Parameters": [ + { + "Name": "context", + "Type": "Microsoft.AspNetCore.Http.HttpContext" + } + ], + "ReturnType": "System.String", + "Virtual": true, + "ImplementedInterface": "Microsoft.AspNetCore.Antiforgery.IAntiforgeryAdditionalDataProvider", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "ValidateAdditionalData", + "Parameters": [ + { + "Name": "context", + "Type": "Microsoft.AspNetCore.Http.HttpContext" + }, + { + "Name": "additionalData", + "Type": "System.String" + } + ], + "ReturnType": "System.Boolean", + "Virtual": true, + "ImplementedInterface": "Microsoft.AspNetCore.Antiforgery.IAntiforgeryAdditionalDataProvider", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Constructor", + "Name": ".ctor", + "Parameters": [], + "Visibility": "Public", + "GenericParameter": [] + } + ], + "GenericParameters": [] + }, + { + "Name": "Microsoft.AspNetCore.Antiforgery.Internal.DefaultAntiforgeryTokenGenerator", + "Visibility": "Public", + "Kind": "Class", + "ImplementedInterfaces": [ + "Microsoft.AspNetCore.Antiforgery.Internal.IAntiforgeryTokenGenerator" + ], + "Members": [ + { + "Kind": "Method", + "Name": "GenerateCookieToken", + "Parameters": [], + "ReturnType": "Microsoft.AspNetCore.Antiforgery.Internal.AntiforgeryToken", + "Sealed": true, + "Virtual": true, + "ImplementedInterface": "Microsoft.AspNetCore.Antiforgery.Internal.IAntiforgeryTokenGenerator", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "GenerateRequestToken", + "Parameters": [ + { + "Name": "httpContext", + "Type": "Microsoft.AspNetCore.Http.HttpContext" + }, + { + "Name": "cookieToken", + "Type": "Microsoft.AspNetCore.Antiforgery.Internal.AntiforgeryToken" + } + ], + "ReturnType": "Microsoft.AspNetCore.Antiforgery.Internal.AntiforgeryToken", + "Sealed": true, + "Virtual": true, + "ImplementedInterface": "Microsoft.AspNetCore.Antiforgery.Internal.IAntiforgeryTokenGenerator", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "IsCookieTokenValid", + "Parameters": [ + { + "Name": "cookieToken", + "Type": "Microsoft.AspNetCore.Antiforgery.Internal.AntiforgeryToken" + } + ], + "ReturnType": "System.Boolean", + "Sealed": true, + "Virtual": true, + "ImplementedInterface": "Microsoft.AspNetCore.Antiforgery.Internal.IAntiforgeryTokenGenerator", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "TryValidateTokenSet", + "Parameters": [ + { + "Name": "httpContext", + "Type": "Microsoft.AspNetCore.Http.HttpContext" + }, + { + "Name": "cookieToken", + "Type": "Microsoft.AspNetCore.Antiforgery.Internal.AntiforgeryToken" + }, + { + "Name": "requestToken", + "Type": "Microsoft.AspNetCore.Antiforgery.Internal.AntiforgeryToken" + }, + { + "Name": "message", + "Type": "System.String", + "Direction": "Out" + } + ], + "ReturnType": "System.Boolean", + "Sealed": true, + "Virtual": true, + "ImplementedInterface": "Microsoft.AspNetCore.Antiforgery.Internal.IAntiforgeryTokenGenerator", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Constructor", + "Name": ".ctor", + "Parameters": [ + { + "Name": "claimUidExtractor", + "Type": "Microsoft.AspNetCore.Antiforgery.Internal.IClaimUidExtractor" + }, + { + "Name": "additionalDataProvider", + "Type": "Microsoft.AspNetCore.Antiforgery.IAntiforgeryAdditionalDataProvider" + } + ], + "Visibility": "Public", + "GenericParameter": [] + } + ], + "GenericParameters": [] + }, + { + "Name": "Microsoft.AspNetCore.Antiforgery.Internal.DefaultAntiforgeryTokenSerializer", + "Visibility": "Public", + "Kind": "Class", + "ImplementedInterfaces": [ + "Microsoft.AspNetCore.Antiforgery.Internal.IAntiforgeryTokenSerializer" + ], + "Members": [ + { + "Kind": "Method", + "Name": "Deserialize", + "Parameters": [ + { + "Name": "serializedToken", + "Type": "System.String" + } + ], + "ReturnType": "Microsoft.AspNetCore.Antiforgery.Internal.AntiforgeryToken", + "Sealed": true, + "Virtual": true, + "ImplementedInterface": "Microsoft.AspNetCore.Antiforgery.Internal.IAntiforgeryTokenSerializer", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "Serialize", + "Parameters": [ + { + "Name": "token", + "Type": "Microsoft.AspNetCore.Antiforgery.Internal.AntiforgeryToken" + } + ], + "ReturnType": "System.String", + "Sealed": true, + "Virtual": true, + "ImplementedInterface": "Microsoft.AspNetCore.Antiforgery.Internal.IAntiforgeryTokenSerializer", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Constructor", + "Name": ".ctor", + "Parameters": [ + { + "Name": "provider", + "Type": "Microsoft.AspNetCore.DataProtection.IDataProtectionProvider" + }, + { + "Name": "pool", + "Type": "Microsoft.Extensions.ObjectPool.ObjectPool" + } + ], + "Visibility": "Public", + "GenericParameter": [] + } + ], + "GenericParameters": [] + }, + { + "Name": "Microsoft.AspNetCore.Antiforgery.Internal.DefaultAntiforgeryTokenStore", + "Visibility": "Public", + "Kind": "Class", + "ImplementedInterfaces": [ + "Microsoft.AspNetCore.Antiforgery.Internal.IAntiforgeryTokenStore" + ], + "Members": [ + { + "Kind": "Method", + "Name": "GetCookieToken", + "Parameters": [ + { + "Name": "httpContext", + "Type": "Microsoft.AspNetCore.Http.HttpContext" + } + ], + "ReturnType": "System.String", + "Sealed": true, + "Virtual": true, + "ImplementedInterface": "Microsoft.AspNetCore.Antiforgery.Internal.IAntiforgeryTokenStore", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "GetRequestTokensAsync", + "Parameters": [ + { + "Name": "httpContext", + "Type": "Microsoft.AspNetCore.Http.HttpContext" + } + ], + "ReturnType": "System.Threading.Tasks.Task", + "Sealed": true, + "Virtual": true, + "ImplementedInterface": "Microsoft.AspNetCore.Antiforgery.Internal.IAntiforgeryTokenStore", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "SaveCookieToken", + "Parameters": [ + { + "Name": "httpContext", + "Type": "Microsoft.AspNetCore.Http.HttpContext" + }, + { + "Name": "token", + "Type": "System.String" + } + ], + "ReturnType": "System.Void", + "Sealed": true, + "Virtual": true, + "ImplementedInterface": "Microsoft.AspNetCore.Antiforgery.Internal.IAntiforgeryTokenStore", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Constructor", + "Name": ".ctor", + "Parameters": [ + { + "Name": "optionsAccessor", + "Type": "Microsoft.Extensions.Options.IOptions" + } + ], + "Visibility": "Public", + "GenericParameter": [] + } + ], + "GenericParameters": [] + }, + { + "Name": "Microsoft.AspNetCore.Antiforgery.Internal.DefaultClaimUidExtractor", + "Visibility": "Public", + "Kind": "Class", + "ImplementedInterfaces": [ + "Microsoft.AspNetCore.Antiforgery.Internal.IClaimUidExtractor" + ], + "Members": [ + { + "Kind": "Method", + "Name": "ExtractClaimUid", + "Parameters": [ + { + "Name": "claimsPrincipal", + "Type": "System.Security.Claims.ClaimsPrincipal" + } + ], + "ReturnType": "System.String", + "Sealed": true, + "Virtual": true, + "ImplementedInterface": "Microsoft.AspNetCore.Antiforgery.Internal.IClaimUidExtractor", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "GetUniqueIdentifierParameters", + "Parameters": [ + { + "Name": "claimsIdentities", + "Type": "System.Collections.Generic.IEnumerable" + } + ], + "ReturnType": "System.Collections.Generic.IList", + "Static": true, + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Constructor", + "Name": ".ctor", + "Parameters": [ + { + "Name": "pool", + "Type": "Microsoft.Extensions.ObjectPool.ObjectPool" + } + ], + "Visibility": "Public", + "GenericParameter": [] + } + ], + "GenericParameters": [] + }, + { + "Name": "Microsoft.AspNetCore.Antiforgery.Internal.IAntiforgeryFeature", + "Visibility": "Public", + "Kind": "Interface", + "Abstract": true, + "ImplementedInterfaces": [], + "Members": [ + { + "Kind": "Method", + "Name": "get_CookieToken", + "Parameters": [], + "ReturnType": "Microsoft.AspNetCore.Antiforgery.Internal.AntiforgeryToken", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "set_CookieToken", + "Parameters": [ + { + "Name": "value", + "Type": "Microsoft.AspNetCore.Antiforgery.Internal.AntiforgeryToken" + } + ], + "ReturnType": "System.Void", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "get_HaveDeserializedCookieToken", + "Parameters": [], + "ReturnType": "System.Boolean", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "set_HaveDeserializedCookieToken", + "Parameters": [ + { + "Name": "value", + "Type": "System.Boolean" + } + ], + "ReturnType": "System.Void", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "get_HaveDeserializedRequestToken", + "Parameters": [], + "ReturnType": "System.Boolean", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "set_HaveDeserializedRequestToken", + "Parameters": [ + { + "Name": "value", + "Type": "System.Boolean" + } + ], + "ReturnType": "System.Void", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "get_HaveGeneratedNewCookieToken", + "Parameters": [], + "ReturnType": "System.Boolean", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "set_HaveGeneratedNewCookieToken", + "Parameters": [ + { + "Name": "value", + "Type": "System.Boolean" + } + ], + "ReturnType": "System.Void", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "get_HaveStoredNewCookieToken", + "Parameters": [], + "ReturnType": "System.Boolean", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "set_HaveStoredNewCookieToken", + "Parameters": [ + { + "Name": "value", + "Type": "System.Boolean" + } + ], + "ReturnType": "System.Void", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "get_NewCookieToken", + "Parameters": [], + "ReturnType": "Microsoft.AspNetCore.Antiforgery.Internal.AntiforgeryToken", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "set_NewCookieToken", + "Parameters": [ + { + "Name": "value", + "Type": "Microsoft.AspNetCore.Antiforgery.Internal.AntiforgeryToken" + } + ], + "ReturnType": "System.Void", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "get_NewCookieTokenString", + "Parameters": [], + "ReturnType": "System.String", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "set_NewCookieTokenString", + "Parameters": [ + { + "Name": "value", + "Type": "System.String" + } + ], + "ReturnType": "System.Void", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "get_NewRequestToken", + "Parameters": [], + "ReturnType": "Microsoft.AspNetCore.Antiforgery.Internal.AntiforgeryToken", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "set_NewRequestToken", + "Parameters": [ + { + "Name": "value", + "Type": "Microsoft.AspNetCore.Antiforgery.Internal.AntiforgeryToken" + } + ], + "ReturnType": "System.Void", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "get_NewRequestTokenString", + "Parameters": [], + "ReturnType": "System.String", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "set_NewRequestTokenString", + "Parameters": [ + { + "Name": "value", + "Type": "System.String" + } + ], + "ReturnType": "System.Void", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "get_RequestToken", + "Parameters": [], + "ReturnType": "Microsoft.AspNetCore.Antiforgery.Internal.AntiforgeryToken", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "set_RequestToken", + "Parameters": [ + { + "Name": "value", + "Type": "Microsoft.AspNetCore.Antiforgery.Internal.AntiforgeryToken" + } + ], + "ReturnType": "System.Void", + "GenericParameter": [] + } + ], + "GenericParameters": [] + }, + { + "Name": "Microsoft.AspNetCore.Antiforgery.Internal.IAntiforgeryTokenGenerator", + "Visibility": "Public", + "Kind": "Interface", + "Abstract": true, + "ImplementedInterfaces": [], + "Members": [ + { + "Kind": "Method", + "Name": "GenerateCookieToken", + "Parameters": [], + "ReturnType": "Microsoft.AspNetCore.Antiforgery.Internal.AntiforgeryToken", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "GenerateRequestToken", + "Parameters": [ + { + "Name": "httpContext", + "Type": "Microsoft.AspNetCore.Http.HttpContext" + }, + { + "Name": "cookieToken", + "Type": "Microsoft.AspNetCore.Antiforgery.Internal.AntiforgeryToken" + } + ], + "ReturnType": "Microsoft.AspNetCore.Antiforgery.Internal.AntiforgeryToken", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "IsCookieTokenValid", + "Parameters": [ + { + "Name": "cookieToken", + "Type": "Microsoft.AspNetCore.Antiforgery.Internal.AntiforgeryToken" + } + ], + "ReturnType": "System.Boolean", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "TryValidateTokenSet", + "Parameters": [ + { + "Name": "httpContext", + "Type": "Microsoft.AspNetCore.Http.HttpContext" + }, + { + "Name": "cookieToken", + "Type": "Microsoft.AspNetCore.Antiforgery.Internal.AntiforgeryToken" + }, + { + "Name": "requestToken", + "Type": "Microsoft.AspNetCore.Antiforgery.Internal.AntiforgeryToken" + }, + { + "Name": "message", + "Type": "System.String", + "Direction": "Out" + } + ], + "ReturnType": "System.Boolean", + "GenericParameter": [] + } + ], + "GenericParameters": [] + }, + { + "Name": "Microsoft.AspNetCore.Antiforgery.Internal.IAntiforgeryTokenSerializer", + "Visibility": "Public", + "Kind": "Interface", + "Abstract": true, + "ImplementedInterfaces": [], + "Members": [ + { + "Kind": "Method", + "Name": "Deserialize", + "Parameters": [ + { + "Name": "serializedToken", + "Type": "System.String" + } + ], + "ReturnType": "Microsoft.AspNetCore.Antiforgery.Internal.AntiforgeryToken", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "Serialize", + "Parameters": [ + { + "Name": "token", + "Type": "Microsoft.AspNetCore.Antiforgery.Internal.AntiforgeryToken" + } + ], + "ReturnType": "System.String", + "GenericParameter": [] + } + ], + "GenericParameters": [] + }, + { + "Name": "Microsoft.AspNetCore.Antiforgery.Internal.IAntiforgeryTokenStore", + "Visibility": "Public", + "Kind": "Interface", + "Abstract": true, + "ImplementedInterfaces": [], + "Members": [ + { + "Kind": "Method", + "Name": "GetCookieToken", + "Parameters": [ + { + "Name": "httpContext", + "Type": "Microsoft.AspNetCore.Http.HttpContext" + } + ], + "ReturnType": "System.String", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "GetRequestTokensAsync", + "Parameters": [ + { + "Name": "httpContext", + "Type": "Microsoft.AspNetCore.Http.HttpContext" + } + ], + "ReturnType": "System.Threading.Tasks.Task", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "SaveCookieToken", + "Parameters": [ + { + "Name": "httpContext", + "Type": "Microsoft.AspNetCore.Http.HttpContext" + }, + { + "Name": "token", + "Type": "System.String" + } + ], + "ReturnType": "System.Void", + "GenericParameter": [] + } + ], + "GenericParameters": [] + }, + { + "Name": "Microsoft.AspNetCore.Antiforgery.Internal.IClaimUidExtractor", + "Visibility": "Public", + "Kind": "Interface", + "Abstract": true, + "ImplementedInterfaces": [], + "Members": [ + { + "Kind": "Method", + "Name": "ExtractClaimUid", + "Parameters": [ + { + "Name": "claimsPrincipal", + "Type": "System.Security.Claims.ClaimsPrincipal" + } + ], + "ReturnType": "System.String", + "GenericParameter": [] + } + ], + "GenericParameters": [] + } + ] +} \ No newline at end of file diff --git a/src/Microsoft.AspNetCore.Antiforgery/baseline.netcore.json b/src/Microsoft.AspNetCore.Antiforgery/baseline.netcore.json new file mode 100644 index 0000000000..9117fb75fd --- /dev/null +++ b/src/Microsoft.AspNetCore.Antiforgery/baseline.netcore.json @@ -0,0 +1,1875 @@ +{ + "AssemblyIdentity": "Microsoft.AspNetCore.Antiforgery, Version=1.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60", + "Types": [ + { + "Name": "Microsoft.Extensions.DependencyInjection.AntiforgeryServiceCollectionExtensions", + "Visibility": "Public", + "Kind": "Class", + "Abstract": true, + "Static": true, + "Sealed": true, + "ImplementedInterfaces": [], + "Members": [ + { + "Kind": "Method", + "Name": "AddAntiforgery", + "Parameters": [ + { + "Name": "services", + "Type": "Microsoft.Extensions.DependencyInjection.IServiceCollection" + } + ], + "ReturnType": "Microsoft.Extensions.DependencyInjection.IServiceCollection", + "Static": true, + "Extension": true, + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "AddAntiforgery", + "Parameters": [ + { + "Name": "services", + "Type": "Microsoft.Extensions.DependencyInjection.IServiceCollection" + }, + { + "Name": "setupAction", + "Type": "System.Action" + } + ], + "ReturnType": "Microsoft.Extensions.DependencyInjection.IServiceCollection", + "Static": true, + "Extension": true, + "Visibility": "Public", + "GenericParameter": [] + } + ], + "GenericParameters": [] + }, + { + "Name": "Microsoft.AspNetCore.Antiforgery.AntiforgeryOptions", + "Visibility": "Public", + "Kind": "Class", + "ImplementedInterfaces": [], + "Members": [ + { + "Kind": "Method", + "Name": "get_CookieName", + "Parameters": [], + "ReturnType": "System.String", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "set_CookieName", + "Parameters": [ + { + "Name": "value", + "Type": "System.String" + } + ], + "ReturnType": "System.Void", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "get_FormFieldName", + "Parameters": [], + "ReturnType": "System.String", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "set_FormFieldName", + "Parameters": [ + { + "Name": "value", + "Type": "System.String" + } + ], + "ReturnType": "System.Void", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "get_HeaderName", + "Parameters": [], + "ReturnType": "System.String", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "set_HeaderName", + "Parameters": [ + { + "Name": "value", + "Type": "System.String" + } + ], + "ReturnType": "System.Void", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "get_RequireSsl", + "Parameters": [], + "ReturnType": "System.Boolean", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "set_RequireSsl", + "Parameters": [ + { + "Name": "value", + "Type": "System.Boolean" + } + ], + "ReturnType": "System.Void", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "get_SuppressXFrameOptionsHeader", + "Parameters": [], + "ReturnType": "System.Boolean", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "set_SuppressXFrameOptionsHeader", + "Parameters": [ + { + "Name": "value", + "Type": "System.Boolean" + } + ], + "ReturnType": "System.Void", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Constructor", + "Name": ".ctor", + "Parameters": [], + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Field", + "Name": "DefaultCookiePrefix", + "Parameters": [], + "ReturnType": "System.String", + "Static": true, + "ReadOnly": true, + "Visibility": "Public", + "GenericParameter": [] + } + ], + "GenericParameters": [] + }, + { + "Name": "Microsoft.AspNetCore.Antiforgery.AntiforgeryTokenSet", + "Visibility": "Public", + "Kind": "Class", + "ImplementedInterfaces": [], + "Members": [ + { + "Kind": "Method", + "Name": "get_RequestToken", + "Parameters": [], + "ReturnType": "System.String", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "get_FormFieldName", + "Parameters": [], + "ReturnType": "System.String", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "get_HeaderName", + "Parameters": [], + "ReturnType": "System.String", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "get_CookieToken", + "Parameters": [], + "ReturnType": "System.String", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Constructor", + "Name": ".ctor", + "Parameters": [ + { + "Name": "requestToken", + "Type": "System.String" + }, + { + "Name": "cookieToken", + "Type": "System.String" + }, + { + "Name": "formFieldName", + "Type": "System.String" + }, + { + "Name": "headerName", + "Type": "System.String" + } + ], + "Visibility": "Public", + "GenericParameter": [] + } + ], + "GenericParameters": [] + }, + { + "Name": "Microsoft.AspNetCore.Antiforgery.AntiforgeryValidationException", + "Visibility": "Public", + "Kind": "Class", + "BaseType": "System.Exception", + "ImplementedInterfaces": [], + "Members": [ + { + "Kind": "Constructor", + "Name": ".ctor", + "Parameters": [ + { + "Name": "message", + "Type": "System.String" + } + ], + "Visibility": "Public", + "GenericParameter": [] + } + ], + "GenericParameters": [] + }, + { + "Name": "Microsoft.AspNetCore.Antiforgery.IAntiforgery", + "Visibility": "Public", + "Kind": "Interface", + "Abstract": true, + "ImplementedInterfaces": [], + "Members": [ + { + "Kind": "Method", + "Name": "GetAndStoreTokens", + "Parameters": [ + { + "Name": "httpContext", + "Type": "Microsoft.AspNetCore.Http.HttpContext" + } + ], + "ReturnType": "Microsoft.AspNetCore.Antiforgery.AntiforgeryTokenSet", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "GetTokens", + "Parameters": [ + { + "Name": "httpContext", + "Type": "Microsoft.AspNetCore.Http.HttpContext" + } + ], + "ReturnType": "Microsoft.AspNetCore.Antiforgery.AntiforgeryTokenSet", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "IsRequestValidAsync", + "Parameters": [ + { + "Name": "httpContext", + "Type": "Microsoft.AspNetCore.Http.HttpContext" + } + ], + "ReturnType": "System.Threading.Tasks.Task", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "ValidateRequestAsync", + "Parameters": [ + { + "Name": "httpContext", + "Type": "Microsoft.AspNetCore.Http.HttpContext" + } + ], + "ReturnType": "System.Threading.Tasks.Task", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "SetCookieTokenAndHeader", + "Parameters": [ + { + "Name": "httpContext", + "Type": "Microsoft.AspNetCore.Http.HttpContext" + } + ], + "ReturnType": "System.Void", + "GenericParameter": [] + } + ], + "GenericParameters": [] + }, + { + "Name": "Microsoft.AspNetCore.Antiforgery.IAntiforgeryAdditionalDataProvider", + "Visibility": "Public", + "Kind": "Interface", + "Abstract": true, + "ImplementedInterfaces": [], + "Members": [ + { + "Kind": "Method", + "Name": "GetAdditionalData", + "Parameters": [ + { + "Name": "context", + "Type": "Microsoft.AspNetCore.Http.HttpContext" + } + ], + "ReturnType": "System.String", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "ValidateAdditionalData", + "Parameters": [ + { + "Name": "context", + "Type": "Microsoft.AspNetCore.Http.HttpContext" + }, + { + "Name": "additionalData", + "Type": "System.String" + } + ], + "ReturnType": "System.Boolean", + "GenericParameter": [] + } + ], + "GenericParameters": [] + }, + { + "Name": "Microsoft.AspNetCore.Antiforgery.Internal.AntiforgeryFeature", + "Visibility": "Public", + "Kind": "Class", + "ImplementedInterfaces": [ + "Microsoft.AspNetCore.Antiforgery.Internal.IAntiforgeryFeature" + ], + "Members": [ + { + "Kind": "Method", + "Name": "get_HaveDeserializedCookieToken", + "Parameters": [], + "ReturnType": "System.Boolean", + "Sealed": true, + "Virtual": true, + "ImplementedInterface": "Microsoft.AspNetCore.Antiforgery.Internal.IAntiforgeryFeature", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "set_HaveDeserializedCookieToken", + "Parameters": [ + { + "Name": "value", + "Type": "System.Boolean" + } + ], + "ReturnType": "System.Void", + "Sealed": true, + "Virtual": true, + "ImplementedInterface": "Microsoft.AspNetCore.Antiforgery.Internal.IAntiforgeryFeature", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "get_CookieToken", + "Parameters": [], + "ReturnType": "Microsoft.AspNetCore.Antiforgery.Internal.AntiforgeryToken", + "Sealed": true, + "Virtual": true, + "ImplementedInterface": "Microsoft.AspNetCore.Antiforgery.Internal.IAntiforgeryFeature", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "set_CookieToken", + "Parameters": [ + { + "Name": "value", + "Type": "Microsoft.AspNetCore.Antiforgery.Internal.AntiforgeryToken" + } + ], + "ReturnType": "System.Void", + "Sealed": true, + "Virtual": true, + "ImplementedInterface": "Microsoft.AspNetCore.Antiforgery.Internal.IAntiforgeryFeature", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "get_HaveDeserializedRequestToken", + "Parameters": [], + "ReturnType": "System.Boolean", + "Sealed": true, + "Virtual": true, + "ImplementedInterface": "Microsoft.AspNetCore.Antiforgery.Internal.IAntiforgeryFeature", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "set_HaveDeserializedRequestToken", + "Parameters": [ + { + "Name": "value", + "Type": "System.Boolean" + } + ], + "ReturnType": "System.Void", + "Sealed": true, + "Virtual": true, + "ImplementedInterface": "Microsoft.AspNetCore.Antiforgery.Internal.IAntiforgeryFeature", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "get_RequestToken", + "Parameters": [], + "ReturnType": "Microsoft.AspNetCore.Antiforgery.Internal.AntiforgeryToken", + "Sealed": true, + "Virtual": true, + "ImplementedInterface": "Microsoft.AspNetCore.Antiforgery.Internal.IAntiforgeryFeature", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "set_RequestToken", + "Parameters": [ + { + "Name": "value", + "Type": "Microsoft.AspNetCore.Antiforgery.Internal.AntiforgeryToken" + } + ], + "ReturnType": "System.Void", + "Sealed": true, + "Virtual": true, + "ImplementedInterface": "Microsoft.AspNetCore.Antiforgery.Internal.IAntiforgeryFeature", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "get_HaveGeneratedNewCookieToken", + "Parameters": [], + "ReturnType": "System.Boolean", + "Sealed": true, + "Virtual": true, + "ImplementedInterface": "Microsoft.AspNetCore.Antiforgery.Internal.IAntiforgeryFeature", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "set_HaveGeneratedNewCookieToken", + "Parameters": [ + { + "Name": "value", + "Type": "System.Boolean" + } + ], + "ReturnType": "System.Void", + "Sealed": true, + "Virtual": true, + "ImplementedInterface": "Microsoft.AspNetCore.Antiforgery.Internal.IAntiforgeryFeature", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "get_NewCookieToken", + "Parameters": [], + "ReturnType": "Microsoft.AspNetCore.Antiforgery.Internal.AntiforgeryToken", + "Sealed": true, + "Virtual": true, + "ImplementedInterface": "Microsoft.AspNetCore.Antiforgery.Internal.IAntiforgeryFeature", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "set_NewCookieToken", + "Parameters": [ + { + "Name": "value", + "Type": "Microsoft.AspNetCore.Antiforgery.Internal.AntiforgeryToken" + } + ], + "ReturnType": "System.Void", + "Sealed": true, + "Virtual": true, + "ImplementedInterface": "Microsoft.AspNetCore.Antiforgery.Internal.IAntiforgeryFeature", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "get_NewCookieTokenString", + "Parameters": [], + "ReturnType": "System.String", + "Sealed": true, + "Virtual": true, + "ImplementedInterface": "Microsoft.AspNetCore.Antiforgery.Internal.IAntiforgeryFeature", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "set_NewCookieTokenString", + "Parameters": [ + { + "Name": "value", + "Type": "System.String" + } + ], + "ReturnType": "System.Void", + "Sealed": true, + "Virtual": true, + "ImplementedInterface": "Microsoft.AspNetCore.Antiforgery.Internal.IAntiforgeryFeature", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "get_NewRequestToken", + "Parameters": [], + "ReturnType": "Microsoft.AspNetCore.Antiforgery.Internal.AntiforgeryToken", + "Sealed": true, + "Virtual": true, + "ImplementedInterface": "Microsoft.AspNetCore.Antiforgery.Internal.IAntiforgeryFeature", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "set_NewRequestToken", + "Parameters": [ + { + "Name": "value", + "Type": "Microsoft.AspNetCore.Antiforgery.Internal.AntiforgeryToken" + } + ], + "ReturnType": "System.Void", + "Sealed": true, + "Virtual": true, + "ImplementedInterface": "Microsoft.AspNetCore.Antiforgery.Internal.IAntiforgeryFeature", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "get_NewRequestTokenString", + "Parameters": [], + "ReturnType": "System.String", + "Sealed": true, + "Virtual": true, + "ImplementedInterface": "Microsoft.AspNetCore.Antiforgery.Internal.IAntiforgeryFeature", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "set_NewRequestTokenString", + "Parameters": [ + { + "Name": "value", + "Type": "System.String" + } + ], + "ReturnType": "System.Void", + "Sealed": true, + "Virtual": true, + "ImplementedInterface": "Microsoft.AspNetCore.Antiforgery.Internal.IAntiforgeryFeature", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "get_HaveStoredNewCookieToken", + "Parameters": [], + "ReturnType": "System.Boolean", + "Sealed": true, + "Virtual": true, + "ImplementedInterface": "Microsoft.AspNetCore.Antiforgery.Internal.IAntiforgeryFeature", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "set_HaveStoredNewCookieToken", + "Parameters": [ + { + "Name": "value", + "Type": "System.Boolean" + } + ], + "ReturnType": "System.Void", + "Sealed": true, + "Virtual": true, + "ImplementedInterface": "Microsoft.AspNetCore.Antiforgery.Internal.IAntiforgeryFeature", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Constructor", + "Name": ".ctor", + "Parameters": [], + "Visibility": "Public", + "GenericParameter": [] + } + ], + "GenericParameters": [] + }, + { + "Name": "Microsoft.AspNetCore.Antiforgery.Internal.AntiforgeryOptionsSetup", + "Visibility": "Public", + "Kind": "Class", + "BaseType": "Microsoft.Extensions.Options.ConfigureOptions", + "ImplementedInterfaces": [], + "Members": [ + { + "Kind": "Method", + "Name": "ConfigureOptions", + "Parameters": [ + { + "Name": "options", + "Type": "Microsoft.AspNetCore.Antiforgery.AntiforgeryOptions" + }, + { + "Name": "dataProtectionOptions", + "Type": "Microsoft.AspNetCore.DataProtection.DataProtectionOptions" + } + ], + "ReturnType": "System.Void", + "Static": true, + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Constructor", + "Name": ".ctor", + "Parameters": [ + { + "Name": "dataProtectionOptionsAccessor", + "Type": "Microsoft.Extensions.Options.IOptions" + } + ], + "Visibility": "Public", + "GenericParameter": [] + } + ], + "GenericParameters": [] + }, + { + "Name": "Microsoft.AspNetCore.Antiforgery.Internal.AntiforgerySerializationContext", + "Visibility": "Public", + "Kind": "Class", + "ImplementedInterfaces": [], + "Members": [ + { + "Kind": "Method", + "Name": "get_Stream", + "Parameters": [], + "ReturnType": "System.IO.MemoryStream", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "get_Reader", + "Parameters": [], + "ReturnType": "System.IO.BinaryReader", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "get_Writer", + "Parameters": [], + "ReturnType": "System.IO.BinaryWriter", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "get_Sha256", + "Parameters": [], + "ReturnType": "System.Security.Cryptography.SHA256", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "GetChars", + "Parameters": [ + { + "Name": "count", + "Type": "System.Int32" + } + ], + "ReturnType": "System.Char[]", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "Reset", + "Parameters": [], + "ReturnType": "System.Void", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Constructor", + "Name": ".ctor", + "Parameters": [], + "Visibility": "Public", + "GenericParameter": [] + } + ], + "GenericParameters": [] + }, + { + "Name": "Microsoft.AspNetCore.Antiforgery.Internal.AntiforgerySerializationContextPooledObjectPolicy", + "Visibility": "Public", + "Kind": "Class", + "ImplementedInterfaces": [ + "Microsoft.Extensions.ObjectPool.IPooledObjectPolicy" + ], + "Members": [ + { + "Kind": "Method", + "Name": "Create", + "Parameters": [], + "ReturnType": "Microsoft.AspNetCore.Antiforgery.Internal.AntiforgerySerializationContext", + "Sealed": true, + "Virtual": true, + "ImplementedInterface": "Microsoft.Extensions.ObjectPool.IPooledObjectPolicy", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "Return", + "Parameters": [ + { + "Name": "obj", + "Type": "Microsoft.AspNetCore.Antiforgery.Internal.AntiforgerySerializationContext" + } + ], + "ReturnType": "System.Boolean", + "Sealed": true, + "Virtual": true, + "ImplementedInterface": "Microsoft.Extensions.ObjectPool.IPooledObjectPolicy", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Constructor", + "Name": ".ctor", + "Parameters": [], + "Visibility": "Public", + "GenericParameter": [] + } + ], + "GenericParameters": [] + }, + { + "Name": "Microsoft.AspNetCore.Antiforgery.Internal.AntiforgeryToken", + "Visibility": "Public", + "Kind": "Class", + "Sealed": true, + "ImplementedInterfaces": [], + "Members": [ + { + "Kind": "Method", + "Name": "get_AdditionalData", + "Parameters": [], + "ReturnType": "System.String", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "set_AdditionalData", + "Parameters": [ + { + "Name": "value", + "Type": "System.String" + } + ], + "ReturnType": "System.Void", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "get_ClaimUid", + "Parameters": [], + "ReturnType": "Microsoft.AspNetCore.Antiforgery.Internal.BinaryBlob", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "set_ClaimUid", + "Parameters": [ + { + "Name": "value", + "Type": "Microsoft.AspNetCore.Antiforgery.Internal.BinaryBlob" + } + ], + "ReturnType": "System.Void", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "get_IsCookieToken", + "Parameters": [], + "ReturnType": "System.Boolean", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "set_IsCookieToken", + "Parameters": [ + { + "Name": "value", + "Type": "System.Boolean" + } + ], + "ReturnType": "System.Void", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "get_SecurityToken", + "Parameters": [], + "ReturnType": "Microsoft.AspNetCore.Antiforgery.Internal.BinaryBlob", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "set_SecurityToken", + "Parameters": [ + { + "Name": "value", + "Type": "Microsoft.AspNetCore.Antiforgery.Internal.BinaryBlob" + } + ], + "ReturnType": "System.Void", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "get_Username", + "Parameters": [], + "ReturnType": "System.String", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "set_Username", + "Parameters": [ + { + "Name": "value", + "Type": "System.String" + } + ], + "ReturnType": "System.Void", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Constructor", + "Name": ".ctor", + "Parameters": [], + "Visibility": "Public", + "GenericParameter": [] + } + ], + "GenericParameters": [] + }, + { + "Name": "Microsoft.AspNetCore.Antiforgery.Internal.BinaryBlob", + "Visibility": "Public", + "Kind": "Class", + "Sealed": true, + "ImplementedInterfaces": [ + "System.IEquatable" + ], + "Members": [ + { + "Kind": "Method", + "Name": "get_BitLength", + "Parameters": [], + "ReturnType": "System.Int32", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "Equals", + "Parameters": [ + { + "Name": "obj", + "Type": "System.Object" + } + ], + "ReturnType": "System.Boolean", + "Virtual": true, + "Override": true, + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "Equals", + "Parameters": [ + { + "Name": "other", + "Type": "Microsoft.AspNetCore.Antiforgery.Internal.BinaryBlob" + } + ], + "ReturnType": "System.Boolean", + "Sealed": true, + "Virtual": true, + "ImplementedInterface": "System.IEquatable", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "GetData", + "Parameters": [], + "ReturnType": "System.Byte[]", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "GetHashCode", + "Parameters": [], + "ReturnType": "System.Int32", + "Virtual": true, + "Override": true, + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Constructor", + "Name": ".ctor", + "Parameters": [ + { + "Name": "bitLength", + "Type": "System.Int32" + } + ], + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Constructor", + "Name": ".ctor", + "Parameters": [ + { + "Name": "bitLength", + "Type": "System.Int32" + }, + { + "Name": "data", + "Type": "System.Byte[]" + } + ], + "Visibility": "Public", + "GenericParameter": [] + } + ], + "GenericParameters": [] + }, + { + "Name": "Microsoft.AspNetCore.Antiforgery.Internal.DefaultAntiforgery", + "Visibility": "Public", + "Kind": "Class", + "ImplementedInterfaces": [ + "Microsoft.AspNetCore.Antiforgery.IAntiforgery" + ], + "Members": [ + { + "Kind": "Method", + "Name": "GetAndStoreTokens", + "Parameters": [ + { + "Name": "httpContext", + "Type": "Microsoft.AspNetCore.Http.HttpContext" + } + ], + "ReturnType": "Microsoft.AspNetCore.Antiforgery.AntiforgeryTokenSet", + "Sealed": true, + "Virtual": true, + "ImplementedInterface": "Microsoft.AspNetCore.Antiforgery.IAntiforgery", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "GetTokens", + "Parameters": [ + { + "Name": "httpContext", + "Type": "Microsoft.AspNetCore.Http.HttpContext" + } + ], + "ReturnType": "Microsoft.AspNetCore.Antiforgery.AntiforgeryTokenSet", + "Sealed": true, + "Virtual": true, + "ImplementedInterface": "Microsoft.AspNetCore.Antiforgery.IAntiforgery", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "IsRequestValidAsync", + "Parameters": [ + { + "Name": "httpContext", + "Type": "Microsoft.AspNetCore.Http.HttpContext" + } + ], + "ReturnType": "System.Threading.Tasks.Task", + "Sealed": true, + "Virtual": true, + "ImplementedInterface": "Microsoft.AspNetCore.Antiforgery.IAntiforgery", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "ValidateRequestAsync", + "Parameters": [ + { + "Name": "httpContext", + "Type": "Microsoft.AspNetCore.Http.HttpContext" + } + ], + "ReturnType": "System.Threading.Tasks.Task", + "Sealed": true, + "Virtual": true, + "ImplementedInterface": "Microsoft.AspNetCore.Antiforgery.IAntiforgery", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "SetCookieTokenAndHeader", + "Parameters": [ + { + "Name": "httpContext", + "Type": "Microsoft.AspNetCore.Http.HttpContext" + } + ], + "ReturnType": "System.Void", + "Sealed": true, + "Virtual": true, + "ImplementedInterface": "Microsoft.AspNetCore.Antiforgery.IAntiforgery", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Constructor", + "Name": ".ctor", + "Parameters": [ + { + "Name": "antiforgeryOptionsAccessor", + "Type": "Microsoft.Extensions.Options.IOptions" + }, + { + "Name": "tokenGenerator", + "Type": "Microsoft.AspNetCore.Antiforgery.Internal.IAntiforgeryTokenGenerator" + }, + { + "Name": "tokenSerializer", + "Type": "Microsoft.AspNetCore.Antiforgery.Internal.IAntiforgeryTokenSerializer" + }, + { + "Name": "tokenStore", + "Type": "Microsoft.AspNetCore.Antiforgery.Internal.IAntiforgeryTokenStore" + }, + { + "Name": "loggerFactory", + "Type": "Microsoft.Extensions.Logging.ILoggerFactory" + } + ], + "Visibility": "Public", + "GenericParameter": [] + } + ], + "GenericParameters": [] + }, + { + "Name": "Microsoft.AspNetCore.Antiforgery.Internal.DefaultAntiforgeryAdditionalDataProvider", + "Visibility": "Public", + "Kind": "Class", + "ImplementedInterfaces": [ + "Microsoft.AspNetCore.Antiforgery.IAntiforgeryAdditionalDataProvider" + ], + "Members": [ + { + "Kind": "Method", + "Name": "GetAdditionalData", + "Parameters": [ + { + "Name": "context", + "Type": "Microsoft.AspNetCore.Http.HttpContext" + } + ], + "ReturnType": "System.String", + "Virtual": true, + "ImplementedInterface": "Microsoft.AspNetCore.Antiforgery.IAntiforgeryAdditionalDataProvider", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "ValidateAdditionalData", + "Parameters": [ + { + "Name": "context", + "Type": "Microsoft.AspNetCore.Http.HttpContext" + }, + { + "Name": "additionalData", + "Type": "System.String" + } + ], + "ReturnType": "System.Boolean", + "Virtual": true, + "ImplementedInterface": "Microsoft.AspNetCore.Antiforgery.IAntiforgeryAdditionalDataProvider", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Constructor", + "Name": ".ctor", + "Parameters": [], + "Visibility": "Public", + "GenericParameter": [] + } + ], + "GenericParameters": [] + }, + { + "Name": "Microsoft.AspNetCore.Antiforgery.Internal.DefaultAntiforgeryTokenGenerator", + "Visibility": "Public", + "Kind": "Class", + "ImplementedInterfaces": [ + "Microsoft.AspNetCore.Antiforgery.Internal.IAntiforgeryTokenGenerator" + ], + "Members": [ + { + "Kind": "Method", + "Name": "GenerateCookieToken", + "Parameters": [], + "ReturnType": "Microsoft.AspNetCore.Antiforgery.Internal.AntiforgeryToken", + "Sealed": true, + "Virtual": true, + "ImplementedInterface": "Microsoft.AspNetCore.Antiforgery.Internal.IAntiforgeryTokenGenerator", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "GenerateRequestToken", + "Parameters": [ + { + "Name": "httpContext", + "Type": "Microsoft.AspNetCore.Http.HttpContext" + }, + { + "Name": "cookieToken", + "Type": "Microsoft.AspNetCore.Antiforgery.Internal.AntiforgeryToken" + } + ], + "ReturnType": "Microsoft.AspNetCore.Antiforgery.Internal.AntiforgeryToken", + "Sealed": true, + "Virtual": true, + "ImplementedInterface": "Microsoft.AspNetCore.Antiforgery.Internal.IAntiforgeryTokenGenerator", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "IsCookieTokenValid", + "Parameters": [ + { + "Name": "cookieToken", + "Type": "Microsoft.AspNetCore.Antiforgery.Internal.AntiforgeryToken" + } + ], + "ReturnType": "System.Boolean", + "Sealed": true, + "Virtual": true, + "ImplementedInterface": "Microsoft.AspNetCore.Antiforgery.Internal.IAntiforgeryTokenGenerator", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "TryValidateTokenSet", + "Parameters": [ + { + "Name": "httpContext", + "Type": "Microsoft.AspNetCore.Http.HttpContext" + }, + { + "Name": "cookieToken", + "Type": "Microsoft.AspNetCore.Antiforgery.Internal.AntiforgeryToken" + }, + { + "Name": "requestToken", + "Type": "Microsoft.AspNetCore.Antiforgery.Internal.AntiforgeryToken" + }, + { + "Name": "message", + "Type": "System.String", + "Direction": "Out" + } + ], + "ReturnType": "System.Boolean", + "Sealed": true, + "Virtual": true, + "ImplementedInterface": "Microsoft.AspNetCore.Antiforgery.Internal.IAntiforgeryTokenGenerator", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Constructor", + "Name": ".ctor", + "Parameters": [ + { + "Name": "claimUidExtractor", + "Type": "Microsoft.AspNetCore.Antiforgery.Internal.IClaimUidExtractor" + }, + { + "Name": "additionalDataProvider", + "Type": "Microsoft.AspNetCore.Antiforgery.IAntiforgeryAdditionalDataProvider" + } + ], + "Visibility": "Public", + "GenericParameter": [] + } + ], + "GenericParameters": [] + }, + { + "Name": "Microsoft.AspNetCore.Antiforgery.Internal.DefaultAntiforgeryTokenSerializer", + "Visibility": "Public", + "Kind": "Class", + "ImplementedInterfaces": [ + "Microsoft.AspNetCore.Antiforgery.Internal.IAntiforgeryTokenSerializer" + ], + "Members": [ + { + "Kind": "Method", + "Name": "Deserialize", + "Parameters": [ + { + "Name": "serializedToken", + "Type": "System.String" + } + ], + "ReturnType": "Microsoft.AspNetCore.Antiforgery.Internal.AntiforgeryToken", + "Sealed": true, + "Virtual": true, + "ImplementedInterface": "Microsoft.AspNetCore.Antiforgery.Internal.IAntiforgeryTokenSerializer", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "Serialize", + "Parameters": [ + { + "Name": "token", + "Type": "Microsoft.AspNetCore.Antiforgery.Internal.AntiforgeryToken" + } + ], + "ReturnType": "System.String", + "Sealed": true, + "Virtual": true, + "ImplementedInterface": "Microsoft.AspNetCore.Antiforgery.Internal.IAntiforgeryTokenSerializer", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Constructor", + "Name": ".ctor", + "Parameters": [ + { + "Name": "provider", + "Type": "Microsoft.AspNetCore.DataProtection.IDataProtectionProvider" + }, + { + "Name": "pool", + "Type": "Microsoft.Extensions.ObjectPool.ObjectPool" + } + ], + "Visibility": "Public", + "GenericParameter": [] + } + ], + "GenericParameters": [] + }, + { + "Name": "Microsoft.AspNetCore.Antiforgery.Internal.DefaultAntiforgeryTokenStore", + "Visibility": "Public", + "Kind": "Class", + "ImplementedInterfaces": [ + "Microsoft.AspNetCore.Antiforgery.Internal.IAntiforgeryTokenStore" + ], + "Members": [ + { + "Kind": "Method", + "Name": "GetCookieToken", + "Parameters": [ + { + "Name": "httpContext", + "Type": "Microsoft.AspNetCore.Http.HttpContext" + } + ], + "ReturnType": "System.String", + "Sealed": true, + "Virtual": true, + "ImplementedInterface": "Microsoft.AspNetCore.Antiforgery.Internal.IAntiforgeryTokenStore", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "GetRequestTokensAsync", + "Parameters": [ + { + "Name": "httpContext", + "Type": "Microsoft.AspNetCore.Http.HttpContext" + } + ], + "ReturnType": "System.Threading.Tasks.Task", + "Sealed": true, + "Virtual": true, + "ImplementedInterface": "Microsoft.AspNetCore.Antiforgery.Internal.IAntiforgeryTokenStore", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "SaveCookieToken", + "Parameters": [ + { + "Name": "httpContext", + "Type": "Microsoft.AspNetCore.Http.HttpContext" + }, + { + "Name": "token", + "Type": "System.String" + } + ], + "ReturnType": "System.Void", + "Sealed": true, + "Virtual": true, + "ImplementedInterface": "Microsoft.AspNetCore.Antiforgery.Internal.IAntiforgeryTokenStore", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Constructor", + "Name": ".ctor", + "Parameters": [ + { + "Name": "optionsAccessor", + "Type": "Microsoft.Extensions.Options.IOptions" + } + ], + "Visibility": "Public", + "GenericParameter": [] + } + ], + "GenericParameters": [] + }, + { + "Name": "Microsoft.AspNetCore.Antiforgery.Internal.DefaultClaimUidExtractor", + "Visibility": "Public", + "Kind": "Class", + "ImplementedInterfaces": [ + "Microsoft.AspNetCore.Antiforgery.Internal.IClaimUidExtractor" + ], + "Members": [ + { + "Kind": "Method", + "Name": "ExtractClaimUid", + "Parameters": [ + { + "Name": "claimsPrincipal", + "Type": "System.Security.Claims.ClaimsPrincipal" + } + ], + "ReturnType": "System.String", + "Sealed": true, + "Virtual": true, + "ImplementedInterface": "Microsoft.AspNetCore.Antiforgery.Internal.IClaimUidExtractor", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "GetUniqueIdentifierParameters", + "Parameters": [ + { + "Name": "claimsIdentities", + "Type": "System.Collections.Generic.IEnumerable" + } + ], + "ReturnType": "System.Collections.Generic.IList", + "Static": true, + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Constructor", + "Name": ".ctor", + "Parameters": [ + { + "Name": "pool", + "Type": "Microsoft.Extensions.ObjectPool.ObjectPool" + } + ], + "Visibility": "Public", + "GenericParameter": [] + } + ], + "GenericParameters": [] + }, + { + "Name": "Microsoft.AspNetCore.Antiforgery.Internal.IAntiforgeryFeature", + "Visibility": "Public", + "Kind": "Interface", + "Abstract": true, + "ImplementedInterfaces": [], + "Members": [ + { + "Kind": "Method", + "Name": "get_CookieToken", + "Parameters": [], + "ReturnType": "Microsoft.AspNetCore.Antiforgery.Internal.AntiforgeryToken", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "set_CookieToken", + "Parameters": [ + { + "Name": "value", + "Type": "Microsoft.AspNetCore.Antiforgery.Internal.AntiforgeryToken" + } + ], + "ReturnType": "System.Void", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "get_HaveDeserializedCookieToken", + "Parameters": [], + "ReturnType": "System.Boolean", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "set_HaveDeserializedCookieToken", + "Parameters": [ + { + "Name": "value", + "Type": "System.Boolean" + } + ], + "ReturnType": "System.Void", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "get_HaveDeserializedRequestToken", + "Parameters": [], + "ReturnType": "System.Boolean", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "set_HaveDeserializedRequestToken", + "Parameters": [ + { + "Name": "value", + "Type": "System.Boolean" + } + ], + "ReturnType": "System.Void", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "get_HaveGeneratedNewCookieToken", + "Parameters": [], + "ReturnType": "System.Boolean", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "set_HaveGeneratedNewCookieToken", + "Parameters": [ + { + "Name": "value", + "Type": "System.Boolean" + } + ], + "ReturnType": "System.Void", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "get_HaveStoredNewCookieToken", + "Parameters": [], + "ReturnType": "System.Boolean", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "set_HaveStoredNewCookieToken", + "Parameters": [ + { + "Name": "value", + "Type": "System.Boolean" + } + ], + "ReturnType": "System.Void", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "get_NewCookieToken", + "Parameters": [], + "ReturnType": "Microsoft.AspNetCore.Antiforgery.Internal.AntiforgeryToken", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "set_NewCookieToken", + "Parameters": [ + { + "Name": "value", + "Type": "Microsoft.AspNetCore.Antiforgery.Internal.AntiforgeryToken" + } + ], + "ReturnType": "System.Void", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "get_NewCookieTokenString", + "Parameters": [], + "ReturnType": "System.String", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "set_NewCookieTokenString", + "Parameters": [ + { + "Name": "value", + "Type": "System.String" + } + ], + "ReturnType": "System.Void", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "get_NewRequestToken", + "Parameters": [], + "ReturnType": "Microsoft.AspNetCore.Antiforgery.Internal.AntiforgeryToken", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "set_NewRequestToken", + "Parameters": [ + { + "Name": "value", + "Type": "Microsoft.AspNetCore.Antiforgery.Internal.AntiforgeryToken" + } + ], + "ReturnType": "System.Void", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "get_NewRequestTokenString", + "Parameters": [], + "ReturnType": "System.String", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "set_NewRequestTokenString", + "Parameters": [ + { + "Name": "value", + "Type": "System.String" + } + ], + "ReturnType": "System.Void", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "get_RequestToken", + "Parameters": [], + "ReturnType": "Microsoft.AspNetCore.Antiforgery.Internal.AntiforgeryToken", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "set_RequestToken", + "Parameters": [ + { + "Name": "value", + "Type": "Microsoft.AspNetCore.Antiforgery.Internal.AntiforgeryToken" + } + ], + "ReturnType": "System.Void", + "GenericParameter": [] + } + ], + "GenericParameters": [] + }, + { + "Name": "Microsoft.AspNetCore.Antiforgery.Internal.IAntiforgeryTokenGenerator", + "Visibility": "Public", + "Kind": "Interface", + "Abstract": true, + "ImplementedInterfaces": [], + "Members": [ + { + "Kind": "Method", + "Name": "GenerateCookieToken", + "Parameters": [], + "ReturnType": "Microsoft.AspNetCore.Antiforgery.Internal.AntiforgeryToken", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "GenerateRequestToken", + "Parameters": [ + { + "Name": "httpContext", + "Type": "Microsoft.AspNetCore.Http.HttpContext" + }, + { + "Name": "cookieToken", + "Type": "Microsoft.AspNetCore.Antiforgery.Internal.AntiforgeryToken" + } + ], + "ReturnType": "Microsoft.AspNetCore.Antiforgery.Internal.AntiforgeryToken", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "IsCookieTokenValid", + "Parameters": [ + { + "Name": "cookieToken", + "Type": "Microsoft.AspNetCore.Antiforgery.Internal.AntiforgeryToken" + } + ], + "ReturnType": "System.Boolean", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "TryValidateTokenSet", + "Parameters": [ + { + "Name": "httpContext", + "Type": "Microsoft.AspNetCore.Http.HttpContext" + }, + { + "Name": "cookieToken", + "Type": "Microsoft.AspNetCore.Antiforgery.Internal.AntiforgeryToken" + }, + { + "Name": "requestToken", + "Type": "Microsoft.AspNetCore.Antiforgery.Internal.AntiforgeryToken" + }, + { + "Name": "message", + "Type": "System.String", + "Direction": "Out" + } + ], + "ReturnType": "System.Boolean", + "GenericParameter": [] + } + ], + "GenericParameters": [] + }, + { + "Name": "Microsoft.AspNetCore.Antiforgery.Internal.IAntiforgeryTokenSerializer", + "Visibility": "Public", + "Kind": "Interface", + "Abstract": true, + "ImplementedInterfaces": [], + "Members": [ + { + "Kind": "Method", + "Name": "Deserialize", + "Parameters": [ + { + "Name": "serializedToken", + "Type": "System.String" + } + ], + "ReturnType": "Microsoft.AspNetCore.Antiforgery.Internal.AntiforgeryToken", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "Serialize", + "Parameters": [ + { + "Name": "token", + "Type": "Microsoft.AspNetCore.Antiforgery.Internal.AntiforgeryToken" + } + ], + "ReturnType": "System.String", + "GenericParameter": [] + } + ], + "GenericParameters": [] + }, + { + "Name": "Microsoft.AspNetCore.Antiforgery.Internal.IAntiforgeryTokenStore", + "Visibility": "Public", + "Kind": "Interface", + "Abstract": true, + "ImplementedInterfaces": [], + "Members": [ + { + "Kind": "Method", + "Name": "GetCookieToken", + "Parameters": [ + { + "Name": "httpContext", + "Type": "Microsoft.AspNetCore.Http.HttpContext" + } + ], + "ReturnType": "System.String", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "GetRequestTokensAsync", + "Parameters": [ + { + "Name": "httpContext", + "Type": "Microsoft.AspNetCore.Http.HttpContext" + } + ], + "ReturnType": "System.Threading.Tasks.Task", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "SaveCookieToken", + "Parameters": [ + { + "Name": "httpContext", + "Type": "Microsoft.AspNetCore.Http.HttpContext" + }, + { + "Name": "token", + "Type": "System.String" + } + ], + "ReturnType": "System.Void", + "GenericParameter": [] + } + ], + "GenericParameters": [] + }, + { + "Name": "Microsoft.AspNetCore.Antiforgery.Internal.IClaimUidExtractor", + "Visibility": "Public", + "Kind": "Interface", + "Abstract": true, + "ImplementedInterfaces": [], + "Members": [ + { + "Kind": "Method", + "Name": "ExtractClaimUid", + "Parameters": [ + { + "Name": "claimsPrincipal", + "Type": "System.Security.Claims.ClaimsPrincipal" + } + ], + "ReturnType": "System.String", + "GenericParameter": [] + } + ], + "GenericParameters": [] + } + ] +} \ No newline at end of file From a5c0e505c142f309b968bd7db549ff85c818ff04 Mon Sep 17 00:00:00 2001 From: Kiran Challa Date: Tue, 8 Nov 2016 09:01:48 -0800 Subject: [PATCH 164/296] Fix cookie from being set to empty pathbase Found with issue: https://github.com/aspnet/Mvc/issues/5512 --- .../Internal/DefaultAntiforgeryTokenStore.cs | 12 ++++- .../AntiforgerySampleTest.cs | 45 ++++++++++--------- .../DefaultAntiforgeryTokenStoreTest.cs | 12 ++--- 3 files changed, 43 insertions(+), 26 deletions(-) diff --git a/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgeryTokenStore.cs b/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgeryTokenStore.cs index 9e3658fa93..ada7752396 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgeryTokenStore.cs +++ b/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgeryTokenStore.cs @@ -71,7 +71,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal var options = new CookieOptions(); options.HttpOnly = true; - options.Path = _options.CookiePath ?? httpContext.Request.PathBase; + options.Path = _options.CookiePath ?? GetPathBase(httpContext); options.Domain = _options.CookieDomain; // Note: don't use "newCookie.Secure = _options.RequireSSL;" since the default // value of newCookie.Secure is populated out of band. @@ -82,5 +82,15 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal httpContext.Response.Cookies.Append(_options.CookieName, token, options); } + + private string GetPathBase(HttpContext httpContext) + { + var pathBase = httpContext.Request.PathBase.ToString(); + if (string.IsNullOrEmpty(pathBase)) + { + pathBase = "/"; + } + return pathBase; + } } } diff --git a/test/Microsoft.AspNetCore.Antiforgery.FunctionalTests/AntiforgerySampleTest.cs b/test/Microsoft.AspNetCore.Antiforgery.FunctionalTests/AntiforgerySampleTest.cs index d49d8df723..52c46bd6b6 100644 --- a/test/Microsoft.AspNetCore.Antiforgery.FunctionalTests/AntiforgerySampleTest.cs +++ b/test/Microsoft.AspNetCore.Antiforgery.FunctionalTests/AntiforgerySampleTest.cs @@ -6,6 +6,7 @@ using System.Linq; using System.Net; using System.Net.Http; using System.Threading.Tasks; +using Microsoft.Net.Http.Headers; using Xunit; namespace Microsoft.AspNetCore.Antiforgery.FunctionalTests @@ -26,11 +27,19 @@ namespace Microsoft.AspNetCore.Antiforgery.FunctionalTests var response = await Client.GetAsync("http://localhost/Index.html"); // Assert - var cookie = RetrieveAntiforgeryCookie(response); - Assert.NotNull(cookie.Value); + var setCookieHeaderValue = RetrieveAntiforgeryCookie(response); + Assert.NotNull(setCookieHeaderValue); + Assert.False(string.IsNullOrEmpty(setCookieHeaderValue.Value)); + Assert.Null(setCookieHeaderValue.Domain); + Assert.Equal("/", setCookieHeaderValue.Path); + Assert.False(setCookieHeaderValue.Secure); - var token = RetrieveAntiforgeryToken(response); - Assert.NotNull(token.Value); + setCookieHeaderValue = RetrieveAntiforgeryToken(response); + Assert.NotNull(setCookieHeaderValue); + Assert.False(string.IsNullOrEmpty(setCookieHeaderValue.Value)); + Assert.Null(setCookieHeaderValue.Domain); + Assert.Equal("/", setCookieHeaderValue.Path); + Assert.False(setCookieHeaderValue.Secure); } [Fact] @@ -49,7 +58,7 @@ namespace Microsoft.AspNetCore.Antiforgery.FunctionalTests }); // Assert - Assert.Contains($"The required antiforgery cookie \"{cookie.Key}\" is not present.", exception.Message); + Assert.Contains($"The required antiforgery cookie \"{cookie.Name}\" is not present.", exception.Message); } [Fact] @@ -63,8 +72,8 @@ namespace Microsoft.AspNetCore.Antiforgery.FunctionalTests var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, "http://localhost/api/items"); + httpRequestMessage.Headers.Add("Cookie", $"{cookie.Name}={cookie.Value}"); httpRequestMessage.Headers.Add("X-XSRF-TOKEN", token.Value); - httpRequestMessage.Headers.Add("Cookie", $"{cookie.Key}={cookie.Value}"); // Act var response = await Client.SendAsync(httpRequestMessage); @@ -73,24 +82,20 @@ namespace Microsoft.AspNetCore.Antiforgery.FunctionalTests Assert.Equal(HttpStatusCode.NoContent, response.StatusCode); } - private static KeyValuePair RetrieveAntiforgeryToken(HttpResponseMessage response) + private static SetCookieHeaderValue RetrieveAntiforgeryToken(HttpResponseMessage response) { - return GetCookie(response, 1); + return response.Headers.GetValues(HeaderNames.SetCookie) + .Select(setCookieValue => SetCookieHeaderValue.Parse(setCookieValue)) + .Where(setCookieHeaderValue => setCookieHeaderValue.Name == "XSRF-TOKEN") + .FirstOrDefault(); } - private static KeyValuePair RetrieveAntiforgeryCookie(HttpResponseMessage response) + private static SetCookieHeaderValue RetrieveAntiforgeryCookie(HttpResponseMessage response) { - return GetCookie(response, 0); - } - - private static KeyValuePair GetCookie(HttpResponseMessage response, int index) - { - var setCookieArray = response.Headers.GetValues("Set-Cookie").ToArray(); - var cookie = setCookieArray[index].Split(';').First().Split('='); - var cookieKey = cookie[0]; - var cookieData = cookie[1]; - - return new KeyValuePair(cookieKey, cookieData); + return response.Headers.GetValues(HeaderNames.SetCookie) + .Select(setCookieValue => SetCookieHeaderValue.Parse(setCookieValue)) + .Where(setCookieHeaderValue => setCookieHeaderValue.Name.StartsWith(".AspNetCore.Antiforgery.")) + .FirstOrDefault(); } } } \ No newline at end of file diff --git a/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTokenStoreTest.cs b/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTokenStoreTest.cs index fb6927f535..f328ff908b 100644 --- a/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTokenStoreTest.cs +++ b/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTokenStoreTest.cs @@ -274,10 +274,12 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal } [Theory] - [InlineData("/")] - [InlineData("/vdir1")] - [InlineData("/vdir1/vdir2")] - public void SaveCookieToken_SetsCookieWithApproriatePathBase(string requestPathBase) + [InlineData(null, "/")] + [InlineData("", "/")] + [InlineData("/", "/")] + [InlineData("/vdir1", "/vdir1")] + [InlineData("/vdir1/vdir2", "/vdir1/vdir2")] + public void SaveCookieToken_SetsCookieWithApproriatePathBase(string requestPathBase, string expectedCookiePath) { // Arrange var token = "serialized-value"; @@ -305,7 +307,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal Assert.Equal(_cookieName, cookies.Key); Assert.Equal("serialized-value", cookies.Value); Assert.True(cookies.Options.HttpOnly); - Assert.Equal(requestPathBase, cookies.Options.Path); + Assert.Equal(expectedCookiePath, cookies.Options.Path); } [Fact] From 2fcb187d7d34e9a0b046c2502c3a8b9b0155db91 Mon Sep 17 00:00:00 2001 From: Kiran Challa Date: Tue, 8 Nov 2016 16:50:46 -0800 Subject: [PATCH 165/296] Use request PathBase value to set cookie path only if it has a non-null & non-empty value --- .../AntiforgeryOptions.cs | 5 +++-- .../Internal/DefaultAntiforgeryTokenStore.cs | 18 ++++++++++++------ 2 files changed, 15 insertions(+), 8 deletions(-) diff --git a/src/Microsoft.AspNetCore.Antiforgery/AntiforgeryOptions.cs b/src/Microsoft.AspNetCore.Antiforgery/AntiforgeryOptions.cs index 98f4968c1e..b8c6e4b816 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/AntiforgeryOptions.cs +++ b/src/Microsoft.AspNetCore.Antiforgery/AntiforgeryOptions.cs @@ -47,8 +47,9 @@ namespace Microsoft.AspNetCore.Antiforgery } /// - /// The path set on the cookie. If it's null, the "path" attribute on the cookie is set to current - /// request's value. + /// The path set on the cookie. If set to null, the "path" attribute on the cookie is set to the current + /// request's value. If the value of is + /// null or empty, then the "path" attribute is set to the value of . /// public PathString? CookiePath { get; set; } diff --git a/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgeryTokenStore.cs b/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgeryTokenStore.cs index ada7752396..0a78eddb41 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgeryTokenStore.cs +++ b/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgeryTokenStore.cs @@ -71,7 +71,6 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal var options = new CookieOptions(); options.HttpOnly = true; - options.Path = _options.CookiePath ?? GetPathBase(httpContext); options.Domain = _options.CookieDomain; // Note: don't use "newCookie.Secure = _options.RequireSSL;" since the default // value of newCookie.Secure is populated out of band. @@ -79,18 +78,25 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal { options.Secure = true; } + SetCookiePath(httpContext, options); httpContext.Response.Cookies.Append(_options.CookieName, token, options); } - private string GetPathBase(HttpContext httpContext) + private void SetCookiePath(HttpContext httpContext, CookieOptions cookieOptions) { - var pathBase = httpContext.Request.PathBase.ToString(); - if (string.IsNullOrEmpty(pathBase)) + if (_options.CookiePath != null) { - pathBase = "/"; + cookieOptions.Path = _options.CookiePath.ToString(); + } + else + { + var pathBase = httpContext.Request.PathBase.ToString(); + if (!string.IsNullOrEmpty(pathBase)) + { + cookieOptions.Path = pathBase; + } } - return pathBase; } } } From 3668d0f0132b533ce819887421078ed16b60be2c Mon Sep 17 00:00:00 2001 From: Pranav K Date: Wed, 9 Nov 2016 11:28:58 -0800 Subject: [PATCH 166/296] Branching for 1.1.0 --- NuGet.config | 4 ++-- build.ps1 | 2 +- build.sh | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/NuGet.config b/NuGet.config index 0fd623ffdd..ad973186eb 100644 --- a/NuGet.config +++ b/NuGet.config @@ -1,7 +1,7 @@ - + - + diff --git a/build.ps1 b/build.ps1 index 8f2f99691a..24ca167cf6 100644 --- a/build.ps1 +++ b/build.ps1 @@ -33,7 +33,7 @@ cd $PSScriptRoot $repoFolder = $PSScriptRoot $env:REPO_FOLDER = $repoFolder -$koreBuildZip="https://github.com/aspnet/KoreBuild/archive/dev.zip" +$koreBuildZip="https://github.com/aspnet/KoreBuild/archive/rel/1.1.0.zip" if ($env:KOREBUILD_ZIP) { $koreBuildZip=$env:KOREBUILD_ZIP diff --git a/build.sh b/build.sh index f4208100eb..fea9ac64ad 100755 --- a/build.sh +++ b/build.sh @@ -2,7 +2,7 @@ repoFolder="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" cd $repoFolder -koreBuildZip="https://github.com/aspnet/KoreBuild/archive/dev.zip" +koreBuildZip="https://github.com/aspnet/KoreBuild/archive/rel/1.1.0.zip" if [ ! -z $KOREBUILD_ZIP ]; then koreBuildZip=$KOREBUILD_ZIP fi From 687be28875d4e80a06f1c75791bd9b73e5f45a11 Mon Sep 17 00:00:00 2001 From: Pranav K Date: Wed, 9 Nov 2016 14:12:21 -0800 Subject: [PATCH 167/296] Updating versions to 1.2.0-* --- samples/AntiforgerySample/project.json | 14 +++++++------- src/Microsoft.AspNetCore.Antiforgery/project.json | 12 ++++++------ .../project.json | 4 ++-- .../project.json | 14 +++++++------- 4 files changed, 22 insertions(+), 22 deletions(-) diff --git a/samples/AntiforgerySample/project.json b/samples/AntiforgerySample/project.json index dd24a3b97b..f427ac0e0c 100644 --- a/samples/AntiforgerySample/project.json +++ b/samples/AntiforgerySample/project.json @@ -1,12 +1,12 @@ { - "version": "1.1.0-*", + "version": "1.2.0-*", "dependencies": { - "Microsoft.AspNetCore.Antiforgery": "1.1.0-*", - "Microsoft.AspNetCore.Http.Abstractions": "1.1.0-*", - "Microsoft.AspNetCore.Http.Extensions": "1.1.0-*", - "Microsoft.AspNetCore.Server.IISIntegration": "1.1.0-*", - "Microsoft.AspNetCore.Server.Kestrel": "1.1.0-*", - "Microsoft.AspNetCore.StaticFiles": "1.1.0-*", + "Microsoft.AspNetCore.Antiforgery": "1.2.0-*", + "Microsoft.AspNetCore.Http.Abstractions": "1.2.0-*", + "Microsoft.AspNetCore.Http.Extensions": "1.2.0-*", + "Microsoft.AspNetCore.Server.IISIntegration": "1.2.0-*", + "Microsoft.AspNetCore.Server.Kestrel": "1.2.0-*", + "Microsoft.AspNetCore.StaticFiles": "1.2.0-*", "Newtonsoft.Json": "9.0.1" }, "buildOptions": { diff --git a/src/Microsoft.AspNetCore.Antiforgery/project.json b/src/Microsoft.AspNetCore.Antiforgery/project.json index 5c9b5608f8..ebe13a3b4d 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/project.json +++ b/src/Microsoft.AspNetCore.Antiforgery/project.json @@ -1,6 +1,6 @@ { "description": "An antiforgery system for ASP.NET Core designed to generate and validate tokens to prevent Cross-Site Request Forgery attacks.", - "version": "1.1.0-*", + "version": "1.2.0-*", "buildOptions": { "warningsAsErrors": true, "keyFile": "../../tools/Key.snk", @@ -20,11 +20,11 @@ ] }, "dependencies": { - "Microsoft.AspNetCore.DataProtection": "1.1.0-*", - "Microsoft.AspNetCore.Http.Abstractions": "1.1.0-*", - "Microsoft.AspNetCore.Http.Extensions": "1.1.0-*", - "Microsoft.AspNetCore.WebUtilities": "1.1.0-*", - "Microsoft.Extensions.ObjectPool": "1.1.0-*", + "Microsoft.AspNetCore.DataProtection": "1.2.0-*", + "Microsoft.AspNetCore.Http.Abstractions": "1.2.0-*", + "Microsoft.AspNetCore.Http.Extensions": "1.2.0-*", + "Microsoft.AspNetCore.WebUtilities": "1.2.0-*", + "Microsoft.Extensions.ObjectPool": "1.2.0-*", "NETStandard.Library": "1.6.1-*" }, "frameworks": { diff --git a/test/Microsoft.AspNetCore.Antiforgery.FunctionalTests/project.json b/test/Microsoft.AspNetCore.Antiforgery.FunctionalTests/project.json index 984fb8ddd8..5f9f3dd9b0 100644 --- a/test/Microsoft.AspNetCore.Antiforgery.FunctionalTests/project.json +++ b/test/Microsoft.AspNetCore.Antiforgery.FunctionalTests/project.json @@ -1,8 +1,8 @@ { "dependencies": { - "AntiforgerySample": "1.1.0-*", + "AntiforgerySample": "1.2.0-*", "dotnet-test-xunit": "2.2.0-*", - "Microsoft.AspNetCore.TestHost": "1.1.0-*", + "Microsoft.AspNetCore.TestHost": "1.2.0-*", "Moq": "4.6.36-*", "xunit": "2.2.0-*" }, diff --git a/test/Microsoft.AspNetCore.Antiforgery.Test/project.json b/test/Microsoft.AspNetCore.Antiforgery.Test/project.json index c8cff04a99..4eff14b67c 100644 --- a/test/Microsoft.AspNetCore.Antiforgery.Test/project.json +++ b/test/Microsoft.AspNetCore.Antiforgery.Test/project.json @@ -5,13 +5,13 @@ }, "dependencies": { "dotnet-test-xunit": "2.2.0-*", - "Microsoft.AspNetCore.Antiforgery": "1.1.0-*", - "Microsoft.AspNetCore.Http": "1.1.0-*", - "Microsoft.AspNetCore.Testing": "1.1.0-*", - "Microsoft.Extensions.DependencyInjection": "1.1.0-*", - "Microsoft.Extensions.Logging": "1.1.0-*", - "Microsoft.Extensions.Logging.Testing": "1.1.0-*", - "Microsoft.Extensions.WebEncoders": "1.1.0-*", + "Microsoft.AspNetCore.Antiforgery": "1.2.0-*", + "Microsoft.AspNetCore.Http": "1.2.0-*", + "Microsoft.AspNetCore.Testing": "1.2.0-*", + "Microsoft.Extensions.DependencyInjection": "1.2.0-*", + "Microsoft.Extensions.Logging": "1.2.0-*", + "Microsoft.Extensions.Logging.Testing": "1.2.0-*", + "Microsoft.Extensions.WebEncoders": "1.2.0-*", "Moq": "4.6.36-*", "xunit": "2.2.0-*" }, From a01c7be3d86cf38cd59c1a136ae961c0d8602b2e Mon Sep 17 00:00:00 2001 From: Nate McMaster Date: Fri, 18 Nov 2016 10:56:12 -0800 Subject: [PATCH 168/296] Clean tmp folder after unzipping KoreBuild --- build.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/build.sh b/build.sh index f4208100eb..4fd7ede788 100755 --- a/build.sh +++ b/build.sh @@ -38,7 +38,7 @@ if test ! -d $buildFolder; then chmod +x $buildFile # Cleanup - if test ! -d $tempFolder; then + if test -d $tempFolder; then rm -rf $tempFolder fi fi From 25e0fee45c24f4fe6d7d883061247d3264404abc Mon Sep 17 00:00:00 2001 From: "N. Taylor Mullen" Date: Wed, 23 Nov 2016 16:00:28 -0800 Subject: [PATCH 169/296] Pin global.json SDK to 1.0.0-preview2-1-003177. --- global.json | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/global.json b/global.json index feb51cb71d..9bf5aae425 100644 --- a/global.json +++ b/global.json @@ -1,3 +1,9 @@ { - "projects": ["src", "samples"] -} + "projects": [ + "src", + "samples" + ], + "sdk": { + "version": "1.0.0-preview2-1-003177" + } +} \ No newline at end of file From db4b088a4a922179006ed0f7de1ae4317a450701 Mon Sep 17 00:00:00 2001 From: "N. Taylor Mullen" Date: Thu, 8 Dec 2016 10:04:20 -0800 Subject: [PATCH 170/296] Update .travis.yml osx image to xcode7.3. --- .travis.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index 20ad23da42..bce76eefa4 100644 --- a/.travis.yml +++ b/.travis.yml @@ -19,7 +19,7 @@ mono: os: - linux - osx -osx_image: xcode7.1 +osx_image: xcode7.3 branches: only: - master From a430bca8c462b302cb2a984ff368a4ccd7beb59a Mon Sep 17 00:00:00 2001 From: Ajay Bhargav Baaskaran Date: Mon, 12 Dec 2016 00:43:04 -0800 Subject: [PATCH 171/296] Removed packages list in NuGetPackageVerifier.json --- NuGetPackageVerifier.json | 10 +--------- 1 file changed, 1 insertion(+), 9 deletions(-) diff --git a/NuGetPackageVerifier.json b/NuGetPackageVerifier.json index 67e35e0f0f..b153ab1515 100644 --- a/NuGetPackageVerifier.json +++ b/NuGetPackageVerifier.json @@ -1,13 +1,5 @@ { - "adx": { // Packages written by the ADX team and that ship on NuGet.org - "rules": [ - "AdxVerificationCompositeRule" - ], - "packages": { - "Microsoft.AspNetCore.Antiforgery": { } - } - }, - "Default": { // Rules to run for packages not listed in any other set. + "Default": { "rules": [ "DefaultCompositeRule" ] From 5cb5178619d9211eee0722d8737b425e2eec1375 Mon Sep 17 00:00:00 2001 From: Pranav K Date: Mon, 5 Dec 2016 09:01:31 -0800 Subject: [PATCH 172/296] Updating to 4.4 CoreFx packages --- global.json | 2 +- samples/AntiforgerySample/project.json | 2 +- src/Microsoft.AspNetCore.Antiforgery/project.json | 2 +- .../project.json | 2 +- test/Microsoft.AspNetCore.Antiforgery.Test/project.json | 4 ++-- 5 files changed, 6 insertions(+), 6 deletions(-) diff --git a/global.json b/global.json index 9bf5aae425..9ecb1c6efa 100644 --- a/global.json +++ b/global.json @@ -4,6 +4,6 @@ "samples" ], "sdk": { - "version": "1.0.0-preview2-1-003177" + "version": "1.0.0-preview2-1-003180" } } \ No newline at end of file diff --git a/samples/AntiforgerySample/project.json b/samples/AntiforgerySample/project.json index f427ac0e0c..328f7f8940 100644 --- a/samples/AntiforgerySample/project.json +++ b/samples/AntiforgerySample/project.json @@ -17,7 +17,7 @@ "netcoreapp1.1": { "dependencies": { "Microsoft.NETCore.App": { - "version": "1.1.0-*", + "version": "1.2.0-*", "type": "platform" } } diff --git a/src/Microsoft.AspNetCore.Antiforgery/project.json b/src/Microsoft.AspNetCore.Antiforgery/project.json index ebe13a3b4d..963c586691 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/project.json +++ b/src/Microsoft.AspNetCore.Antiforgery/project.json @@ -25,7 +25,7 @@ "Microsoft.AspNetCore.Http.Extensions": "1.2.0-*", "Microsoft.AspNetCore.WebUtilities": "1.2.0-*", "Microsoft.Extensions.ObjectPool": "1.2.0-*", - "NETStandard.Library": "1.6.1-*" + "NETStandard.Library": "1.6.2-*" }, "frameworks": { "netstandard1.3": {}, diff --git a/test/Microsoft.AspNetCore.Antiforgery.FunctionalTests/project.json b/test/Microsoft.AspNetCore.Antiforgery.FunctionalTests/project.json index 5f9f3dd9b0..3a19511a4e 100644 --- a/test/Microsoft.AspNetCore.Antiforgery.FunctionalTests/project.json +++ b/test/Microsoft.AspNetCore.Antiforgery.FunctionalTests/project.json @@ -11,7 +11,7 @@ "netcoreapp1.1": { "dependencies": { "Microsoft.NETCore.App": { - "version": "1.1.0-*", + "version": "1.2.0-*", "type": "platform" } } diff --git a/test/Microsoft.AspNetCore.Antiforgery.Test/project.json b/test/Microsoft.AspNetCore.Antiforgery.Test/project.json index 4eff14b67c..e564174790 100644 --- a/test/Microsoft.AspNetCore.Antiforgery.Test/project.json +++ b/test/Microsoft.AspNetCore.Antiforgery.Test/project.json @@ -20,10 +20,10 @@ "netcoreapp1.1": { "dependencies": { "Microsoft.NETCore.App": { - "version": "1.1.0-*", + "version": "1.2.0-*", "type": "platform" }, - "System.Diagnostics.TraceSource": "4.3.0-*" + "System.Diagnostics.TraceSource": "4.4.0-*" } }, "net451": { From cd4afdc08384fe3fd255ae08fd4c62cdd7c3ee32 Mon Sep 17 00:00:00 2001 From: Kiran Challa Date: Mon, 23 Jan 2017 09:27:09 -0800 Subject: [PATCH 173/296] [Fixes #116] Set 'no-store' also in Cache-Conrol header --- .../Internal/AntiforgeryLoggerExtensions.cs | 5 +++-- .../Internal/DefaultAntiforgery.cs | 10 ++++++---- .../Internal/DefaultAntiforgeryTest.cs | 17 +++++++++-------- 3 files changed, 18 insertions(+), 14 deletions(-) diff --git a/src/Microsoft.AspNetCore.Antiforgery/Internal/AntiforgeryLoggerExtensions.cs b/src/Microsoft.AspNetCore.Antiforgery/Internal/AntiforgeryLoggerExtensions.cs index 7dd43069db..0c8ef5ccfd 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/Internal/AntiforgeryLoggerExtensions.cs +++ b/src/Microsoft.AspNetCore.Antiforgery/Internal/AntiforgeryLoggerExtensions.cs @@ -51,8 +51,9 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal _responseCacheHeadersOverridenToNoCache = LoggerMessage.Define( LogLevel.Warning, 8, - "The 'Cache-Control' and 'Pragma' headers have been overridden and set to 'no-cache' to prevent " + - "caching of this response. Any response that uses antiforgery should not be cached."); + "The 'Cache-Control' and 'Pragma' headers have been overridden and set to 'no-cache, no-store' and " + + "'no-cache' respectively to prevent caching of this response. Any response that uses antiforgery " + + "should not be cached."); } public static void ValidationFailed(this ILogger logger, string message) diff --git a/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgery.cs b/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgery.cs index 755d8ae2f1..9677f7a793 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgery.cs +++ b/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgery.cs @@ -243,8 +243,6 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal _logger.ReusedCookieToken(); } - // Explicitly set the cache headers to 'no-cache'. This could override any user set value but this is fine - // as a response with antiforgery token must never be cached. SetDoNotCacheHeaders(httpContext); } @@ -367,14 +365,18 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal return antiforgeryFeature; } - private void SetDoNotCacheHeaders(HttpContext httpContext) + /// + /// Sets the 'Cache-Control' header to 'no-cache, no-store' and 'Pragma' header to 'no-cache' overriding any user set value. + /// + /// The . + protected virtual void SetDoNotCacheHeaders(HttpContext httpContext) { // Since antifogery token generation is not very obvious to the end users (ex: MVC's form tag generates them // by default), log a warning to let users know of the change in behavior to any cache headers they might // have set explicitly. LogCacheHeaderOverrideWarning(httpContext.Response); - httpContext.Response.Headers[HeaderNames.CacheControl] = "no-cache"; + httpContext.Response.Headers[HeaderNames.CacheControl] = "no-cache, no-store"; httpContext.Response.Headers[HeaderNames.Pragma] = "no-cache"; } diff --git a/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTest.cs b/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTest.cs index 943eb94cb4..e9b56f1c91 100644 --- a/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTest.cs +++ b/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTest.cs @@ -19,8 +19,9 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal public class DefaultAntiforgeryTest { private const string ResponseCacheHeadersOverrideWarningMessage = - "The 'Cache-Control' and 'Pragma' headers have been overridden and set to 'no-cache' to prevent caching " + - "of this response. Any response that uses antiforgery should not be cached."; + "The 'Cache-Control' and 'Pragma' headers have been overridden and set to 'no-cache, no-store' and " + + "'no-cache' respectively to prevent caching of this response. Any response that uses antiforgery " + + "should not be cached."; [Fact] public async Task ChecksSSL_ValidateRequestAsync_Throws() @@ -308,7 +309,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal Assert.NotNull(antiforgeryFeature); Assert.Equal(context.TestTokenSet.OldCookieToken, antiforgeryFeature.CookieToken); - Assert.Equal("no-cache", context.HttpContext.Response.Headers[HeaderNames.CacheControl]); + Assert.Equal("no-cache, no-store", context.HttpContext.Response.Headers[HeaderNames.CacheControl]); Assert.Equal("no-cache", context.HttpContext.Response.Headers[HeaderNames.Pragma]); } @@ -339,7 +340,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal Assert.NotNull(antiforgeryFeature); Assert.Equal(context.TestTokenSet.OldCookieToken, antiforgeryFeature.CookieToken); - Assert.Equal("no-cache", context.HttpContext.Response.Headers[HeaderNames.CacheControl]); + Assert.Equal("no-cache, no-store", context.HttpContext.Response.Headers[HeaderNames.CacheControl]); Assert.Equal("no-cache", context.HttpContext.Response.Headers[HeaderNames.Pragma]); } @@ -403,7 +404,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal Assert.NotNull(antiforgeryFeature); Assert.True(antiforgeryFeature.HaveDeserializedCookieToken); Assert.Equal(context.TestTokenSet.OldCookieToken, antiforgeryFeature.CookieToken); - Assert.Equal("no-cache", context.HttpContext.Response.Headers[HeaderNames.CacheControl]); + Assert.Equal("no-cache, no-store", context.HttpContext.Response.Headers[HeaderNames.CacheControl]); Assert.Equal("no-cache", context.HttpContext.Response.Headers[HeaderNames.Pragma]); } @@ -925,7 +926,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal antiforgery.SetCookieTokenAndHeader(context.HttpContext); // Assert - Assert.Equal("no-cache", context.HttpContext.Response.Headers["Cache-Control"]); + Assert.Equal("no-cache, no-store", context.HttpContext.Response.Headers["Cache-Control"]); Assert.Equal("no-cache", context.HttpContext.Response.Headers["Pragma"]); } @@ -948,7 +949,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal antiforgery.SetCookieTokenAndHeader(context.HttpContext); // Assert - Assert.Equal("no-cache", context.HttpContext.Response.Headers["Cache-Control"]); + Assert.Equal("no-cache, no-store", context.HttpContext.Response.Headers["Cache-Control"]); Assert.Equal("no-cache", context.HttpContext.Response.Headers["Pragma"]); } @@ -972,7 +973,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal antiforgery.SetCookieTokenAndHeader(context.HttpContext); // Assert - Assert.Equal("no-cache", context.HttpContext.Response.Headers["Cache-Control"]); + Assert.Equal("no-cache, no-store", context.HttpContext.Response.Headers["Cache-Control"]); Assert.Equal("no-cache", context.HttpContext.Response.Headers["Pragma"]); } From aeab73f9f6b39714cbc1c817e495ef0f71588821 Mon Sep 17 00:00:00 2001 From: Nate McMaster Date: Mon, 30 Jan 2017 14:05:08 -0800 Subject: [PATCH 174/296] Upgrade to VS 2017 --- Antiforgery.sln | 13 +++--- NuGet.config | 3 +- appveyor.yml | 3 +- build.ps1 | 2 +- build.sh | 2 +- {tools => build}/Key.snk | Bin build/common.props | 19 +++++++++ global.json | 9 ---- .../AntiforgerySample.csproj | 24 +++++++++++ .../AntiforgerySample/AntiforgerySample.xproj | 18 -------- samples/AntiforgerySample/project.json | 38 ----------------- .../Microsoft.AspNetCore.Antiforgery.csproj | 25 +++++++++++ .../Microsoft.AspNetCore.Antiforgery.xproj | 17 -------- .../Properties/AssemblyInfo.cs | 7 --- .../project.json | 40 ------------------ ...NetCore.Antiforgery.FunctionalTests.csproj | 21 +++++++++ ...pNetCore.Antiforgery.FunctionalTests.xproj | 20 --------- .../project.json | 25 ----------- ...crosoft.AspNetCore.Antiforgery.Test.csproj | 27 ++++++++++++ ...icrosoft.AspNetCore.Antiforgery.Test.xproj | 20 --------- .../project.json | 35 --------------- version.props | 7 +++ 22 files changed, 135 insertions(+), 240 deletions(-) rename {tools => build}/Key.snk (100%) create mode 100644 build/common.props delete mode 100644 global.json create mode 100644 samples/AntiforgerySample/AntiforgerySample.csproj delete mode 100644 samples/AntiforgerySample/AntiforgerySample.xproj delete mode 100644 samples/AntiforgerySample/project.json create mode 100644 src/Microsoft.AspNetCore.Antiforgery/Microsoft.AspNetCore.Antiforgery.csproj delete mode 100644 src/Microsoft.AspNetCore.Antiforgery/Microsoft.AspNetCore.Antiforgery.xproj delete mode 100644 src/Microsoft.AspNetCore.Antiforgery/project.json create mode 100644 test/Microsoft.AspNetCore.Antiforgery.FunctionalTests/Microsoft.AspNetCore.Antiforgery.FunctionalTests.csproj delete mode 100644 test/Microsoft.AspNetCore.Antiforgery.FunctionalTests/Microsoft.AspNetCore.Antiforgery.FunctionalTests.xproj delete mode 100644 test/Microsoft.AspNetCore.Antiforgery.FunctionalTests/project.json create mode 100644 test/Microsoft.AspNetCore.Antiforgery.Test/Microsoft.AspNetCore.Antiforgery.Test.csproj delete mode 100644 test/Microsoft.AspNetCore.Antiforgery.Test/Microsoft.AspNetCore.Antiforgery.Test.xproj delete mode 100644 test/Microsoft.AspNetCore.Antiforgery.Test/project.json create mode 100644 version.props diff --git a/Antiforgery.sln b/Antiforgery.sln index b25af44097..04e95ee7f6 100644 --- a/Antiforgery.sln +++ b/Antiforgery.sln @@ -1,21 +1,20 @@ - Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio 14 -VisualStudioVersion = 14.0.24720.0 +# Visual Studio 15 +VisualStudioVersion = 15.0.26127.0 MinimumVisualStudioVersion = 10.0.40219.1 Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{71D070C4-B325-48F7-9F25-DD4E91C2BBCA}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "test", "test", "{6EDD8B57-4DE8-4246-A6A3-47ECD92740B4}" EndProject -Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "Microsoft.AspNetCore.Antiforgery", "src\Microsoft.AspNetCore.Antiforgery\Microsoft.AspNetCore.Antiforgery.xproj", "{46FB03FB-7A44-4106-BDDE-D6F5417544AB}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Microsoft.AspNetCore.Antiforgery", "src\Microsoft.AspNetCore.Antiforgery\Microsoft.AspNetCore.Antiforgery.csproj", "{46FB03FB-7A44-4106-BDDE-D6F5417544AB}" EndProject -Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "Microsoft.AspNetCore.Antiforgery.Test", "test\Microsoft.AspNetCore.Antiforgery.Test\Microsoft.AspNetCore.Antiforgery.Test.xproj", "{415E83F8-6002-47E4-AA8E-CD5169C06F28}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Microsoft.AspNetCore.Antiforgery.Test", "test\Microsoft.AspNetCore.Antiforgery.Test\Microsoft.AspNetCore.Antiforgery.Test.csproj", "{415E83F8-6002-47E4-AA8E-CD5169C06F28}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "samples", "samples", "{D8C46ADF-E40A-4B48-ADE9-E1FA80466FE3}" EndProject -Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "AntiforgerySample", "samples\AntiforgerySample\AntiforgerySample.xproj", "{AF9E0784-5EDB-494F-B46C-1A8DA785C49C}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AntiforgerySample", "samples\AntiforgerySample\AntiforgerySample.csproj", "{AF9E0784-5EDB-494F-B46C-1A8DA785C49C}" EndProject -Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "Microsoft.AspNetCore.Antiforgery.FunctionalTests", "test\Microsoft.AspNetCore.Antiforgery.FunctionalTests\Microsoft.AspNetCore.Antiforgery.FunctionalTests.xproj", "{8B288810-5A96-4AF5-9836-8BA2D2953203}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Microsoft.AspNetCore.Antiforgery.FunctionalTests", "test\Microsoft.AspNetCore.Antiforgery.FunctionalTests\Microsoft.AspNetCore.Antiforgery.FunctionalTests.csproj", "{8B288810-5A96-4AF5-9836-8BA2D2953203}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution diff --git a/NuGet.config b/NuGet.config index 0fd623ffdd..8e65695611 100644 --- a/NuGet.config +++ b/NuGet.config @@ -1,7 +1,8 @@ - + + diff --git a/appveyor.yml b/appveyor.yml index be95b88d6f..773bfa8425 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -10,4 +10,5 @@ build_script: - build.cmd --quiet verify clone_depth: 1 test: off -deploy: off \ No newline at end of file +deploy: off +os: Visual Studio 2015 diff --git a/build.ps1 b/build.ps1 index 8f2f99691a..0605b59c01 100644 --- a/build.ps1 +++ b/build.ps1 @@ -33,7 +33,7 @@ cd $PSScriptRoot $repoFolder = $PSScriptRoot $env:REPO_FOLDER = $repoFolder -$koreBuildZip="https://github.com/aspnet/KoreBuild/archive/dev.zip" +$koreBuildZip="https://github.com/aspnet/KoreBuild/archive/feature/msbuild.zip" if ($env:KOREBUILD_ZIP) { $koreBuildZip=$env:KOREBUILD_ZIP diff --git a/build.sh b/build.sh index 4fd7ede788..07997d6c83 100755 --- a/build.sh +++ b/build.sh @@ -2,7 +2,7 @@ repoFolder="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" cd $repoFolder -koreBuildZip="https://github.com/aspnet/KoreBuild/archive/dev.zip" +koreBuildZip="https://github.com/aspnet/KoreBuild/archive/feature/msbuild.zip" if [ ! -z $KOREBUILD_ZIP ]; then koreBuildZip=$KOREBUILD_ZIP fi diff --git a/tools/Key.snk b/build/Key.snk similarity index 100% rename from tools/Key.snk rename to build/Key.snk diff --git a/build/common.props b/build/common.props new file mode 100644 index 0000000000..363c7862da --- /dev/null +++ b/build/common.props @@ -0,0 +1,19 @@ + + + + + Microsoft ASP.NET Core + https://github.com/aspnet/Antiforgery + git + $(MSBuildThisFileDirectory)Key.snk + true + true + 1.2.0-* + 1.6.2-* + $(VersionSuffix)-$(BuildNumber) + + + + + + \ No newline at end of file diff --git a/global.json b/global.json deleted file mode 100644 index 9ecb1c6efa..0000000000 --- a/global.json +++ /dev/null @@ -1,9 +0,0 @@ -{ - "projects": [ - "src", - "samples" - ], - "sdk": { - "version": "1.0.0-preview2-1-003180" - } -} \ No newline at end of file diff --git a/samples/AntiforgerySample/AntiforgerySample.csproj b/samples/AntiforgerySample/AntiforgerySample.csproj new file mode 100644 index 0000000000..44c1f381db --- /dev/null +++ b/samples/AntiforgerySample/AntiforgerySample.csproj @@ -0,0 +1,24 @@ + + + + net451;netcoreapp1.1 + win7-x64 + Exe + 1.2.0-* + + + + + + + + + + + + + + + + + diff --git a/samples/AntiforgerySample/AntiforgerySample.xproj b/samples/AntiforgerySample/AntiforgerySample.xproj deleted file mode 100644 index df07bd9b50..0000000000 --- a/samples/AntiforgerySample/AntiforgerySample.xproj +++ /dev/null @@ -1,18 +0,0 @@ - - - - 14.0 - $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion) - - - - af9e0784-5edb-494f-b46c-1a8da785c49c - .\obj - .\bin\ - - - 2.0 - 48542 - - - \ No newline at end of file diff --git a/samples/AntiforgerySample/project.json b/samples/AntiforgerySample/project.json deleted file mode 100644 index 328f7f8940..0000000000 --- a/samples/AntiforgerySample/project.json +++ /dev/null @@ -1,38 +0,0 @@ -{ - "version": "1.2.0-*", - "dependencies": { - "Microsoft.AspNetCore.Antiforgery": "1.2.0-*", - "Microsoft.AspNetCore.Http.Abstractions": "1.2.0-*", - "Microsoft.AspNetCore.Http.Extensions": "1.2.0-*", - "Microsoft.AspNetCore.Server.IISIntegration": "1.2.0-*", - "Microsoft.AspNetCore.Server.Kestrel": "1.2.0-*", - "Microsoft.AspNetCore.StaticFiles": "1.2.0-*", - "Newtonsoft.Json": "9.0.1" - }, - "buildOptions": { - "emitEntryPoint": true - }, - "frameworks": { - "net451": {}, - "netcoreapp1.1": { - "dependencies": { - "Microsoft.NETCore.App": { - "version": "1.2.0-*", - "type": "platform" - } - } - } - }, - "publishOptions": { - "include": [ - "wwwroot", - "web.config" - ] - }, - "tools": { - "Microsoft.AspNetCore.Server.IISIntegration.Tools": "1.0.0-*" - }, - "scripts": { - "postpublish": "dotnet publish-iis --publish-folder %publish:OutputPath% --framework %publish:FullTargetFramework%" - } -} \ No newline at end of file diff --git a/src/Microsoft.AspNetCore.Antiforgery/Microsoft.AspNetCore.Antiforgery.csproj b/src/Microsoft.AspNetCore.Antiforgery/Microsoft.AspNetCore.Antiforgery.csproj new file mode 100644 index 0000000000..8f5c0e3ff2 --- /dev/null +++ b/src/Microsoft.AspNetCore.Antiforgery/Microsoft.AspNetCore.Antiforgery.csproj @@ -0,0 +1,25 @@ + + + + + + An antiforgery system for ASP.NET Core designed to generate and validate tokens to prevent Cross-Site Request Forgery attacks. + netstandard1.3;net451 + $(NoWarn);CS1591 + true + aspnetcore;antiforgery + + + + + + + + + + + + + + + diff --git a/src/Microsoft.AspNetCore.Antiforgery/Microsoft.AspNetCore.Antiforgery.xproj b/src/Microsoft.AspNetCore.Antiforgery/Microsoft.AspNetCore.Antiforgery.xproj deleted file mode 100644 index 3799efa7b6..0000000000 --- a/src/Microsoft.AspNetCore.Antiforgery/Microsoft.AspNetCore.Antiforgery.xproj +++ /dev/null @@ -1,17 +0,0 @@ - - - - 14.0 - $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion) - - - - 46fb03fb-7a44-4106-bdde-d6f5417544ab - .\obj - .\bin\ - - - 2.0 - - - \ No newline at end of file diff --git a/src/Microsoft.AspNetCore.Antiforgery/Properties/AssemblyInfo.cs b/src/Microsoft.AspNetCore.Antiforgery/Properties/AssemblyInfo.cs index 5b79e64ce4..490fb19533 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/Properties/AssemblyInfo.cs +++ b/src/Microsoft.AspNetCore.Antiforgery/Properties/AssemblyInfo.cs @@ -1,14 +1,7 @@ // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. -using System.Reflection; -using System.Resources; using System.Runtime.CompilerServices; [assembly: InternalsVisibleTo("DynamicProxyGenAssembly2, PublicKey=0024000004800000940000000602000000240000525341310004000001000100c547cac37abd99c8db225ef2f6c8a3602f3b3606cc9891605d02baa56104f4cfc0734aa39b93bf7852f7d9266654753cc297e7d2edfe0bac1cdcf9f717241550e0a7b191195b7667bb4f64bcb8e2121380fd1d9d46ad2d92d2d15605093924cceaf74c4861eff62abf69b9291ed0a340e113be11e6a7d3113e92484cf7045cc7")] [assembly: InternalsVisibleTo("Microsoft.AspNetCore.Antiforgery.Test, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f33a29044fa9d740c9b3213a93e57c84b472c84e0b8a0e1ae48e67a9f8f6de9d5f7f3d52ac23e48ac51801f1dc950abe901da34d2a9e3baadb141a17c77ef3c565dd5ee5054b91cf63bb3c6ab83f72ab3aafe93d0fc3c2348b764fafb0b1c0733de51459aeab46580384bf9d74c4e28164b7cde247f891ba07891c9d872ad2bb")] -[assembly: AssemblyMetadata("Serviceable", "True")] -[assembly: NeutralResourcesLanguage("en-us")] -[assembly: AssemblyCompany("Microsoft Corporation.")] -[assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] -[assembly: AssemblyProduct("Microsoft ASP.NET Core")] diff --git a/src/Microsoft.AspNetCore.Antiforgery/project.json b/src/Microsoft.AspNetCore.Antiforgery/project.json deleted file mode 100644 index 963c586691..0000000000 --- a/src/Microsoft.AspNetCore.Antiforgery/project.json +++ /dev/null @@ -1,40 +0,0 @@ -{ - "description": "An antiforgery system for ASP.NET Core designed to generate and validate tokens to prevent Cross-Site Request Forgery attacks.", - "version": "1.2.0-*", - "buildOptions": { - "warningsAsErrors": true, - "keyFile": "../../tools/Key.snk", - "nowarn": [ - "CS1591" - ], - "xmlDoc": true - }, - "packOptions": { - "repository": { - "type": "git", - "url": "git://github.com/aspnet/antiforgery" - }, - "tags": [ - "aspnetcore", - "antiforgery" - ] - }, - "dependencies": { - "Microsoft.AspNetCore.DataProtection": "1.2.0-*", - "Microsoft.AspNetCore.Http.Abstractions": "1.2.0-*", - "Microsoft.AspNetCore.Http.Extensions": "1.2.0-*", - "Microsoft.AspNetCore.WebUtilities": "1.2.0-*", - "Microsoft.Extensions.ObjectPool": "1.2.0-*", - "NETStandard.Library": "1.6.2-*" - }, - "frameworks": { - "netstandard1.3": {}, - "net451": { - "frameworkAssemblies": { - "System.Runtime": { - "type": "build" - } - } - } - } -} \ No newline at end of file diff --git a/test/Microsoft.AspNetCore.Antiforgery.FunctionalTests/Microsoft.AspNetCore.Antiforgery.FunctionalTests.csproj b/test/Microsoft.AspNetCore.Antiforgery.FunctionalTests/Microsoft.AspNetCore.Antiforgery.FunctionalTests.csproj new file mode 100644 index 0000000000..34e281b1bb --- /dev/null +++ b/test/Microsoft.AspNetCore.Antiforgery.FunctionalTests/Microsoft.AspNetCore.Antiforgery.FunctionalTests.csproj @@ -0,0 +1,21 @@ + + + + + + netcoreapp1.1;net451 + win7-x64 + false + false + + + + + + + + + + + + diff --git a/test/Microsoft.AspNetCore.Antiforgery.FunctionalTests/Microsoft.AspNetCore.Antiforgery.FunctionalTests.xproj b/test/Microsoft.AspNetCore.Antiforgery.FunctionalTests/Microsoft.AspNetCore.Antiforgery.FunctionalTests.xproj deleted file mode 100644 index 1901f0cc82..0000000000 --- a/test/Microsoft.AspNetCore.Antiforgery.FunctionalTests/Microsoft.AspNetCore.Antiforgery.FunctionalTests.xproj +++ /dev/null @@ -1,20 +0,0 @@ - - - - 14.0 - $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion) - - - - 8b288810-5a96-4af5-9836-8ba2d2953203 - .\obj - .\bin\ - - - 2.0 - - - - - - \ No newline at end of file diff --git a/test/Microsoft.AspNetCore.Antiforgery.FunctionalTests/project.json b/test/Microsoft.AspNetCore.Antiforgery.FunctionalTests/project.json deleted file mode 100644 index 3a19511a4e..0000000000 --- a/test/Microsoft.AspNetCore.Antiforgery.FunctionalTests/project.json +++ /dev/null @@ -1,25 +0,0 @@ -{ - "dependencies": { - "AntiforgerySample": "1.2.0-*", - "dotnet-test-xunit": "2.2.0-*", - "Microsoft.AspNetCore.TestHost": "1.2.0-*", - "Moq": "4.6.36-*", - "xunit": "2.2.0-*" - }, - "testRunner": "xunit", - "frameworks": { - "netcoreapp1.1": { - "dependencies": { - "Microsoft.NETCore.App": { - "version": "1.2.0-*", - "type": "platform" - } - } - }, - "net451": { - "frameworkAssemblies": { - "System.Net.Http": "" - } - } - } -} \ No newline at end of file diff --git a/test/Microsoft.AspNetCore.Antiforgery.Test/Microsoft.AspNetCore.Antiforgery.Test.csproj b/test/Microsoft.AspNetCore.Antiforgery.Test/Microsoft.AspNetCore.Antiforgery.Test.csproj new file mode 100644 index 0000000000..1dfe470799 --- /dev/null +++ b/test/Microsoft.AspNetCore.Antiforgery.Test/Microsoft.AspNetCore.Antiforgery.Test.csproj @@ -0,0 +1,27 @@ + + + + + + netcoreapp1.1;net451 + + + + + + + + + + + + + + + + + + + + + diff --git a/test/Microsoft.AspNetCore.Antiforgery.Test/Microsoft.AspNetCore.Antiforgery.Test.xproj b/test/Microsoft.AspNetCore.Antiforgery.Test/Microsoft.AspNetCore.Antiforgery.Test.xproj deleted file mode 100644 index 87bf4fd855..0000000000 --- a/test/Microsoft.AspNetCore.Antiforgery.Test/Microsoft.AspNetCore.Antiforgery.Test.xproj +++ /dev/null @@ -1,20 +0,0 @@ - - - - 14.0 - $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion) - - - - 415e83f8-6002-47e4-aa8e-cd5169c06f28 - .\obj - .\bin\ - - - 2.0 - - - - - - \ No newline at end of file diff --git a/test/Microsoft.AspNetCore.Antiforgery.Test/project.json b/test/Microsoft.AspNetCore.Antiforgery.Test/project.json deleted file mode 100644 index e564174790..0000000000 --- a/test/Microsoft.AspNetCore.Antiforgery.Test/project.json +++ /dev/null @@ -1,35 +0,0 @@ -{ - "buildOptions": { - "warningsAsErrors": true, - "keyFile": "../../tools/Key.snk" - }, - "dependencies": { - "dotnet-test-xunit": "2.2.0-*", - "Microsoft.AspNetCore.Antiforgery": "1.2.0-*", - "Microsoft.AspNetCore.Http": "1.2.0-*", - "Microsoft.AspNetCore.Testing": "1.2.0-*", - "Microsoft.Extensions.DependencyInjection": "1.2.0-*", - "Microsoft.Extensions.Logging": "1.2.0-*", - "Microsoft.Extensions.Logging.Testing": "1.2.0-*", - "Microsoft.Extensions.WebEncoders": "1.2.0-*", - "Moq": "4.6.36-*", - "xunit": "2.2.0-*" - }, - "testRunner": "xunit", - "frameworks": { - "netcoreapp1.1": { - "dependencies": { - "Microsoft.NETCore.App": { - "version": "1.2.0-*", - "type": "platform" - }, - "System.Diagnostics.TraceSource": "4.4.0-*" - } - }, - "net451": { - "frameworkAssemblies": { - "System.Threading.Tasks": "" - } - } - } -} \ No newline at end of file diff --git a/version.props b/version.props new file mode 100644 index 0000000000..38c93687ab --- /dev/null +++ b/version.props @@ -0,0 +1,7 @@ + + + + 1.2.0 + preview1 + + \ No newline at end of file From 829050ec316ebdb2e8db0177119d843186d7de03 Mon Sep 17 00:00:00 2001 From: Ryan Brandenburg Date: Wed, 8 Feb 2017 09:36:44 -0800 Subject: [PATCH 175/296] Move samples to Entropy (#120) --- README.md | 6 +- .../AntiforgerySample.csproj | 24 ----- samples/AntiforgerySample/Startup.cs | 81 -------------- samples/AntiforgerySample/TodoItem.cs | 13 --- samples/AntiforgerySample/TodoRepository.cs | 31 ------ samples/AntiforgerySample/web.config | 9 -- samples/AntiforgerySample/wwwroot/Index.html | 47 -------- samples/AntiforgerySample/wwwroot/app.js | 4 - .../AntiforgerySample/wwwroot/controllers.js | 21 ---- samples/AntiforgerySample/wwwroot/services.js | 22 ---- .../AntiForgerySampleTestFixture.cs | 44 -------- .../AntiforgerySampleTest.cs | 101 ------------------ ...NetCore.Antiforgery.FunctionalTests.csproj | 21 ---- 13 files changed, 5 insertions(+), 419 deletions(-) delete mode 100644 samples/AntiforgerySample/AntiforgerySample.csproj delete mode 100644 samples/AntiforgerySample/Startup.cs delete mode 100644 samples/AntiforgerySample/TodoItem.cs delete mode 100644 samples/AntiforgerySample/TodoRepository.cs delete mode 100644 samples/AntiforgerySample/web.config delete mode 100644 samples/AntiforgerySample/wwwroot/Index.html delete mode 100644 samples/AntiforgerySample/wwwroot/app.js delete mode 100644 samples/AntiforgerySample/wwwroot/controllers.js delete mode 100644 samples/AntiforgerySample/wwwroot/services.js delete mode 100644 test/Microsoft.AspNetCore.Antiforgery.FunctionalTests/AntiForgerySampleTestFixture.cs delete mode 100644 test/Microsoft.AspNetCore.Antiforgery.FunctionalTests/AntiforgerySampleTest.cs delete mode 100644 test/Microsoft.AspNetCore.Antiforgery.FunctionalTests/Microsoft.AspNetCore.Antiforgery.FunctionalTests.csproj diff --git a/README.md b/README.md index 3ea14d6634..b0430c7868 100644 --- a/README.md +++ b/README.md @@ -7,4 +7,8 @@ Travis: [![Travis](https://travis-ci.org/aspnet/Antiforgery.svg?branch=dev)](h Antiforgery system for generating secure tokens to prevent Cross-Site Request Forgery attacks. -This project is part of ASP.NET Core. You can find samples, documentation and getting started instructions for ASP.NET Core at the [Home](https://github.com/aspnet/home) repo. +This project is part of ASP.NET Core. You can find documentation and getting started instructions for ASP.NET Core at the [Home](https://github.com/aspnet/home) repo. + +Samples can be found in [Entropy](https://github.com/aspnet/Entropy). +The [MVC](https://github.com/aspnet/Entropy/tree/dev/samples/Antiforgery.MvcWithAuthAndAjax) sample shows how to use Antiforgery in MVC when making AJAX requests. +The [Angular](https://github.com/aspnet/Entropy/tree/dev/samples/Antiforgery.Angular1) sample shows how to use Antiforgery with Angular 1. \ No newline at end of file diff --git a/samples/AntiforgerySample/AntiforgerySample.csproj b/samples/AntiforgerySample/AntiforgerySample.csproj deleted file mode 100644 index 44c1f381db..0000000000 --- a/samples/AntiforgerySample/AntiforgerySample.csproj +++ /dev/null @@ -1,24 +0,0 @@ - - - - net451;netcoreapp1.1 - win7-x64 - Exe - 1.2.0-* - - - - - - - - - - - - - - - - - diff --git a/samples/AntiforgerySample/Startup.cs b/samples/AntiforgerySample/Startup.cs deleted file mode 100644 index 1eff1c760d..0000000000 --- a/samples/AntiforgerySample/Startup.cs +++ /dev/null @@ -1,81 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.IO; -using Microsoft.AspNetCore.Antiforgery; -using Microsoft.AspNetCore.Builder; -using Microsoft.AspNetCore.Hosting; -using Microsoft.AspNetCore.Http; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Options; -using Newtonsoft.Json; - -namespace AntiforgerySample -{ - public class Startup - { - public void ConfigureServices(IServiceCollection services) - { - // Angular's default header name for sending the XSRF token. - services.AddAntiforgery(options => options.HeaderName = "X-XSRF-TOKEN"); - - services.AddSingleton(); - } - - public void Configure(IApplicationBuilder app, IAntiforgery antiforgery, IOptions options, TodoRepository repository) - { - app.Use(next => context => - { - if ( - string.Equals(context.Request.Path.Value, "/", StringComparison.OrdinalIgnoreCase) || - string.Equals(context.Request.Path.Value, "/index.html", StringComparison.OrdinalIgnoreCase)) - { - // We can send the request token as a JavaScript-readable cookie, and Angular will use it by default. - var tokens = antiforgery.GetAndStoreTokens(context); - context.Response.Cookies.Append("XSRF-TOKEN", tokens.RequestToken, new CookieOptions() { HttpOnly = false }); - } - - return next(context); - }); - - app.UseDefaultFiles(); - app.UseStaticFiles(); - - app.Map("/api/items", a => a.Run(async context => - { - if (string.Equals("GET", context.Request.Method, StringComparison.OrdinalIgnoreCase)) - { - var items = repository.GetItems(); - await context.Response.WriteAsync(JsonConvert.SerializeObject(items)); - } - else if (string.Equals("POST", context.Request.Method, StringComparison.OrdinalIgnoreCase)) - { - // This will throw if the token is invalid. - await antiforgery.ValidateRequestAsync(context); - - var serializer = new JsonSerializer(); - using (var reader = new JsonTextReader(new StreamReader(context.Request.Body))) - { - var item = serializer.Deserialize(reader); - repository.Add(item); - } - - context.Response.StatusCode = 204; - } - })); - } - - public static void Main(string[] args) - { - var host = new WebHostBuilder() - .UseKestrel() - .UseIISIntegration() - .UseStartup() - .Build(); - - host.Run(); - } - } -} - diff --git a/samples/AntiforgerySample/TodoItem.cs b/samples/AntiforgerySample/TodoItem.cs deleted file mode 100644 index e58adb37ad..0000000000 --- a/samples/AntiforgerySample/TodoItem.cs +++ /dev/null @@ -1,13 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using Newtonsoft.Json; - -namespace AntiforgerySample -{ - public class TodoItem - { - [JsonProperty(PropertyName = "name")] - public string Name { get; set; } - } -} diff --git a/samples/AntiforgerySample/TodoRepository.cs b/samples/AntiforgerySample/TodoRepository.cs deleted file mode 100644 index 8625882c0a..0000000000 --- a/samples/AntiforgerySample/TodoRepository.cs +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System.Collections.Generic; - -namespace AntiforgerySample -{ - public class TodoRepository - { - private List _items; - - public TodoRepository() - { - _items = new List() - { - new TodoItem() { Name = "Mow the lawn" }, - new TodoItem() { Name = "Do the dishes" }, - }; - } - - public IEnumerable GetItems() - { - return _items; - } - - public void Add(TodoItem item) - { - _items.Add(item); - } - } -} diff --git a/samples/AntiforgerySample/web.config b/samples/AntiforgerySample/web.config deleted file mode 100644 index f7ac679334..0000000000 --- a/samples/AntiforgerySample/web.config +++ /dev/null @@ -1,9 +0,0 @@ - - - - - - - - - \ No newline at end of file diff --git a/samples/AntiforgerySample/wwwroot/Index.html b/samples/AntiforgerySample/wwwroot/Index.html deleted file mode 100644 index 8d130b34c2..0000000000 --- a/samples/AntiforgerySample/wwwroot/Index.html +++ /dev/null @@ -1,47 +0,0 @@ - - - - - - Todo List Antiforgery Sample - - - -
-
-

Todo List Antiforgery Sample

-
-
-
- - - - - - - - - - -
TODO List
{{$index + 1}} - {{item.name}} -
-
-
-
-
-
- - -
- -
-
-
- - - - - - - diff --git a/samples/AntiforgerySample/wwwroot/app.js b/samples/AntiforgerySample/wwwroot/app.js deleted file mode 100644 index f57425a553..0000000000 --- a/samples/AntiforgerySample/wwwroot/app.js +++ /dev/null @@ -1,4 +0,0 @@ -angular.module('TODO', [ - 'TODO.controllers', - 'TODO.services' -]); \ No newline at end of file diff --git a/samples/AntiforgerySample/wwwroot/controllers.js b/samples/AntiforgerySample/wwwroot/controllers.js deleted file mode 100644 index df35c5cab0..0000000000 --- a/samples/AntiforgerySample/wwwroot/controllers.js +++ /dev/null @@ -1,21 +0,0 @@ -angular.module('TODO.controllers', []). -controller('todoController', function ($scope, todoApi) { - $scope.itemList = []; - $scope.item = {}; - - $scope.refresh = function (item) { - todoApi.getItems().success(function (response) { - $scope.itemList = response; - }); - }; - - $scope.create = function (item) { - todoApi.create(item).success(function (response) { - $scope.item = {}; - $scope.refresh(); - }); - }; - - // Load initial items - $scope.refresh(); -}); \ No newline at end of file diff --git a/samples/AntiforgerySample/wwwroot/services.js b/samples/AntiforgerySample/wwwroot/services.js deleted file mode 100644 index be27281ba6..0000000000 --- a/samples/AntiforgerySample/wwwroot/services.js +++ /dev/null @@ -1,22 +0,0 @@ -angular.module('TODO.services', []). - factory('todoApi', function ($http) { - - var todoApi = {}; - - todoApi.getItems = function () { - return $http({ - method: 'GET', - url: '/api/items' - }); - } - - todoApi.create = function (item) { - return $http({ - method: 'POST', - url: '/api/items', - data: item - }); - }; - - return todoApi; - }); \ No newline at end of file diff --git a/test/Microsoft.AspNetCore.Antiforgery.FunctionalTests/AntiForgerySampleTestFixture.cs b/test/Microsoft.AspNetCore.Antiforgery.FunctionalTests/AntiForgerySampleTestFixture.cs deleted file mode 100644 index 5958064a0c..0000000000 --- a/test/Microsoft.AspNetCore.Antiforgery.FunctionalTests/AntiForgerySampleTestFixture.cs +++ /dev/null @@ -1,44 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; -using System.Net.Http; -using Microsoft.AspNetCore.Hosting; -using Microsoft.AspNetCore.TestHost; -using Microsoft.Extensions.Configuration; - -namespace Microsoft.AspNetCore.Antiforgery.FunctionalTests -{ - public class AntiForgerySampleTestFixture : IDisposable - { - private readonly TestServer _server; - - public AntiForgerySampleTestFixture() - { - var configurationBuilder = new ConfigurationBuilder(); - - configurationBuilder.AddInMemoryCollection(new[] - { - new KeyValuePair("webroot", "wwwroot") - }); - - var builder = new WebHostBuilder() - .UseConfiguration(configurationBuilder.Build()) - .UseStartup(typeof(AntiforgerySample.Startup)); - - _server = new TestServer(builder); - - Client = _server.CreateClient(); - Client.BaseAddress = new Uri("http://localhost"); - } - - public HttpClient Client { get; } - - public void Dispose() - { - Client.Dispose(); - _server.Dispose(); - } - } -} diff --git a/test/Microsoft.AspNetCore.Antiforgery.FunctionalTests/AntiforgerySampleTest.cs b/test/Microsoft.AspNetCore.Antiforgery.FunctionalTests/AntiforgerySampleTest.cs deleted file mode 100644 index 52c46bd6b6..0000000000 --- a/test/Microsoft.AspNetCore.Antiforgery.FunctionalTests/AntiforgerySampleTest.cs +++ /dev/null @@ -1,101 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System.Collections.Generic; -using System.Linq; -using System.Net; -using System.Net.Http; -using System.Threading.Tasks; -using Microsoft.Net.Http.Headers; -using Xunit; - -namespace Microsoft.AspNetCore.Antiforgery.FunctionalTests -{ - public class AntiforgerySampleTests : IClassFixture - { - public AntiforgerySampleTests(AntiForgerySampleTestFixture fixture) - { - Client = fixture.Client; - } - - public HttpClient Client { get; } - - [Fact] - public async Task ItemsPage_SetsXSRFTokens() - { - // Arrange & Act - var response = await Client.GetAsync("http://localhost/Index.html"); - - // Assert - var setCookieHeaderValue = RetrieveAntiforgeryCookie(response); - Assert.NotNull(setCookieHeaderValue); - Assert.False(string.IsNullOrEmpty(setCookieHeaderValue.Value)); - Assert.Null(setCookieHeaderValue.Domain); - Assert.Equal("/", setCookieHeaderValue.Path); - Assert.False(setCookieHeaderValue.Secure); - - setCookieHeaderValue = RetrieveAntiforgeryToken(response); - Assert.NotNull(setCookieHeaderValue); - Assert.False(string.IsNullOrEmpty(setCookieHeaderValue.Value)); - Assert.Null(setCookieHeaderValue.Domain); - Assert.Equal("/", setCookieHeaderValue.Path); - Assert.False(setCookieHeaderValue.Secure); - } - - [Fact] - public async Task PostItem_NeedsHeader() - { - // Arrange - var httpResponse = await Client.GetAsync("http://localhost"); - var cookie = RetrieveAntiforgeryCookie(httpResponse); - - var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, "http://localhost/api/items"); - - // Act - var exception = await Assert.ThrowsAsync(async () => - { - var response = await Client.SendAsync(httpRequestMessage); - }); - - // Assert - Assert.Contains($"The required antiforgery cookie \"{cookie.Name}\" is not present.", exception.Message); - } - - [Fact] - public async Task PostItem_XSRFWorks() - { - // Arrange - var httpResponse = await Client.GetAsync("/Index.html"); - - var cookie = RetrieveAntiforgeryCookie(httpResponse); - var token = RetrieveAntiforgeryToken(httpResponse); - - var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, "http://localhost/api/items"); - - httpRequestMessage.Headers.Add("Cookie", $"{cookie.Name}={cookie.Value}"); - httpRequestMessage.Headers.Add("X-XSRF-TOKEN", token.Value); - - // Act - var response = await Client.SendAsync(httpRequestMessage); - - // Assert - Assert.Equal(HttpStatusCode.NoContent, response.StatusCode); - } - - private static SetCookieHeaderValue RetrieveAntiforgeryToken(HttpResponseMessage response) - { - return response.Headers.GetValues(HeaderNames.SetCookie) - .Select(setCookieValue => SetCookieHeaderValue.Parse(setCookieValue)) - .Where(setCookieHeaderValue => setCookieHeaderValue.Name == "XSRF-TOKEN") - .FirstOrDefault(); - } - - private static SetCookieHeaderValue RetrieveAntiforgeryCookie(HttpResponseMessage response) - { - return response.Headers.GetValues(HeaderNames.SetCookie) - .Select(setCookieValue => SetCookieHeaderValue.Parse(setCookieValue)) - .Where(setCookieHeaderValue => setCookieHeaderValue.Name.StartsWith(".AspNetCore.Antiforgery.")) - .FirstOrDefault(); - } - } -} \ No newline at end of file diff --git a/test/Microsoft.AspNetCore.Antiforgery.FunctionalTests/Microsoft.AspNetCore.Antiforgery.FunctionalTests.csproj b/test/Microsoft.AspNetCore.Antiforgery.FunctionalTests/Microsoft.AspNetCore.Antiforgery.FunctionalTests.csproj deleted file mode 100644 index 34e281b1bb..0000000000 --- a/test/Microsoft.AspNetCore.Antiforgery.FunctionalTests/Microsoft.AspNetCore.Antiforgery.FunctionalTests.csproj +++ /dev/null @@ -1,21 +0,0 @@ - - - - - - netcoreapp1.1;net451 - win7-x64 - false - false - - - - - - - - - - - - From 69abfa893b9e6f4ab3bab125be84be1b06fbcdcb Mon Sep 17 00:00:00 2001 From: Nate McMaster Date: Thu, 9 Feb 2017 13:29:00 -0800 Subject: [PATCH 176/296] Cleanup solution file --- Antiforgery.sln | 22 +++------------------- 1 file changed, 3 insertions(+), 19 deletions(-) diff --git a/Antiforgery.sln b/Antiforgery.sln index 04e95ee7f6..44bca25a08 100644 --- a/Antiforgery.sln +++ b/Antiforgery.sln @@ -1,20 +1,14 @@ Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio 15 -VisualStudioVersion = 15.0.26127.0 +VisualStudioVersion = 15.0.26208.0 MinimumVisualStudioVersion = 10.0.40219.1 Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{71D070C4-B325-48F7-9F25-DD4E91C2BBCA}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "test", "test", "{6EDD8B57-4DE8-4246-A6A3-47ECD92740B4}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Microsoft.AspNetCore.Antiforgery", "src\Microsoft.AspNetCore.Antiforgery\Microsoft.AspNetCore.Antiforgery.csproj", "{46FB03FB-7A44-4106-BDDE-D6F5417544AB}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.AspNetCore.Antiforgery", "src\Microsoft.AspNetCore.Antiforgery\Microsoft.AspNetCore.Antiforgery.csproj", "{46FB03FB-7A44-4106-BDDE-D6F5417544AB}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Microsoft.AspNetCore.Antiforgery.Test", "test\Microsoft.AspNetCore.Antiforgery.Test\Microsoft.AspNetCore.Antiforgery.Test.csproj", "{415E83F8-6002-47E4-AA8E-CD5169C06F28}" -EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "samples", "samples", "{D8C46ADF-E40A-4B48-ADE9-E1FA80466FE3}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AntiforgerySample", "samples\AntiforgerySample\AntiforgerySample.csproj", "{AF9E0784-5EDB-494F-B46C-1A8DA785C49C}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Microsoft.AspNetCore.Antiforgery.FunctionalTests", "test\Microsoft.AspNetCore.Antiforgery.FunctionalTests\Microsoft.AspNetCore.Antiforgery.FunctionalTests.csproj", "{8B288810-5A96-4AF5-9836-8BA2D2953203}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.AspNetCore.Antiforgery.Test", "test\Microsoft.AspNetCore.Antiforgery.Test\Microsoft.AspNetCore.Antiforgery.Test.csproj", "{415E83F8-6002-47E4-AA8E-CD5169C06F28}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution @@ -30,14 +24,6 @@ Global {415E83F8-6002-47E4-AA8E-CD5169C06F28}.Debug|Any CPU.Build.0 = Debug|Any CPU {415E83F8-6002-47E4-AA8E-CD5169C06F28}.Release|Any CPU.ActiveCfg = Release|Any CPU {415E83F8-6002-47E4-AA8E-CD5169C06F28}.Release|Any CPU.Build.0 = Release|Any CPU - {AF9E0784-5EDB-494F-B46C-1A8DA785C49C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {AF9E0784-5EDB-494F-B46C-1A8DA785C49C}.Debug|Any CPU.Build.0 = Debug|Any CPU - {AF9E0784-5EDB-494F-B46C-1A8DA785C49C}.Release|Any CPU.ActiveCfg = Release|Any CPU - {AF9E0784-5EDB-494F-B46C-1A8DA785C49C}.Release|Any CPU.Build.0 = Release|Any CPU - {8B288810-5A96-4AF5-9836-8BA2D2953203}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {8B288810-5A96-4AF5-9836-8BA2D2953203}.Debug|Any CPU.Build.0 = Debug|Any CPU - {8B288810-5A96-4AF5-9836-8BA2D2953203}.Release|Any CPU.ActiveCfg = Release|Any CPU - {8B288810-5A96-4AF5-9836-8BA2D2953203}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -45,7 +31,5 @@ Global GlobalSection(NestedProjects) = preSolution {46FB03FB-7A44-4106-BDDE-D6F5417544AB} = {71D070C4-B325-48F7-9F25-DD4E91C2BBCA} {415E83F8-6002-47E4-AA8E-CD5169C06F28} = {6EDD8B57-4DE8-4246-A6A3-47ECD92740B4} - {AF9E0784-5EDB-494F-B46C-1A8DA785C49C} = {D8C46ADF-E40A-4B48-ADE9-E1FA80466FE3} - {8B288810-5A96-4AF5-9836-8BA2D2953203} = {6EDD8B57-4DE8-4246-A6A3-47ECD92740B4} EndGlobalSection EndGlobal From 00fe95253aac667225e68de2bb36b043bd0412d3 Mon Sep 17 00:00:00 2001 From: Nate McMaster Date: Thu, 9 Feb 2017 17:29:07 -0800 Subject: [PATCH 177/296] Delete makefile.shade --- makefile.shade | 7 ------- 1 file changed, 7 deletions(-) delete mode 100644 makefile.shade diff --git a/makefile.shade b/makefile.shade deleted file mode 100644 index 562494d144..0000000000 --- a/makefile.shade +++ /dev/null @@ -1,7 +0,0 @@ - -var VERSION='0.1' -var FULL_VERSION='0.1' -var AUTHORS='Microsoft Open Technologies, Inc.' - -use-standard-lifecycle -k-standard-goals From 221c582a6f41e73cde255e81e9e53b85a23b69ca Mon Sep 17 00:00:00 2001 From: Doug Bunting Date: Tue, 14 Feb 2017 12:11:52 -0800 Subject: [PATCH 178/296] Bump test projects up to .NET 4.5.2 - aspnet/Testing#248 - xUnit no longer supports .NET 4.5.1 - build tests for desktop .NET only on Windows --- .../Internal/DefaultClaimUidExtractorTest.cs | 2 +- .../Microsoft.AspNetCore.Antiforgery.Test.csproj | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultClaimUidExtractorTest.cs b/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultClaimUidExtractorTest.cs index 5b694ace88..81bef79689 100644 --- a/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultClaimUidExtractorTest.cs +++ b/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultClaimUidExtractorTest.cs @@ -60,7 +60,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal identity.AddClaim(new Claim(ClaimTypes.Email, "someone@antifrogery.com")); identity.AddClaim(new Claim(ClaimTypes.GivenName, "some")); identity.AddClaim(new Claim(ClaimTypes.Surname, "one")); -#if NET451 +#if NET452 // CoreCLR doesn't support an 'empty' name identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, string.Empty)); #endif diff --git a/test/Microsoft.AspNetCore.Antiforgery.Test/Microsoft.AspNetCore.Antiforgery.Test.csproj b/test/Microsoft.AspNetCore.Antiforgery.Test/Microsoft.AspNetCore.Antiforgery.Test.csproj index 1dfe470799..17ce5bf2cf 100644 --- a/test/Microsoft.AspNetCore.Antiforgery.Test/Microsoft.AspNetCore.Antiforgery.Test.csproj +++ b/test/Microsoft.AspNetCore.Antiforgery.Test/Microsoft.AspNetCore.Antiforgery.Test.csproj @@ -3,7 +3,8 @@ - netcoreapp1.1;net451 + netcoreapp1.1;net452 + netcoreapp1.1 From c8053845a46cd62223ccc00201dcf1c869ebe858 Mon Sep 17 00:00:00 2001 From: Nate McMaster Date: Tue, 14 Feb 2017 16:03:54 -0800 Subject: [PATCH 179/296] Downgrade to stable packages --- build/common.props | 5 ++--- build/dependencies.props | 6 ++++++ .../Microsoft.AspNetCore.Antiforgery.Test.csproj | 4 ---- 3 files changed, 8 insertions(+), 7 deletions(-) create mode 100644 build/dependencies.props diff --git a/build/common.props b/build/common.props index 363c7862da..7c783e99d3 100644 --- a/build/common.props +++ b/build/common.props @@ -1,4 +1,5 @@ + @@ -8,12 +9,10 @@ $(MSBuildThisFileDirectory)Key.snk true true - 1.2.0-* - 1.6.2-* $(VersionSuffix)-$(BuildNumber) - \ No newline at end of file + diff --git a/build/dependencies.props b/build/dependencies.props new file mode 100644 index 0000000000..e704edaec0 --- /dev/null +++ b/build/dependencies.props @@ -0,0 +1,6 @@ + + + 1.6.1 + 4.3.0 + + diff --git a/test/Microsoft.AspNetCore.Antiforgery.Test/Microsoft.AspNetCore.Antiforgery.Test.csproj b/test/Microsoft.AspNetCore.Antiforgery.Test/Microsoft.AspNetCore.Antiforgery.Test.csproj index 17ce5bf2cf..c9db70010b 100644 --- a/test/Microsoft.AspNetCore.Antiforgery.Test/Microsoft.AspNetCore.Antiforgery.Test.csproj +++ b/test/Microsoft.AspNetCore.Antiforgery.Test/Microsoft.AspNetCore.Antiforgery.Test.csproj @@ -21,8 +21,4 @@ - - - - From 0e0fe9b43614cd3110bfd969a512a0b7dcca6eeb Mon Sep 17 00:00:00 2001 From: Nate McMaster Date: Wed, 1 Mar 2017 18:14:13 -0800 Subject: [PATCH 180/296] Change korebuild branch and fix argument forwarding in bootstrapper --- build.ps1 | 16 ++++++++-------- build.sh | 22 +++++++++++----------- 2 files changed, 19 insertions(+), 19 deletions(-) diff --git a/build.ps1 b/build.ps1 index 0605b59c01..5bf0e2c113 100644 --- a/build.ps1 +++ b/build.ps1 @@ -1,6 +1,6 @@ $ErrorActionPreference = "Stop" -function DownloadWithRetry([string] $url, [string] $downloadLocation, [int] $retries) +function DownloadWithRetry([string] $url, [string] $downloadLocation, [int] $retries) { while($true) { @@ -19,7 +19,7 @@ function DownloadWithRetry([string] $url, [string] $downloadLocation, [int] $ret Start-Sleep -Seconds 10 } - else + else { $exception = $_.Exception throw $exception @@ -33,7 +33,7 @@ cd $PSScriptRoot $repoFolder = $PSScriptRoot $env:REPO_FOLDER = $repoFolder -$koreBuildZip="https://github.com/aspnet/KoreBuild/archive/feature/msbuild.zip" +$koreBuildZip="https://github.com/aspnet/KoreBuild/archive/dev.zip" if ($env:KOREBUILD_ZIP) { $koreBuildZip=$env:KOREBUILD_ZIP @@ -43,18 +43,18 @@ $buildFolder = ".build" $buildFile="$buildFolder\KoreBuild.ps1" if (!(Test-Path $buildFolder)) { - Write-Host "Downloading KoreBuild from $koreBuildZip" - + Write-Host "Downloading KoreBuild from $koreBuildZip" + $tempFolder=$env:TEMP + "\KoreBuild-" + [guid]::NewGuid() New-Item -Path "$tempFolder" -Type directory | Out-Null $localZipFile="$tempFolder\korebuild.zip" - + DownloadWithRetry -url $koreBuildZip -downloadLocation $localZipFile -retries 6 Add-Type -AssemblyName System.IO.Compression.FileSystem [System.IO.Compression.ZipFile]::ExtractToDirectory($localZipFile, $tempFolder) - + New-Item -Path "$buildFolder" -Type directory | Out-Null copy-item "$tempFolder\**\build\*" $buildFolder -Recurse @@ -64,4 +64,4 @@ if (!(Test-Path $buildFolder)) { } } -&"$buildFile" $args \ No newline at end of file +&"$buildFile" @args diff --git a/build.sh b/build.sh index 07997d6c83..b0bcadb579 100755 --- a/build.sh +++ b/build.sh @@ -2,7 +2,7 @@ repoFolder="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" cd $repoFolder -koreBuildZip="https://github.com/aspnet/KoreBuild/archive/feature/msbuild.zip" +koreBuildZip="https://github.com/aspnet/KoreBuild/archive/dev.zip" if [ ! -z $KOREBUILD_ZIP ]; then koreBuildZip=$KOREBUILD_ZIP fi @@ -12,12 +12,12 @@ buildFile="$buildFolder/KoreBuild.sh" if test ! -d $buildFolder; then echo "Downloading KoreBuild from $koreBuildZip" - - tempFolder="/tmp/KoreBuild-$(uuidgen)" + + tempFolder="/tmp/KoreBuild-$(uuidgen)" mkdir $tempFolder - + localZipFile="$tempFolder/korebuild.zip" - + retries=6 until (wget -O $localZipFile $koreBuildZip 2>/dev/null || curl -o $localZipFile --location $koreBuildZip 2>/dev/null) do @@ -29,18 +29,18 @@ if test ! -d $buildFolder; then echo "Waiting 10 seconds before retrying. Retries left: $retries" sleep 10s done - + unzip -q -d $tempFolder $localZipFile - + mkdir $buildFolder cp -r $tempFolder/**/build/** $buildFolder - + chmod +x $buildFile - + # Cleanup if test -d $tempFolder; then - rm -rf $tempFolder + rm -rf $tempFolder fi fi -$buildFile -r $repoFolder "$@" \ No newline at end of file +$buildFile -r $repoFolder "$@" From ce243b3d34e1d7fa6f1bcf0023029ff245be7775 Mon Sep 17 00:00:00 2001 From: Nate McMaster Date: Wed, 1 Mar 2017 18:19:36 -0800 Subject: [PATCH 181/296] Update Travis and AppVeyor settings --- .travis.yml | 2 +- appveyor.yml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.travis.yml b/.travis.yml index bce76eefa4..e29e710b4e 100644 --- a/.travis.yml +++ b/.travis.yml @@ -29,7 +29,7 @@ branches: before_install: - if test "$TRAVIS_OS_NAME" == "osx"; then brew update; brew install openssl; ln -s /usr/local/opt/openssl/lib/libcrypto.1.0.0.dylib /usr/local/lib/; ln -s /usr/local/opt/openssl/lib/libssl.1.0.0.dylib /usr/local/lib/; fi script: - - ./build.sh --quiet verify + - ./build.sh notifications: webhooks: secure: "dzKsW/YJVie2UeYKMlKFA9dcHv0WpF4IKd7z/yEhV96eB5e2Pls+vtQFUP86Wg/fcqeLHAmb0GazXnomPg2cX13ihz+mF0hCvA58UTczNpwwfTZd7VHQe9Ti93Zoo49HkTFBbIDMns9eUxhcEo4T4lC85dG4ZRz7v8X6/Nlr71PMIGYI29Uyur/1oPrnNI7DBweOY4Z1Xhl5cfaSPd945VM8QPHeM494XGmgldGpIZs+LjZbA8S3xxB0YaxpAwGKO4gWSXL2fP4y1z5rFEY1JZamPaedA3dICVi3BVDjJ4l3sn3fEBxOAv8QwjHvSu0xWK/MAIX/SmY7ScgIND+UMjGFTaeZLYN18hJDm+a4mAx/tPaqsOGAKm9F/aVQAzP0g4z+VAVDz1iqxDWe+x/cK4DPjUbLXpP6Y6jtrVES/TkKNuLNA/NUOp+vDPXieDaQAmeU2l6M2el1PscQPtla6KIS1oDDiuHeWC/b4suCAJVsads25y7KyncmmwYE1Tgh1sUJa+Vk9c/hxiIuDJQUWxmi/4BGjDYO29y60jc2niimzvQ3sV2x+Rh81zJaLWXNYdIgugzQpe4nG8wQDbLuEAlfINBt7cIxw3MK3ov4MV5MVRaDVMEm0A5yIN9Mz83USPkuXxfhGtOo6YU1Ny/D2bjc9LI7lGHbjQtFlJa6U6c=" diff --git a/appveyor.yml b/appveyor.yml index 773bfa8425..4af9de6b8a 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -7,7 +7,7 @@ branches: - dev - /^(.*\/)?ci-.*$/ build_script: - - build.cmd --quiet verify + - ps: .\build.ps1 clone_depth: 1 test: off deploy: off From 1c9a4f5705c02d182e6beefa96739de81cd3d850 Mon Sep 17 00:00:00 2001 From: Juan Naputi Date: Wed, 1 Mar 2017 09:07:52 -0800 Subject: [PATCH 182/296] Fixed typo in IAntiforgery file --- src/Microsoft.AspNetCore.Antiforgery/IAntiforgery.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Microsoft.AspNetCore.Antiforgery/IAntiforgery.cs b/src/Microsoft.AspNetCore.Antiforgery/IAntiforgery.cs index d6dd05aeae..89630a46d0 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/IAntiforgery.cs +++ b/src/Microsoft.AspNetCore.Antiforgery/IAntiforgery.cs @@ -42,8 +42,8 @@ namespace Microsoft.AspNetCore.Antiforgery ///
/// The associated with the current request. /// - /// A that, when completed, returns true if the is requst uses a safe HTTP - /// method or contains a value antiforgery token, otherwise returns false. + /// A that, when completed, returns true if the request uses a safe HTTP + /// method or contains a valid antiforgery token, otherwise returns false. /// Task IsRequestValidAsync(HttpContext httpContext); From 411da70cb5f6296e11465b10b40e19376f7b5e04 Mon Sep 17 00:00:00 2001 From: David Fowler Date: Wed, 8 Mar 2017 20:16:43 -0800 Subject: [PATCH 183/296] Update .travis.yml --- .travis.yml | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/.travis.yml b/.travis.yml index e29e710b4e..bcb80c9026 100644 --- a/.travis.yml +++ b/.travis.yml @@ -14,8 +14,7 @@ env: global: - DOTNET_SKIP_FIRST_TIME_EXPERIENCE: true - DOTNET_CLI_TELEMETRY_OPTOUT: 1 -mono: - - 4.0.5 +mono: none os: - linux - osx From aa63089a36403d6d736829ec58590626518fde1f Mon Sep 17 00:00:00 2001 From: Nate McMaster Date: Tue, 14 Mar 2017 13:39:30 -0700 Subject: [PATCH 184/296] Update appveyor and travis settings --- .travis.yml | 1 - appveyor.yml | 2 +- 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/.travis.yml b/.travis.yml index bcb80c9026..61dbcbdc56 100644 --- a/.travis.yml +++ b/.travis.yml @@ -18,7 +18,6 @@ mono: none os: - linux - osx -osx_image: xcode7.3 branches: only: - master diff --git a/appveyor.yml b/appveyor.yml index 4af9de6b8a..1041615c68 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -11,4 +11,4 @@ build_script: clone_depth: 1 test: off deploy: off -os: Visual Studio 2015 +os: Visual Studio 2017 From ce6c832465838649d67c7fb7bb225794f20c5b16 Mon Sep 17 00:00:00 2001 From: Nate McMaster Date: Wed, 15 Mar 2017 11:39:16 -0700 Subject: [PATCH 185/296] Unify dependency version to one file --- .bowerrc | 3 --- build/common.props | 4 ++++ build/dependencies.props | 6 ++++- .../Microsoft.AspNetCore.Antiforgery.csproj | 14 ++++------- ...crosoft.AspNetCore.Antiforgery.Test.csproj | 23 +++++++++++-------- 5 files changed, 27 insertions(+), 23 deletions(-) delete mode 100644 .bowerrc diff --git a/.bowerrc b/.bowerrc deleted file mode 100644 index eae11312d8..0000000000 --- a/.bowerrc +++ /dev/null @@ -1,3 +0,0 @@ -{ - "directory": "wwwroot/lib" -} \ No newline at end of file diff --git a/build/common.props b/build/common.props index 7c783e99d3..be1709564f 100644 --- a/build/common.props +++ b/build/common.props @@ -15,4 +15,8 @@ + + + + diff --git a/build/dependencies.props b/build/dependencies.props index e704edaec0..c153f0e3f9 100644 --- a/build/dependencies.props +++ b/build/dependencies.props @@ -1,6 +1,10 @@ - 1.6.1 + 1.2.0-* 4.3.0 + 4.7.1 + 1.6.1 + 15.0.0 + 2.2.0 diff --git a/src/Microsoft.AspNetCore.Antiforgery/Microsoft.AspNetCore.Antiforgery.csproj b/src/Microsoft.AspNetCore.Antiforgery/Microsoft.AspNetCore.Antiforgery.csproj index 8f5c0e3ff2..783825919c 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/Microsoft.AspNetCore.Antiforgery.csproj +++ b/src/Microsoft.AspNetCore.Antiforgery/Microsoft.AspNetCore.Antiforgery.csproj @@ -11,15 +11,11 @@ - - - - - - - - - + + + + + diff --git a/test/Microsoft.AspNetCore.Antiforgery.Test/Microsoft.AspNetCore.Antiforgery.Test.csproj b/test/Microsoft.AspNetCore.Antiforgery.Test/Microsoft.AspNetCore.Antiforgery.Test.csproj index c9db70010b..0db4ae9f2d 100644 --- a/test/Microsoft.AspNetCore.Antiforgery.Test/Microsoft.AspNetCore.Antiforgery.Test.csproj +++ b/test/Microsoft.AspNetCore.Antiforgery.Test/Microsoft.AspNetCore.Antiforgery.Test.csproj @@ -9,16 +9,19 @@ - - - - - - - - - - + + + + + + + + + + + + + From 151e792ecbf3418a25ba26d31ca402e84cc499b8 Mon Sep 17 00:00:00 2001 From: Nate McMaster Date: Tue, 21 Mar 2017 11:15:58 -0700 Subject: [PATCH 186/296] Update Travis to macOS Sierra [skip appveyor] --- .travis.yml | 18 ++---------------- 1 file changed, 2 insertions(+), 16 deletions(-) diff --git a/.travis.yml b/.travis.yml index 61dbcbdc56..2a46104677 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,15 +1,6 @@ language: csharp -sudo: required +sudo: false dist: trusty -addons: - apt: - packages: - - gettext - - libcurl4-openssl-dev - - libicu-dev - - libssl-dev - - libunwind8 - - zlib1g env: global: - DOTNET_SKIP_FIRST_TIME_EXPERIENCE: true @@ -18,6 +9,7 @@ mono: none os: - linux - osx +osx_image: xcode8.2 branches: only: - master @@ -28,9 +20,3 @@ before_install: - if test "$TRAVIS_OS_NAME" == "osx"; then brew update; brew install openssl; ln -s /usr/local/opt/openssl/lib/libcrypto.1.0.0.dylib /usr/local/lib/; ln -s /usr/local/opt/openssl/lib/libssl.1.0.0.dylib /usr/local/lib/; fi script: - ./build.sh -notifications: - webhooks: - secure: "dzKsW/YJVie2UeYKMlKFA9dcHv0WpF4IKd7z/yEhV96eB5e2Pls+vtQFUP86Wg/fcqeLHAmb0GazXnomPg2cX13ihz+mF0hCvA58UTczNpwwfTZd7VHQe9Ti93Zoo49HkTFBbIDMns9eUxhcEo4T4lC85dG4ZRz7v8X6/Nlr71PMIGYI29Uyur/1oPrnNI7DBweOY4Z1Xhl5cfaSPd945VM8QPHeM494XGmgldGpIZs+LjZbA8S3xxB0YaxpAwGKO4gWSXL2fP4y1z5rFEY1JZamPaedA3dICVi3BVDjJ4l3sn3fEBxOAv8QwjHvSu0xWK/MAIX/SmY7ScgIND+UMjGFTaeZLYN18hJDm+a4mAx/tPaqsOGAKm9F/aVQAzP0g4z+VAVDz1iqxDWe+x/cK4DPjUbLXpP6Y6jtrVES/TkKNuLNA/NUOp+vDPXieDaQAmeU2l6M2el1PscQPtla6KIS1oDDiuHeWC/b4suCAJVsads25y7KyncmmwYE1Tgh1sUJa+Vk9c/hxiIuDJQUWxmi/4BGjDYO29y60jc2niimzvQ3sV2x+Rh81zJaLWXNYdIgugzQpe4nG8wQDbLuEAlfINBt7cIxw3MK3ov4MV5MVRaDVMEm0A5yIN9Mz83USPkuXxfhGtOo6YU1Ny/D2bjc9LI7lGHbjQtFlJa6U6c=" - on_success: always - on_failure: always - on_start: always From f31c302e5c779b83f9a03100e36855820da1a560 Mon Sep 17 00:00:00 2001 From: Kiran Challa Date: Tue, 21 Mar 2017 16:57:47 -0700 Subject: [PATCH 187/296] Converted test project to run on netcoreapp2.0 --- build/dependencies.props | 1 + .../Internal/DefaultClaimUidExtractorTest.cs | 3 +++ .../Microsoft.AspNetCore.Antiforgery.Test.csproj | 4 ++-- 3 files changed, 6 insertions(+), 2 deletions(-) diff --git a/build/dependencies.props b/build/dependencies.props index c153f0e3f9..35c5cad19a 100644 --- a/build/dependencies.props +++ b/build/dependencies.props @@ -4,6 +4,7 @@ 4.3.0 4.7.1 1.6.1 + 2.0.0-* 15.0.0 2.2.0 diff --git a/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultClaimUidExtractorTest.cs b/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultClaimUidExtractorTest.cs index 81bef79689..625984e97f 100644 --- a/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultClaimUidExtractorTest.cs +++ b/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultClaimUidExtractorTest.cs @@ -63,6 +63,9 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal #if NET452 // CoreCLR doesn't support an 'empty' name identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, string.Empty)); +#elif NETCOREAPP2_0 +#else +#error Target framework needs to be updated #endif // Arrange diff --git a/test/Microsoft.AspNetCore.Antiforgery.Test/Microsoft.AspNetCore.Antiforgery.Test.csproj b/test/Microsoft.AspNetCore.Antiforgery.Test/Microsoft.AspNetCore.Antiforgery.Test.csproj index 0db4ae9f2d..45f2bb8269 100644 --- a/test/Microsoft.AspNetCore.Antiforgery.Test/Microsoft.AspNetCore.Antiforgery.Test.csproj +++ b/test/Microsoft.AspNetCore.Antiforgery.Test/Microsoft.AspNetCore.Antiforgery.Test.csproj @@ -3,8 +3,8 @@ - netcoreapp1.1;net452 - netcoreapp1.1 + netcoreapp2.0;net452 + netcoreapp2.0 From c3d312b0b0620bdc92bbda14be889049d96ef17e Mon Sep 17 00:00:00 2001 From: Pranav K Date: Sun, 12 Mar 2017 08:12:05 -0700 Subject: [PATCH 188/296] Remove net451 as a cross-compile target --- .gitignore | 3 ++- .../Internal/CryptographyAlgorithms.cs | 4 +++- .../Microsoft.AspNetCore.Antiforgery.csproj | 2 +- .../Internal/DefaultClaimUidExtractorTest.cs | 2 +- .../Microsoft.AspNetCore.Antiforgery.Test.csproj | 3 ++- 5 files changed, 9 insertions(+), 5 deletions(-) diff --git a/.gitignore b/.gitignore index 980ee002d9..6da3c6a3e9 100644 --- a/.gitignore +++ b/.gitignore @@ -36,4 +36,5 @@ node_modules **/[Cc]ompiler/[Rr]esources/**/*.js *launchSettings.json .build/ -.testPublish/ \ No newline at end of file +.testPublish/ +global.json diff --git a/src/Microsoft.AspNetCore.Antiforgery/Internal/CryptographyAlgorithms.cs b/src/Microsoft.AspNetCore.Antiforgery/Internal/CryptographyAlgorithms.cs index 95df639b9c..c466512fee 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/Internal/CryptographyAlgorithms.cs +++ b/src/Microsoft.AspNetCore.Antiforgery/Internal/CryptographyAlgorithms.cs @@ -14,7 +14,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal return sha256; } -#else +#elif NET46 public static SHA256 CreateSHA256() { SHA256 sha256; @@ -33,6 +33,8 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal return sha256; } +#else +#error target frameworks need to be updated. #endif } } diff --git a/src/Microsoft.AspNetCore.Antiforgery/Microsoft.AspNetCore.Antiforgery.csproj b/src/Microsoft.AspNetCore.Antiforgery/Microsoft.AspNetCore.Antiforgery.csproj index 783825919c..0a815abdba 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/Microsoft.AspNetCore.Antiforgery.csproj +++ b/src/Microsoft.AspNetCore.Antiforgery/Microsoft.AspNetCore.Antiforgery.csproj @@ -4,7 +4,7 @@ An antiforgery system for ASP.NET Core designed to generate and validate tokens to prevent Cross-Site Request Forgery attacks. - netstandard1.3;net451 + netstandard1.3;net46 $(NoWarn);CS1591 true aspnetcore;antiforgery diff --git a/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultClaimUidExtractorTest.cs b/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultClaimUidExtractorTest.cs index 625984e97f..b03c76e6cc 100644 --- a/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultClaimUidExtractorTest.cs +++ b/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultClaimUidExtractorTest.cs @@ -60,7 +60,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal identity.AddClaim(new Claim(ClaimTypes.Email, "someone@antifrogery.com")); identity.AddClaim(new Claim(ClaimTypes.GivenName, "some")); identity.AddClaim(new Claim(ClaimTypes.Surname, "one")); -#if NET452 +#if NET46 // CoreCLR doesn't support an 'empty' name identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, string.Empty)); #elif NETCOREAPP2_0 diff --git a/test/Microsoft.AspNetCore.Antiforgery.Test/Microsoft.AspNetCore.Antiforgery.Test.csproj b/test/Microsoft.AspNetCore.Antiforgery.Test/Microsoft.AspNetCore.Antiforgery.Test.csproj index 45f2bb8269..f835c84940 100644 --- a/test/Microsoft.AspNetCore.Antiforgery.Test/Microsoft.AspNetCore.Antiforgery.Test.csproj +++ b/test/Microsoft.AspNetCore.Antiforgery.Test/Microsoft.AspNetCore.Antiforgery.Test.csproj @@ -3,7 +3,7 @@ - netcoreapp2.0;net452 + netcoreapp2.0;net46 netcoreapp2.0 @@ -20,6 +20,7 @@ + From af84fadf8cfe0b98a9579776fc008f76e6ed7afa Mon Sep 17 00:00:00 2001 From: Pranav K Date: Wed, 29 Mar 2017 11:30:31 -0700 Subject: [PATCH 189/296] Updating to 2.0.0 Internal.AspNetCore.Sdk --- build/common.props | 2 +- build/dependencies.props | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/build/common.props b/build/common.props index be1709564f..c794f6b5a9 100644 --- a/build/common.props +++ b/build/common.props @@ -13,7 +13,7 @@ - + diff --git a/build/dependencies.props b/build/dependencies.props index 35c5cad19a..cf4424fae5 100644 --- a/build/dependencies.props +++ b/build/dependencies.props @@ -2,10 +2,11 @@ 1.2.0-* 4.3.0 + 2.0.0-* 4.7.1 1.6.1 2.0.0-* 15.0.0 2.2.0 - + \ No newline at end of file From 03869c6e50cd75217176436bc832d8706ce6ee26 Mon Sep 17 00:00:00 2001 From: Pranav K Date: Mon, 3 Apr 2017 21:41:08 -0700 Subject: [PATCH 190/296] Updating versions to 2.0.0-preview1 --- build/dependencies.props | 2 +- version.props | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/build/dependencies.props b/build/dependencies.props index cf4424fae5..afc72a267b 100644 --- a/build/dependencies.props +++ b/build/dependencies.props @@ -1,6 +1,6 @@ - 1.2.0-* + 2.0.0-* 4.3.0 2.0.0-* 4.7.1 diff --git a/version.props b/version.props index 38c93687ab..10a1c898f3 100644 --- a/version.props +++ b/version.props @@ -1,7 +1,7 @@ - 1.2.0 + 2.0.0 preview1 \ No newline at end of file From bb916af873c8222b79bd2daf164284c4fa71a13f Mon Sep 17 00:00:00 2001 From: Smit Patel Date: Mon, 24 Apr 2017 17:13:11 -0700 Subject: [PATCH 191/296] Update API Check related files React to aspnet/BuildTools#238 --- .../{baseline.net45.json => baseline.netframework.json} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename src/Microsoft.AspNetCore.Antiforgery/{baseline.net45.json => baseline.netframework.json} (100%) diff --git a/src/Microsoft.AspNetCore.Antiforgery/baseline.net45.json b/src/Microsoft.AspNetCore.Antiforgery/baseline.netframework.json similarity index 100% rename from src/Microsoft.AspNetCore.Antiforgery/baseline.net45.json rename to src/Microsoft.AspNetCore.Antiforgery/baseline.netframework.json From c68e8035d9f902923fc8684ed11dfbf80359530a Mon Sep 17 00:00:00 2001 From: Pranav K Date: Tue, 25 Apr 2017 11:04:07 -0700 Subject: [PATCH 192/296] Use Bundled NETStandard.Library \ NETCoreApp versions instead of explicitly specifying one --- build/common.props | 2 +- build/dependencies.props | 4 +--- 2 files changed, 2 insertions(+), 4 deletions(-) diff --git a/build/common.props b/build/common.props index c794f6b5a9..1f1fbe023d 100644 --- a/build/common.props +++ b/build/common.props @@ -17,6 +17,6 @@ - + diff --git a/build/dependencies.props b/build/dependencies.props index afc72a267b..8587abb455 100644 --- a/build/dependencies.props +++ b/build/dependencies.props @@ -4,9 +4,7 @@ 4.3.0 2.0.0-* 4.7.1 - 1.6.1 - 2.0.0-* 15.0.0 2.2.0 - \ No newline at end of file + From 20a3e283adfb23f40199adc17810c68a0f9fbff2 Mon Sep 17 00:00:00 2001 From: Pranav K Date: Tue, 25 Apr 2017 22:00:29 -0700 Subject: [PATCH 193/296] Branching for 2.0.0-preview1 --- NuGet.config | 2 +- build.ps1 | 2 +- build.sh | 2 +- build/dependencies.props | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/NuGet.config b/NuGet.config index 8e65695611..fa4304af9c 100644 --- a/NuGet.config +++ b/NuGet.config @@ -1,7 +1,7 @@ - + diff --git a/build.ps1 b/build.ps1 index 5bf0e2c113..225b1fe450 100644 --- a/build.ps1 +++ b/build.ps1 @@ -33,7 +33,7 @@ cd $PSScriptRoot $repoFolder = $PSScriptRoot $env:REPO_FOLDER = $repoFolder -$koreBuildZip="https://github.com/aspnet/KoreBuild/archive/dev.zip" +$koreBuildZip="https://github.com/aspnet/KoreBuild/archive/rel/2.0.0-preview1.zip" if ($env:KOREBUILD_ZIP) { $koreBuildZip=$env:KOREBUILD_ZIP diff --git a/build.sh b/build.sh index b0bcadb579..702b25c636 100755 --- a/build.sh +++ b/build.sh @@ -2,7 +2,7 @@ repoFolder="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" cd $repoFolder -koreBuildZip="https://github.com/aspnet/KoreBuild/archive/dev.zip" +koreBuildZip="https://github.com/aspnet/KoreBuild/archive/rel/2.0.0-preview1.zip" if [ ! -z $KOREBUILD_ZIP ]; then koreBuildZip=$KOREBUILD_ZIP fi diff --git a/build/dependencies.props b/build/dependencies.props index 8587abb455..61dccd8321 100644 --- a/build/dependencies.props +++ b/build/dependencies.props @@ -1,6 +1,6 @@ - 2.0.0-* + 2.0.0-preview1-* 4.3.0 2.0.0-* 4.7.1 From ef21413f9c8a588d9f51d867051a76ffe2980c93 Mon Sep 17 00:00:00 2001 From: Pranav K Date: Wed, 26 Apr 2017 07:12:30 -0700 Subject: [PATCH 194/296] Updating package version to preview2 --- version.props | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/version.props b/version.props index 10a1c898f3..019fba2829 100644 --- a/version.props +++ b/version.props @@ -2,6 +2,6 @@ 2.0.0 - preview1 + preview2 \ No newline at end of file From d9a9f248b4f3961124a063f63883ddef2db0894e Mon Sep 17 00:00:00 2001 From: Pranav K Date: Mon, 1 May 2017 12:38:50 -0700 Subject: [PATCH 195/296] Use the bundled NETStandard.Library package in netstandard targeting libraries --- build/dependencies.props | 1 + 1 file changed, 1 insertion(+) diff --git a/build/dependencies.props b/build/dependencies.props index 61dccd8321..50283ae2ae 100644 --- a/build/dependencies.props +++ b/build/dependencies.props @@ -4,6 +4,7 @@ 4.3.0 2.0.0-* 4.7.1 + $(BundledNETStandardPackageVersion) 15.0.0 2.2.0 From 525ca80d4f1f56ba73ee37755c0eb02d45b45aac Mon Sep 17 00:00:00 2001 From: Pavel Krymets Date: Fri, 5 May 2017 10:05:38 -0700 Subject: [PATCH 196/296] Update InternalAspNetCoreSdkVersion --- build/dependencies.props | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/build/dependencies.props b/build/dependencies.props index 50283ae2ae..a353b25211 100644 --- a/build/dependencies.props +++ b/build/dependencies.props @@ -2,7 +2,7 @@ 2.0.0-preview1-* 4.3.0 - 2.0.0-* + 2.1.0-* 4.7.1 $(BundledNETStandardPackageVersion) 15.0.0 From 6986ab3a0fe08e11ab05791410b8923d3928cca9 Mon Sep 17 00:00:00 2001 From: Pranav K Date: Thu, 4 May 2017 15:13:46 -0700 Subject: [PATCH 197/296] Change TFM to netcoreapp2.0 --- .../Internal/AntiforgeryOptionsSetup.cs | 2 +- .../AntiforgerySerializationContext.cs | 2 +- .../Internal/CryptographyAlgorithms.cs | 40 ------------------- .../Microsoft.AspNetCore.Antiforgery.csproj | 2 +- .../Internal/DefaultClaimUidExtractorTest.cs | 6 --- ...crosoft.AspNetCore.Antiforgery.Test.csproj | 3 +- 6 files changed, 4 insertions(+), 51 deletions(-) delete mode 100644 src/Microsoft.AspNetCore.Antiforgery/Internal/CryptographyAlgorithms.cs diff --git a/src/Microsoft.AspNetCore.Antiforgery/Internal/AntiforgeryOptionsSetup.cs b/src/Microsoft.AspNetCore.Antiforgery/Internal/AntiforgeryOptionsSetup.cs index 29c3780786..1c5a3fa4b8 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/Internal/AntiforgeryOptionsSetup.cs +++ b/src/Microsoft.AspNetCore.Antiforgery/Internal/AntiforgeryOptionsSetup.cs @@ -28,7 +28,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal private static string ComputeCookieName(string applicationId) { - using (var sha256 = CryptographyAlgorithms.CreateSHA256()) + using (var sha256 = SHA256.Create()) { var hash = sha256.ComputeHash(Encoding.UTF8.GetBytes(applicationId)); var subHash = hash.Take(8).ToArray(); diff --git a/src/Microsoft.AspNetCore.Antiforgery/Internal/AntiforgerySerializationContext.cs b/src/Microsoft.AspNetCore.Antiforgery/Internal/AntiforgerySerializationContext.cs index 6d697fa0da..5347f6651a 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/Internal/AntiforgerySerializationContext.cs +++ b/src/Microsoft.AspNetCore.Antiforgery/Internal/AntiforgerySerializationContext.cs @@ -88,7 +88,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal { if (_sha256 == null) { - _sha256 = CryptographyAlgorithms.CreateSHA256(); + _sha256 = SHA256.Create(); } return _sha256; diff --git a/src/Microsoft.AspNetCore.Antiforgery/Internal/CryptographyAlgorithms.cs b/src/Microsoft.AspNetCore.Antiforgery/Internal/CryptographyAlgorithms.cs deleted file mode 100644 index c466512fee..0000000000 --- a/src/Microsoft.AspNetCore.Antiforgery/Internal/CryptographyAlgorithms.cs +++ /dev/null @@ -1,40 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System.Security.Cryptography; - -namespace Microsoft.AspNetCore.Antiforgery.Internal -{ - public static class CryptographyAlgorithms - { -#if NETSTANDARD1_3 - public static SHA256 CreateSHA256() - { - var sha256 = SHA256.Create(); - - return sha256; - } -#elif NET46 - public static SHA256 CreateSHA256() - { - SHA256 sha256; - - try - { - sha256 = SHA256.Create(); - } - // SHA256.Create is documented to throw this exception on FIPS compliant machines. - // See: https://msdn.microsoft.com/en-us/library/z08hz7ad%28v=vs.110%29.aspx?f=255&MSPPError=-2147217396 - catch (System.Reflection.TargetInvocationException) - { - // Fallback to a FIPS compliant SHA256 algorithm. - sha256 = new SHA256CryptoServiceProvider(); - } - - return sha256; - } -#else -#error target frameworks need to be updated. -#endif - } -} diff --git a/src/Microsoft.AspNetCore.Antiforgery/Microsoft.AspNetCore.Antiforgery.csproj b/src/Microsoft.AspNetCore.Antiforgery/Microsoft.AspNetCore.Antiforgery.csproj index 0a815abdba..12b72a69c3 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/Microsoft.AspNetCore.Antiforgery.csproj +++ b/src/Microsoft.AspNetCore.Antiforgery/Microsoft.AspNetCore.Antiforgery.csproj @@ -4,7 +4,7 @@ An antiforgery system for ASP.NET Core designed to generate and validate tokens to prevent Cross-Site Request Forgery attacks. - netstandard1.3;net46 + netcoreapp2.0 $(NoWarn);CS1591 true aspnetcore;antiforgery diff --git a/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultClaimUidExtractorTest.cs b/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultClaimUidExtractorTest.cs index b03c76e6cc..aa5234c690 100644 --- a/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultClaimUidExtractorTest.cs +++ b/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultClaimUidExtractorTest.cs @@ -60,13 +60,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal identity.AddClaim(new Claim(ClaimTypes.Email, "someone@antifrogery.com")); identity.AddClaim(new Claim(ClaimTypes.GivenName, "some")); identity.AddClaim(new Claim(ClaimTypes.Surname, "one")); -#if NET46 - // CoreCLR doesn't support an 'empty' name identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, string.Empty)); -#elif NETCOREAPP2_0 -#else -#error Target framework needs to be updated -#endif // Arrange var claimsIdentity = (ClaimsIdentity)identity; diff --git a/test/Microsoft.AspNetCore.Antiforgery.Test/Microsoft.AspNetCore.Antiforgery.Test.csproj b/test/Microsoft.AspNetCore.Antiforgery.Test/Microsoft.AspNetCore.Antiforgery.Test.csproj index f835c84940..52581604da 100644 --- a/test/Microsoft.AspNetCore.Antiforgery.Test/Microsoft.AspNetCore.Antiforgery.Test.csproj +++ b/test/Microsoft.AspNetCore.Antiforgery.Test/Microsoft.AspNetCore.Antiforgery.Test.csproj @@ -3,8 +3,7 @@ - netcoreapp2.0;net46 - netcoreapp2.0 + netcoreapp2.0 From d1df39b5e578f1e822311f4a44e7ccdefb5ac2fb Mon Sep 17 00:00:00 2001 From: Pavel Krymets Date: Wed, 10 May 2017 08:46:23 -0700 Subject: [PATCH 198/296] Remove unused dependencies (#139) --- build/dependencies.props | 1 - .../Microsoft.AspNetCore.Antiforgery.Test.csproj | 3 +-- 2 files changed, 1 insertion(+), 3 deletions(-) diff --git a/build/dependencies.props b/build/dependencies.props index 8738a88691..0a6c8d6eb5 100644 --- a/build/dependencies.props +++ b/build/dependencies.props @@ -1,7 +1,6 @@ 2.0.0-* - 4.3.0 2.1.0-* 4.7.1 $(BundledNETStandardPackageVersion) diff --git a/test/Microsoft.AspNetCore.Antiforgery.Test/Microsoft.AspNetCore.Antiforgery.Test.csproj b/test/Microsoft.AspNetCore.Antiforgery.Test/Microsoft.AspNetCore.Antiforgery.Test.csproj index 52581604da..f88af18dda 100644 --- a/test/Microsoft.AspNetCore.Antiforgery.Test/Microsoft.AspNetCore.Antiforgery.Test.csproj +++ b/test/Microsoft.AspNetCore.Antiforgery.Test/Microsoft.AspNetCore.Antiforgery.Test.csproj @@ -1,4 +1,4 @@ - + @@ -19,7 +19,6 @@ - From 75c73a31e1fd15dc2fb166df76f5b8661ffe9df2 Mon Sep 17 00:00:00 2001 From: Nate McMaster Date: Fri, 12 May 2017 16:36:33 -0700 Subject: [PATCH 199/296] Upgrade test framework versions --- build/dependencies.props | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/build/dependencies.props b/build/dependencies.props index 0a6c8d6eb5..226b77c333 100644 --- a/build/dependencies.props +++ b/build/dependencies.props @@ -4,7 +4,7 @@ 2.1.0-* 4.7.1 $(BundledNETStandardPackageVersion) - 15.0.0 - 2.2.0 + 15.3.0-* + 2.3.0-beta2-* From 74239f08c0e565156afca1662ce2fd2e1371c2f4 Mon Sep 17 00:00:00 2001 From: Nate McMaster Date: Thu, 18 May 2017 16:09:19 -0700 Subject: [PATCH 200/296] Update TFM to netstandard2.0 --- build/common.props | 4 +- build/dependencies.props | 2 +- .../Microsoft.AspNetCore.Antiforgery.csproj | 2 +- .../baseline.netframework.json | 1875 ----------------- ...crosoft.AspNetCore.Antiforgery.Test.csproj | 3 +- 5 files changed, 6 insertions(+), 1880 deletions(-) delete mode 100644 src/Microsoft.AspNetCore.Antiforgery/baseline.netframework.json diff --git a/build/common.props b/build/common.props index 1f1fbe023d..dc3d395f64 100644 --- a/build/common.props +++ b/build/common.props @@ -16,7 +16,7 @@ - - + + diff --git a/build/dependencies.props b/build/dependencies.props index 226b77c333..1a75c90b26 100644 --- a/build/dependencies.props +++ b/build/dependencies.props @@ -3,7 +3,7 @@ 2.0.0-* 2.1.0-* 4.7.1 - $(BundledNETStandardPackageVersion) + 2.0.0-* 15.3.0-* 2.3.0-beta2-* diff --git a/src/Microsoft.AspNetCore.Antiforgery/Microsoft.AspNetCore.Antiforgery.csproj b/src/Microsoft.AspNetCore.Antiforgery/Microsoft.AspNetCore.Antiforgery.csproj index 12b72a69c3..2e8ce21e1a 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/Microsoft.AspNetCore.Antiforgery.csproj +++ b/src/Microsoft.AspNetCore.Antiforgery/Microsoft.AspNetCore.Antiforgery.csproj @@ -4,7 +4,7 @@ An antiforgery system for ASP.NET Core designed to generate and validate tokens to prevent Cross-Site Request Forgery attacks. - netcoreapp2.0 + netstandard2.0 $(NoWarn);CS1591 true aspnetcore;antiforgery diff --git a/src/Microsoft.AspNetCore.Antiforgery/baseline.netframework.json b/src/Microsoft.AspNetCore.Antiforgery/baseline.netframework.json deleted file mode 100644 index 9117fb75fd..0000000000 --- a/src/Microsoft.AspNetCore.Antiforgery/baseline.netframework.json +++ /dev/null @@ -1,1875 +0,0 @@ -{ - "AssemblyIdentity": "Microsoft.AspNetCore.Antiforgery, Version=1.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60", - "Types": [ - { - "Name": "Microsoft.Extensions.DependencyInjection.AntiforgeryServiceCollectionExtensions", - "Visibility": "Public", - "Kind": "Class", - "Abstract": true, - "Static": true, - "Sealed": true, - "ImplementedInterfaces": [], - "Members": [ - { - "Kind": "Method", - "Name": "AddAntiforgery", - "Parameters": [ - { - "Name": "services", - "Type": "Microsoft.Extensions.DependencyInjection.IServiceCollection" - } - ], - "ReturnType": "Microsoft.Extensions.DependencyInjection.IServiceCollection", - "Static": true, - "Extension": true, - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "AddAntiforgery", - "Parameters": [ - { - "Name": "services", - "Type": "Microsoft.Extensions.DependencyInjection.IServiceCollection" - }, - { - "Name": "setupAction", - "Type": "System.Action" - } - ], - "ReturnType": "Microsoft.Extensions.DependencyInjection.IServiceCollection", - "Static": true, - "Extension": true, - "Visibility": "Public", - "GenericParameter": [] - } - ], - "GenericParameters": [] - }, - { - "Name": "Microsoft.AspNetCore.Antiforgery.AntiforgeryOptions", - "Visibility": "Public", - "Kind": "Class", - "ImplementedInterfaces": [], - "Members": [ - { - "Kind": "Method", - "Name": "get_CookieName", - "Parameters": [], - "ReturnType": "System.String", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "set_CookieName", - "Parameters": [ - { - "Name": "value", - "Type": "System.String" - } - ], - "ReturnType": "System.Void", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "get_FormFieldName", - "Parameters": [], - "ReturnType": "System.String", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "set_FormFieldName", - "Parameters": [ - { - "Name": "value", - "Type": "System.String" - } - ], - "ReturnType": "System.Void", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "get_HeaderName", - "Parameters": [], - "ReturnType": "System.String", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "set_HeaderName", - "Parameters": [ - { - "Name": "value", - "Type": "System.String" - } - ], - "ReturnType": "System.Void", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "get_RequireSsl", - "Parameters": [], - "ReturnType": "System.Boolean", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "set_RequireSsl", - "Parameters": [ - { - "Name": "value", - "Type": "System.Boolean" - } - ], - "ReturnType": "System.Void", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "get_SuppressXFrameOptionsHeader", - "Parameters": [], - "ReturnType": "System.Boolean", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "set_SuppressXFrameOptionsHeader", - "Parameters": [ - { - "Name": "value", - "Type": "System.Boolean" - } - ], - "ReturnType": "System.Void", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Constructor", - "Name": ".ctor", - "Parameters": [], - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Field", - "Name": "DefaultCookiePrefix", - "Parameters": [], - "ReturnType": "System.String", - "Static": true, - "ReadOnly": true, - "Visibility": "Public", - "GenericParameter": [] - } - ], - "GenericParameters": [] - }, - { - "Name": "Microsoft.AspNetCore.Antiforgery.AntiforgeryTokenSet", - "Visibility": "Public", - "Kind": "Class", - "ImplementedInterfaces": [], - "Members": [ - { - "Kind": "Method", - "Name": "get_RequestToken", - "Parameters": [], - "ReturnType": "System.String", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "get_FormFieldName", - "Parameters": [], - "ReturnType": "System.String", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "get_HeaderName", - "Parameters": [], - "ReturnType": "System.String", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "get_CookieToken", - "Parameters": [], - "ReturnType": "System.String", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Constructor", - "Name": ".ctor", - "Parameters": [ - { - "Name": "requestToken", - "Type": "System.String" - }, - { - "Name": "cookieToken", - "Type": "System.String" - }, - { - "Name": "formFieldName", - "Type": "System.String" - }, - { - "Name": "headerName", - "Type": "System.String" - } - ], - "Visibility": "Public", - "GenericParameter": [] - } - ], - "GenericParameters": [] - }, - { - "Name": "Microsoft.AspNetCore.Antiforgery.AntiforgeryValidationException", - "Visibility": "Public", - "Kind": "Class", - "BaseType": "System.Exception", - "ImplementedInterfaces": [], - "Members": [ - { - "Kind": "Constructor", - "Name": ".ctor", - "Parameters": [ - { - "Name": "message", - "Type": "System.String" - } - ], - "Visibility": "Public", - "GenericParameter": [] - } - ], - "GenericParameters": [] - }, - { - "Name": "Microsoft.AspNetCore.Antiforgery.IAntiforgery", - "Visibility": "Public", - "Kind": "Interface", - "Abstract": true, - "ImplementedInterfaces": [], - "Members": [ - { - "Kind": "Method", - "Name": "GetAndStoreTokens", - "Parameters": [ - { - "Name": "httpContext", - "Type": "Microsoft.AspNetCore.Http.HttpContext" - } - ], - "ReturnType": "Microsoft.AspNetCore.Antiforgery.AntiforgeryTokenSet", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "GetTokens", - "Parameters": [ - { - "Name": "httpContext", - "Type": "Microsoft.AspNetCore.Http.HttpContext" - } - ], - "ReturnType": "Microsoft.AspNetCore.Antiforgery.AntiforgeryTokenSet", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "IsRequestValidAsync", - "Parameters": [ - { - "Name": "httpContext", - "Type": "Microsoft.AspNetCore.Http.HttpContext" - } - ], - "ReturnType": "System.Threading.Tasks.Task", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "ValidateRequestAsync", - "Parameters": [ - { - "Name": "httpContext", - "Type": "Microsoft.AspNetCore.Http.HttpContext" - } - ], - "ReturnType": "System.Threading.Tasks.Task", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "SetCookieTokenAndHeader", - "Parameters": [ - { - "Name": "httpContext", - "Type": "Microsoft.AspNetCore.Http.HttpContext" - } - ], - "ReturnType": "System.Void", - "GenericParameter": [] - } - ], - "GenericParameters": [] - }, - { - "Name": "Microsoft.AspNetCore.Antiforgery.IAntiforgeryAdditionalDataProvider", - "Visibility": "Public", - "Kind": "Interface", - "Abstract": true, - "ImplementedInterfaces": [], - "Members": [ - { - "Kind": "Method", - "Name": "GetAdditionalData", - "Parameters": [ - { - "Name": "context", - "Type": "Microsoft.AspNetCore.Http.HttpContext" - } - ], - "ReturnType": "System.String", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "ValidateAdditionalData", - "Parameters": [ - { - "Name": "context", - "Type": "Microsoft.AspNetCore.Http.HttpContext" - }, - { - "Name": "additionalData", - "Type": "System.String" - } - ], - "ReturnType": "System.Boolean", - "GenericParameter": [] - } - ], - "GenericParameters": [] - }, - { - "Name": "Microsoft.AspNetCore.Antiforgery.Internal.AntiforgeryFeature", - "Visibility": "Public", - "Kind": "Class", - "ImplementedInterfaces": [ - "Microsoft.AspNetCore.Antiforgery.Internal.IAntiforgeryFeature" - ], - "Members": [ - { - "Kind": "Method", - "Name": "get_HaveDeserializedCookieToken", - "Parameters": [], - "ReturnType": "System.Boolean", - "Sealed": true, - "Virtual": true, - "ImplementedInterface": "Microsoft.AspNetCore.Antiforgery.Internal.IAntiforgeryFeature", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "set_HaveDeserializedCookieToken", - "Parameters": [ - { - "Name": "value", - "Type": "System.Boolean" - } - ], - "ReturnType": "System.Void", - "Sealed": true, - "Virtual": true, - "ImplementedInterface": "Microsoft.AspNetCore.Antiforgery.Internal.IAntiforgeryFeature", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "get_CookieToken", - "Parameters": [], - "ReturnType": "Microsoft.AspNetCore.Antiforgery.Internal.AntiforgeryToken", - "Sealed": true, - "Virtual": true, - "ImplementedInterface": "Microsoft.AspNetCore.Antiforgery.Internal.IAntiforgeryFeature", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "set_CookieToken", - "Parameters": [ - { - "Name": "value", - "Type": "Microsoft.AspNetCore.Antiforgery.Internal.AntiforgeryToken" - } - ], - "ReturnType": "System.Void", - "Sealed": true, - "Virtual": true, - "ImplementedInterface": "Microsoft.AspNetCore.Antiforgery.Internal.IAntiforgeryFeature", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "get_HaveDeserializedRequestToken", - "Parameters": [], - "ReturnType": "System.Boolean", - "Sealed": true, - "Virtual": true, - "ImplementedInterface": "Microsoft.AspNetCore.Antiforgery.Internal.IAntiforgeryFeature", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "set_HaveDeserializedRequestToken", - "Parameters": [ - { - "Name": "value", - "Type": "System.Boolean" - } - ], - "ReturnType": "System.Void", - "Sealed": true, - "Virtual": true, - "ImplementedInterface": "Microsoft.AspNetCore.Antiforgery.Internal.IAntiforgeryFeature", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "get_RequestToken", - "Parameters": [], - "ReturnType": "Microsoft.AspNetCore.Antiforgery.Internal.AntiforgeryToken", - "Sealed": true, - "Virtual": true, - "ImplementedInterface": "Microsoft.AspNetCore.Antiforgery.Internal.IAntiforgeryFeature", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "set_RequestToken", - "Parameters": [ - { - "Name": "value", - "Type": "Microsoft.AspNetCore.Antiforgery.Internal.AntiforgeryToken" - } - ], - "ReturnType": "System.Void", - "Sealed": true, - "Virtual": true, - "ImplementedInterface": "Microsoft.AspNetCore.Antiforgery.Internal.IAntiforgeryFeature", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "get_HaveGeneratedNewCookieToken", - "Parameters": [], - "ReturnType": "System.Boolean", - "Sealed": true, - "Virtual": true, - "ImplementedInterface": "Microsoft.AspNetCore.Antiforgery.Internal.IAntiforgeryFeature", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "set_HaveGeneratedNewCookieToken", - "Parameters": [ - { - "Name": "value", - "Type": "System.Boolean" - } - ], - "ReturnType": "System.Void", - "Sealed": true, - "Virtual": true, - "ImplementedInterface": "Microsoft.AspNetCore.Antiforgery.Internal.IAntiforgeryFeature", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "get_NewCookieToken", - "Parameters": [], - "ReturnType": "Microsoft.AspNetCore.Antiforgery.Internal.AntiforgeryToken", - "Sealed": true, - "Virtual": true, - "ImplementedInterface": "Microsoft.AspNetCore.Antiforgery.Internal.IAntiforgeryFeature", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "set_NewCookieToken", - "Parameters": [ - { - "Name": "value", - "Type": "Microsoft.AspNetCore.Antiforgery.Internal.AntiforgeryToken" - } - ], - "ReturnType": "System.Void", - "Sealed": true, - "Virtual": true, - "ImplementedInterface": "Microsoft.AspNetCore.Antiforgery.Internal.IAntiforgeryFeature", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "get_NewCookieTokenString", - "Parameters": [], - "ReturnType": "System.String", - "Sealed": true, - "Virtual": true, - "ImplementedInterface": "Microsoft.AspNetCore.Antiforgery.Internal.IAntiforgeryFeature", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "set_NewCookieTokenString", - "Parameters": [ - { - "Name": "value", - "Type": "System.String" - } - ], - "ReturnType": "System.Void", - "Sealed": true, - "Virtual": true, - "ImplementedInterface": "Microsoft.AspNetCore.Antiforgery.Internal.IAntiforgeryFeature", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "get_NewRequestToken", - "Parameters": [], - "ReturnType": "Microsoft.AspNetCore.Antiforgery.Internal.AntiforgeryToken", - "Sealed": true, - "Virtual": true, - "ImplementedInterface": "Microsoft.AspNetCore.Antiforgery.Internal.IAntiforgeryFeature", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "set_NewRequestToken", - "Parameters": [ - { - "Name": "value", - "Type": "Microsoft.AspNetCore.Antiforgery.Internal.AntiforgeryToken" - } - ], - "ReturnType": "System.Void", - "Sealed": true, - "Virtual": true, - "ImplementedInterface": "Microsoft.AspNetCore.Antiforgery.Internal.IAntiforgeryFeature", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "get_NewRequestTokenString", - "Parameters": [], - "ReturnType": "System.String", - "Sealed": true, - "Virtual": true, - "ImplementedInterface": "Microsoft.AspNetCore.Antiforgery.Internal.IAntiforgeryFeature", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "set_NewRequestTokenString", - "Parameters": [ - { - "Name": "value", - "Type": "System.String" - } - ], - "ReturnType": "System.Void", - "Sealed": true, - "Virtual": true, - "ImplementedInterface": "Microsoft.AspNetCore.Antiforgery.Internal.IAntiforgeryFeature", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "get_HaveStoredNewCookieToken", - "Parameters": [], - "ReturnType": "System.Boolean", - "Sealed": true, - "Virtual": true, - "ImplementedInterface": "Microsoft.AspNetCore.Antiforgery.Internal.IAntiforgeryFeature", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "set_HaveStoredNewCookieToken", - "Parameters": [ - { - "Name": "value", - "Type": "System.Boolean" - } - ], - "ReturnType": "System.Void", - "Sealed": true, - "Virtual": true, - "ImplementedInterface": "Microsoft.AspNetCore.Antiforgery.Internal.IAntiforgeryFeature", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Constructor", - "Name": ".ctor", - "Parameters": [], - "Visibility": "Public", - "GenericParameter": [] - } - ], - "GenericParameters": [] - }, - { - "Name": "Microsoft.AspNetCore.Antiforgery.Internal.AntiforgeryOptionsSetup", - "Visibility": "Public", - "Kind": "Class", - "BaseType": "Microsoft.Extensions.Options.ConfigureOptions", - "ImplementedInterfaces": [], - "Members": [ - { - "Kind": "Method", - "Name": "ConfigureOptions", - "Parameters": [ - { - "Name": "options", - "Type": "Microsoft.AspNetCore.Antiforgery.AntiforgeryOptions" - }, - { - "Name": "dataProtectionOptions", - "Type": "Microsoft.AspNetCore.DataProtection.DataProtectionOptions" - } - ], - "ReturnType": "System.Void", - "Static": true, - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Constructor", - "Name": ".ctor", - "Parameters": [ - { - "Name": "dataProtectionOptionsAccessor", - "Type": "Microsoft.Extensions.Options.IOptions" - } - ], - "Visibility": "Public", - "GenericParameter": [] - } - ], - "GenericParameters": [] - }, - { - "Name": "Microsoft.AspNetCore.Antiforgery.Internal.AntiforgerySerializationContext", - "Visibility": "Public", - "Kind": "Class", - "ImplementedInterfaces": [], - "Members": [ - { - "Kind": "Method", - "Name": "get_Stream", - "Parameters": [], - "ReturnType": "System.IO.MemoryStream", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "get_Reader", - "Parameters": [], - "ReturnType": "System.IO.BinaryReader", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "get_Writer", - "Parameters": [], - "ReturnType": "System.IO.BinaryWriter", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "get_Sha256", - "Parameters": [], - "ReturnType": "System.Security.Cryptography.SHA256", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "GetChars", - "Parameters": [ - { - "Name": "count", - "Type": "System.Int32" - } - ], - "ReturnType": "System.Char[]", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "Reset", - "Parameters": [], - "ReturnType": "System.Void", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Constructor", - "Name": ".ctor", - "Parameters": [], - "Visibility": "Public", - "GenericParameter": [] - } - ], - "GenericParameters": [] - }, - { - "Name": "Microsoft.AspNetCore.Antiforgery.Internal.AntiforgerySerializationContextPooledObjectPolicy", - "Visibility": "Public", - "Kind": "Class", - "ImplementedInterfaces": [ - "Microsoft.Extensions.ObjectPool.IPooledObjectPolicy" - ], - "Members": [ - { - "Kind": "Method", - "Name": "Create", - "Parameters": [], - "ReturnType": "Microsoft.AspNetCore.Antiforgery.Internal.AntiforgerySerializationContext", - "Sealed": true, - "Virtual": true, - "ImplementedInterface": "Microsoft.Extensions.ObjectPool.IPooledObjectPolicy", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "Return", - "Parameters": [ - { - "Name": "obj", - "Type": "Microsoft.AspNetCore.Antiforgery.Internal.AntiforgerySerializationContext" - } - ], - "ReturnType": "System.Boolean", - "Sealed": true, - "Virtual": true, - "ImplementedInterface": "Microsoft.Extensions.ObjectPool.IPooledObjectPolicy", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Constructor", - "Name": ".ctor", - "Parameters": [], - "Visibility": "Public", - "GenericParameter": [] - } - ], - "GenericParameters": [] - }, - { - "Name": "Microsoft.AspNetCore.Antiforgery.Internal.AntiforgeryToken", - "Visibility": "Public", - "Kind": "Class", - "Sealed": true, - "ImplementedInterfaces": [], - "Members": [ - { - "Kind": "Method", - "Name": "get_AdditionalData", - "Parameters": [], - "ReturnType": "System.String", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "set_AdditionalData", - "Parameters": [ - { - "Name": "value", - "Type": "System.String" - } - ], - "ReturnType": "System.Void", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "get_ClaimUid", - "Parameters": [], - "ReturnType": "Microsoft.AspNetCore.Antiforgery.Internal.BinaryBlob", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "set_ClaimUid", - "Parameters": [ - { - "Name": "value", - "Type": "Microsoft.AspNetCore.Antiforgery.Internal.BinaryBlob" - } - ], - "ReturnType": "System.Void", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "get_IsCookieToken", - "Parameters": [], - "ReturnType": "System.Boolean", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "set_IsCookieToken", - "Parameters": [ - { - "Name": "value", - "Type": "System.Boolean" - } - ], - "ReturnType": "System.Void", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "get_SecurityToken", - "Parameters": [], - "ReturnType": "Microsoft.AspNetCore.Antiforgery.Internal.BinaryBlob", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "set_SecurityToken", - "Parameters": [ - { - "Name": "value", - "Type": "Microsoft.AspNetCore.Antiforgery.Internal.BinaryBlob" - } - ], - "ReturnType": "System.Void", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "get_Username", - "Parameters": [], - "ReturnType": "System.String", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "set_Username", - "Parameters": [ - { - "Name": "value", - "Type": "System.String" - } - ], - "ReturnType": "System.Void", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Constructor", - "Name": ".ctor", - "Parameters": [], - "Visibility": "Public", - "GenericParameter": [] - } - ], - "GenericParameters": [] - }, - { - "Name": "Microsoft.AspNetCore.Antiforgery.Internal.BinaryBlob", - "Visibility": "Public", - "Kind": "Class", - "Sealed": true, - "ImplementedInterfaces": [ - "System.IEquatable" - ], - "Members": [ - { - "Kind": "Method", - "Name": "get_BitLength", - "Parameters": [], - "ReturnType": "System.Int32", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "Equals", - "Parameters": [ - { - "Name": "obj", - "Type": "System.Object" - } - ], - "ReturnType": "System.Boolean", - "Virtual": true, - "Override": true, - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "Equals", - "Parameters": [ - { - "Name": "other", - "Type": "Microsoft.AspNetCore.Antiforgery.Internal.BinaryBlob" - } - ], - "ReturnType": "System.Boolean", - "Sealed": true, - "Virtual": true, - "ImplementedInterface": "System.IEquatable", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "GetData", - "Parameters": [], - "ReturnType": "System.Byte[]", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "GetHashCode", - "Parameters": [], - "ReturnType": "System.Int32", - "Virtual": true, - "Override": true, - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Constructor", - "Name": ".ctor", - "Parameters": [ - { - "Name": "bitLength", - "Type": "System.Int32" - } - ], - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Constructor", - "Name": ".ctor", - "Parameters": [ - { - "Name": "bitLength", - "Type": "System.Int32" - }, - { - "Name": "data", - "Type": "System.Byte[]" - } - ], - "Visibility": "Public", - "GenericParameter": [] - } - ], - "GenericParameters": [] - }, - { - "Name": "Microsoft.AspNetCore.Antiforgery.Internal.DefaultAntiforgery", - "Visibility": "Public", - "Kind": "Class", - "ImplementedInterfaces": [ - "Microsoft.AspNetCore.Antiforgery.IAntiforgery" - ], - "Members": [ - { - "Kind": "Method", - "Name": "GetAndStoreTokens", - "Parameters": [ - { - "Name": "httpContext", - "Type": "Microsoft.AspNetCore.Http.HttpContext" - } - ], - "ReturnType": "Microsoft.AspNetCore.Antiforgery.AntiforgeryTokenSet", - "Sealed": true, - "Virtual": true, - "ImplementedInterface": "Microsoft.AspNetCore.Antiforgery.IAntiforgery", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "GetTokens", - "Parameters": [ - { - "Name": "httpContext", - "Type": "Microsoft.AspNetCore.Http.HttpContext" - } - ], - "ReturnType": "Microsoft.AspNetCore.Antiforgery.AntiforgeryTokenSet", - "Sealed": true, - "Virtual": true, - "ImplementedInterface": "Microsoft.AspNetCore.Antiforgery.IAntiforgery", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "IsRequestValidAsync", - "Parameters": [ - { - "Name": "httpContext", - "Type": "Microsoft.AspNetCore.Http.HttpContext" - } - ], - "ReturnType": "System.Threading.Tasks.Task", - "Sealed": true, - "Virtual": true, - "ImplementedInterface": "Microsoft.AspNetCore.Antiforgery.IAntiforgery", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "ValidateRequestAsync", - "Parameters": [ - { - "Name": "httpContext", - "Type": "Microsoft.AspNetCore.Http.HttpContext" - } - ], - "ReturnType": "System.Threading.Tasks.Task", - "Sealed": true, - "Virtual": true, - "ImplementedInterface": "Microsoft.AspNetCore.Antiforgery.IAntiforgery", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "SetCookieTokenAndHeader", - "Parameters": [ - { - "Name": "httpContext", - "Type": "Microsoft.AspNetCore.Http.HttpContext" - } - ], - "ReturnType": "System.Void", - "Sealed": true, - "Virtual": true, - "ImplementedInterface": "Microsoft.AspNetCore.Antiforgery.IAntiforgery", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Constructor", - "Name": ".ctor", - "Parameters": [ - { - "Name": "antiforgeryOptionsAccessor", - "Type": "Microsoft.Extensions.Options.IOptions" - }, - { - "Name": "tokenGenerator", - "Type": "Microsoft.AspNetCore.Antiforgery.Internal.IAntiforgeryTokenGenerator" - }, - { - "Name": "tokenSerializer", - "Type": "Microsoft.AspNetCore.Antiforgery.Internal.IAntiforgeryTokenSerializer" - }, - { - "Name": "tokenStore", - "Type": "Microsoft.AspNetCore.Antiforgery.Internal.IAntiforgeryTokenStore" - }, - { - "Name": "loggerFactory", - "Type": "Microsoft.Extensions.Logging.ILoggerFactory" - } - ], - "Visibility": "Public", - "GenericParameter": [] - } - ], - "GenericParameters": [] - }, - { - "Name": "Microsoft.AspNetCore.Antiforgery.Internal.DefaultAntiforgeryAdditionalDataProvider", - "Visibility": "Public", - "Kind": "Class", - "ImplementedInterfaces": [ - "Microsoft.AspNetCore.Antiforgery.IAntiforgeryAdditionalDataProvider" - ], - "Members": [ - { - "Kind": "Method", - "Name": "GetAdditionalData", - "Parameters": [ - { - "Name": "context", - "Type": "Microsoft.AspNetCore.Http.HttpContext" - } - ], - "ReturnType": "System.String", - "Virtual": true, - "ImplementedInterface": "Microsoft.AspNetCore.Antiforgery.IAntiforgeryAdditionalDataProvider", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "ValidateAdditionalData", - "Parameters": [ - { - "Name": "context", - "Type": "Microsoft.AspNetCore.Http.HttpContext" - }, - { - "Name": "additionalData", - "Type": "System.String" - } - ], - "ReturnType": "System.Boolean", - "Virtual": true, - "ImplementedInterface": "Microsoft.AspNetCore.Antiforgery.IAntiforgeryAdditionalDataProvider", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Constructor", - "Name": ".ctor", - "Parameters": [], - "Visibility": "Public", - "GenericParameter": [] - } - ], - "GenericParameters": [] - }, - { - "Name": "Microsoft.AspNetCore.Antiforgery.Internal.DefaultAntiforgeryTokenGenerator", - "Visibility": "Public", - "Kind": "Class", - "ImplementedInterfaces": [ - "Microsoft.AspNetCore.Antiforgery.Internal.IAntiforgeryTokenGenerator" - ], - "Members": [ - { - "Kind": "Method", - "Name": "GenerateCookieToken", - "Parameters": [], - "ReturnType": "Microsoft.AspNetCore.Antiforgery.Internal.AntiforgeryToken", - "Sealed": true, - "Virtual": true, - "ImplementedInterface": "Microsoft.AspNetCore.Antiforgery.Internal.IAntiforgeryTokenGenerator", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "GenerateRequestToken", - "Parameters": [ - { - "Name": "httpContext", - "Type": "Microsoft.AspNetCore.Http.HttpContext" - }, - { - "Name": "cookieToken", - "Type": "Microsoft.AspNetCore.Antiforgery.Internal.AntiforgeryToken" - } - ], - "ReturnType": "Microsoft.AspNetCore.Antiforgery.Internal.AntiforgeryToken", - "Sealed": true, - "Virtual": true, - "ImplementedInterface": "Microsoft.AspNetCore.Antiforgery.Internal.IAntiforgeryTokenGenerator", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "IsCookieTokenValid", - "Parameters": [ - { - "Name": "cookieToken", - "Type": "Microsoft.AspNetCore.Antiforgery.Internal.AntiforgeryToken" - } - ], - "ReturnType": "System.Boolean", - "Sealed": true, - "Virtual": true, - "ImplementedInterface": "Microsoft.AspNetCore.Antiforgery.Internal.IAntiforgeryTokenGenerator", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "TryValidateTokenSet", - "Parameters": [ - { - "Name": "httpContext", - "Type": "Microsoft.AspNetCore.Http.HttpContext" - }, - { - "Name": "cookieToken", - "Type": "Microsoft.AspNetCore.Antiforgery.Internal.AntiforgeryToken" - }, - { - "Name": "requestToken", - "Type": "Microsoft.AspNetCore.Antiforgery.Internal.AntiforgeryToken" - }, - { - "Name": "message", - "Type": "System.String", - "Direction": "Out" - } - ], - "ReturnType": "System.Boolean", - "Sealed": true, - "Virtual": true, - "ImplementedInterface": "Microsoft.AspNetCore.Antiforgery.Internal.IAntiforgeryTokenGenerator", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Constructor", - "Name": ".ctor", - "Parameters": [ - { - "Name": "claimUidExtractor", - "Type": "Microsoft.AspNetCore.Antiforgery.Internal.IClaimUidExtractor" - }, - { - "Name": "additionalDataProvider", - "Type": "Microsoft.AspNetCore.Antiforgery.IAntiforgeryAdditionalDataProvider" - } - ], - "Visibility": "Public", - "GenericParameter": [] - } - ], - "GenericParameters": [] - }, - { - "Name": "Microsoft.AspNetCore.Antiforgery.Internal.DefaultAntiforgeryTokenSerializer", - "Visibility": "Public", - "Kind": "Class", - "ImplementedInterfaces": [ - "Microsoft.AspNetCore.Antiforgery.Internal.IAntiforgeryTokenSerializer" - ], - "Members": [ - { - "Kind": "Method", - "Name": "Deserialize", - "Parameters": [ - { - "Name": "serializedToken", - "Type": "System.String" - } - ], - "ReturnType": "Microsoft.AspNetCore.Antiforgery.Internal.AntiforgeryToken", - "Sealed": true, - "Virtual": true, - "ImplementedInterface": "Microsoft.AspNetCore.Antiforgery.Internal.IAntiforgeryTokenSerializer", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "Serialize", - "Parameters": [ - { - "Name": "token", - "Type": "Microsoft.AspNetCore.Antiforgery.Internal.AntiforgeryToken" - } - ], - "ReturnType": "System.String", - "Sealed": true, - "Virtual": true, - "ImplementedInterface": "Microsoft.AspNetCore.Antiforgery.Internal.IAntiforgeryTokenSerializer", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Constructor", - "Name": ".ctor", - "Parameters": [ - { - "Name": "provider", - "Type": "Microsoft.AspNetCore.DataProtection.IDataProtectionProvider" - }, - { - "Name": "pool", - "Type": "Microsoft.Extensions.ObjectPool.ObjectPool" - } - ], - "Visibility": "Public", - "GenericParameter": [] - } - ], - "GenericParameters": [] - }, - { - "Name": "Microsoft.AspNetCore.Antiforgery.Internal.DefaultAntiforgeryTokenStore", - "Visibility": "Public", - "Kind": "Class", - "ImplementedInterfaces": [ - "Microsoft.AspNetCore.Antiforgery.Internal.IAntiforgeryTokenStore" - ], - "Members": [ - { - "Kind": "Method", - "Name": "GetCookieToken", - "Parameters": [ - { - "Name": "httpContext", - "Type": "Microsoft.AspNetCore.Http.HttpContext" - } - ], - "ReturnType": "System.String", - "Sealed": true, - "Virtual": true, - "ImplementedInterface": "Microsoft.AspNetCore.Antiforgery.Internal.IAntiforgeryTokenStore", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "GetRequestTokensAsync", - "Parameters": [ - { - "Name": "httpContext", - "Type": "Microsoft.AspNetCore.Http.HttpContext" - } - ], - "ReturnType": "System.Threading.Tasks.Task", - "Sealed": true, - "Virtual": true, - "ImplementedInterface": "Microsoft.AspNetCore.Antiforgery.Internal.IAntiforgeryTokenStore", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "SaveCookieToken", - "Parameters": [ - { - "Name": "httpContext", - "Type": "Microsoft.AspNetCore.Http.HttpContext" - }, - { - "Name": "token", - "Type": "System.String" - } - ], - "ReturnType": "System.Void", - "Sealed": true, - "Virtual": true, - "ImplementedInterface": "Microsoft.AspNetCore.Antiforgery.Internal.IAntiforgeryTokenStore", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Constructor", - "Name": ".ctor", - "Parameters": [ - { - "Name": "optionsAccessor", - "Type": "Microsoft.Extensions.Options.IOptions" - } - ], - "Visibility": "Public", - "GenericParameter": [] - } - ], - "GenericParameters": [] - }, - { - "Name": "Microsoft.AspNetCore.Antiforgery.Internal.DefaultClaimUidExtractor", - "Visibility": "Public", - "Kind": "Class", - "ImplementedInterfaces": [ - "Microsoft.AspNetCore.Antiforgery.Internal.IClaimUidExtractor" - ], - "Members": [ - { - "Kind": "Method", - "Name": "ExtractClaimUid", - "Parameters": [ - { - "Name": "claimsPrincipal", - "Type": "System.Security.Claims.ClaimsPrincipal" - } - ], - "ReturnType": "System.String", - "Sealed": true, - "Virtual": true, - "ImplementedInterface": "Microsoft.AspNetCore.Antiforgery.Internal.IClaimUidExtractor", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "GetUniqueIdentifierParameters", - "Parameters": [ - { - "Name": "claimsIdentities", - "Type": "System.Collections.Generic.IEnumerable" - } - ], - "ReturnType": "System.Collections.Generic.IList", - "Static": true, - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Constructor", - "Name": ".ctor", - "Parameters": [ - { - "Name": "pool", - "Type": "Microsoft.Extensions.ObjectPool.ObjectPool" - } - ], - "Visibility": "Public", - "GenericParameter": [] - } - ], - "GenericParameters": [] - }, - { - "Name": "Microsoft.AspNetCore.Antiforgery.Internal.IAntiforgeryFeature", - "Visibility": "Public", - "Kind": "Interface", - "Abstract": true, - "ImplementedInterfaces": [], - "Members": [ - { - "Kind": "Method", - "Name": "get_CookieToken", - "Parameters": [], - "ReturnType": "Microsoft.AspNetCore.Antiforgery.Internal.AntiforgeryToken", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "set_CookieToken", - "Parameters": [ - { - "Name": "value", - "Type": "Microsoft.AspNetCore.Antiforgery.Internal.AntiforgeryToken" - } - ], - "ReturnType": "System.Void", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "get_HaveDeserializedCookieToken", - "Parameters": [], - "ReturnType": "System.Boolean", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "set_HaveDeserializedCookieToken", - "Parameters": [ - { - "Name": "value", - "Type": "System.Boolean" - } - ], - "ReturnType": "System.Void", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "get_HaveDeserializedRequestToken", - "Parameters": [], - "ReturnType": "System.Boolean", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "set_HaveDeserializedRequestToken", - "Parameters": [ - { - "Name": "value", - "Type": "System.Boolean" - } - ], - "ReturnType": "System.Void", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "get_HaveGeneratedNewCookieToken", - "Parameters": [], - "ReturnType": "System.Boolean", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "set_HaveGeneratedNewCookieToken", - "Parameters": [ - { - "Name": "value", - "Type": "System.Boolean" - } - ], - "ReturnType": "System.Void", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "get_HaveStoredNewCookieToken", - "Parameters": [], - "ReturnType": "System.Boolean", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "set_HaveStoredNewCookieToken", - "Parameters": [ - { - "Name": "value", - "Type": "System.Boolean" - } - ], - "ReturnType": "System.Void", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "get_NewCookieToken", - "Parameters": [], - "ReturnType": "Microsoft.AspNetCore.Antiforgery.Internal.AntiforgeryToken", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "set_NewCookieToken", - "Parameters": [ - { - "Name": "value", - "Type": "Microsoft.AspNetCore.Antiforgery.Internal.AntiforgeryToken" - } - ], - "ReturnType": "System.Void", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "get_NewCookieTokenString", - "Parameters": [], - "ReturnType": "System.String", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "set_NewCookieTokenString", - "Parameters": [ - { - "Name": "value", - "Type": "System.String" - } - ], - "ReturnType": "System.Void", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "get_NewRequestToken", - "Parameters": [], - "ReturnType": "Microsoft.AspNetCore.Antiforgery.Internal.AntiforgeryToken", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "set_NewRequestToken", - "Parameters": [ - { - "Name": "value", - "Type": "Microsoft.AspNetCore.Antiforgery.Internal.AntiforgeryToken" - } - ], - "ReturnType": "System.Void", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "get_NewRequestTokenString", - "Parameters": [], - "ReturnType": "System.String", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "set_NewRequestTokenString", - "Parameters": [ - { - "Name": "value", - "Type": "System.String" - } - ], - "ReturnType": "System.Void", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "get_RequestToken", - "Parameters": [], - "ReturnType": "Microsoft.AspNetCore.Antiforgery.Internal.AntiforgeryToken", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "set_RequestToken", - "Parameters": [ - { - "Name": "value", - "Type": "Microsoft.AspNetCore.Antiforgery.Internal.AntiforgeryToken" - } - ], - "ReturnType": "System.Void", - "GenericParameter": [] - } - ], - "GenericParameters": [] - }, - { - "Name": "Microsoft.AspNetCore.Antiforgery.Internal.IAntiforgeryTokenGenerator", - "Visibility": "Public", - "Kind": "Interface", - "Abstract": true, - "ImplementedInterfaces": [], - "Members": [ - { - "Kind": "Method", - "Name": "GenerateCookieToken", - "Parameters": [], - "ReturnType": "Microsoft.AspNetCore.Antiforgery.Internal.AntiforgeryToken", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "GenerateRequestToken", - "Parameters": [ - { - "Name": "httpContext", - "Type": "Microsoft.AspNetCore.Http.HttpContext" - }, - { - "Name": "cookieToken", - "Type": "Microsoft.AspNetCore.Antiforgery.Internal.AntiforgeryToken" - } - ], - "ReturnType": "Microsoft.AspNetCore.Antiforgery.Internal.AntiforgeryToken", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "IsCookieTokenValid", - "Parameters": [ - { - "Name": "cookieToken", - "Type": "Microsoft.AspNetCore.Antiforgery.Internal.AntiforgeryToken" - } - ], - "ReturnType": "System.Boolean", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "TryValidateTokenSet", - "Parameters": [ - { - "Name": "httpContext", - "Type": "Microsoft.AspNetCore.Http.HttpContext" - }, - { - "Name": "cookieToken", - "Type": "Microsoft.AspNetCore.Antiforgery.Internal.AntiforgeryToken" - }, - { - "Name": "requestToken", - "Type": "Microsoft.AspNetCore.Antiforgery.Internal.AntiforgeryToken" - }, - { - "Name": "message", - "Type": "System.String", - "Direction": "Out" - } - ], - "ReturnType": "System.Boolean", - "GenericParameter": [] - } - ], - "GenericParameters": [] - }, - { - "Name": "Microsoft.AspNetCore.Antiforgery.Internal.IAntiforgeryTokenSerializer", - "Visibility": "Public", - "Kind": "Interface", - "Abstract": true, - "ImplementedInterfaces": [], - "Members": [ - { - "Kind": "Method", - "Name": "Deserialize", - "Parameters": [ - { - "Name": "serializedToken", - "Type": "System.String" - } - ], - "ReturnType": "Microsoft.AspNetCore.Antiforgery.Internal.AntiforgeryToken", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "Serialize", - "Parameters": [ - { - "Name": "token", - "Type": "Microsoft.AspNetCore.Antiforgery.Internal.AntiforgeryToken" - } - ], - "ReturnType": "System.String", - "GenericParameter": [] - } - ], - "GenericParameters": [] - }, - { - "Name": "Microsoft.AspNetCore.Antiforgery.Internal.IAntiforgeryTokenStore", - "Visibility": "Public", - "Kind": "Interface", - "Abstract": true, - "ImplementedInterfaces": [], - "Members": [ - { - "Kind": "Method", - "Name": "GetCookieToken", - "Parameters": [ - { - "Name": "httpContext", - "Type": "Microsoft.AspNetCore.Http.HttpContext" - } - ], - "ReturnType": "System.String", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "GetRequestTokensAsync", - "Parameters": [ - { - "Name": "httpContext", - "Type": "Microsoft.AspNetCore.Http.HttpContext" - } - ], - "ReturnType": "System.Threading.Tasks.Task", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "SaveCookieToken", - "Parameters": [ - { - "Name": "httpContext", - "Type": "Microsoft.AspNetCore.Http.HttpContext" - }, - { - "Name": "token", - "Type": "System.String" - } - ], - "ReturnType": "System.Void", - "GenericParameter": [] - } - ], - "GenericParameters": [] - }, - { - "Name": "Microsoft.AspNetCore.Antiforgery.Internal.IClaimUidExtractor", - "Visibility": "Public", - "Kind": "Interface", - "Abstract": true, - "ImplementedInterfaces": [], - "Members": [ - { - "Kind": "Method", - "Name": "ExtractClaimUid", - "Parameters": [ - { - "Name": "claimsPrincipal", - "Type": "System.Security.Claims.ClaimsPrincipal" - } - ], - "ReturnType": "System.String", - "GenericParameter": [] - } - ], - "GenericParameters": [] - } - ] -} \ No newline at end of file diff --git a/test/Microsoft.AspNetCore.Antiforgery.Test/Microsoft.AspNetCore.Antiforgery.Test.csproj b/test/Microsoft.AspNetCore.Antiforgery.Test/Microsoft.AspNetCore.Antiforgery.Test.csproj index f88af18dda..021d56162a 100644 --- a/test/Microsoft.AspNetCore.Antiforgery.Test/Microsoft.AspNetCore.Antiforgery.Test.csproj +++ b/test/Microsoft.AspNetCore.Antiforgery.Test/Microsoft.AspNetCore.Antiforgery.Test.csproj @@ -3,7 +3,8 @@ - netcoreapp2.0 + netcoreapp2.0;net461 + netcoreapp2.0 From f258be61fd05ff23d286661c58409b1eba004440 Mon Sep 17 00:00:00 2001 From: Chris R Date: Thu, 18 May 2017 21:57:13 -0700 Subject: [PATCH 201/296] React to parser StringSegment changes --- .../Internal/DefaultAntiforgery.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgery.cs b/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgery.cs index 9677f7a793..5f849335ef 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgery.cs +++ b/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgery.cs @@ -384,7 +384,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal { var logWarning = false; CacheControlHeaderValue cacheControlHeaderValue; - if (CacheControlHeaderValue.TryParse(response.Headers[HeaderNames.CacheControl], out cacheControlHeaderValue)) + if (CacheControlHeaderValue.TryParse(response.Headers[HeaderNames.CacheControl].ToString(), out cacheControlHeaderValue)) { if (!cacheControlHeaderValue.NoCache) { From 0ab3f1e94f8df362a9a6683437701db38f830440 Mon Sep 17 00:00:00 2001 From: Kiran Challa Date: Fri, 26 May 2017 12:36:36 -0700 Subject: [PATCH 202/296] Updated to use the latest shared runtime --- build/dependencies.props | 1 + 1 file changed, 1 insertion(+) diff --git a/build/dependencies.props b/build/dependencies.props index 1a75c90b26..a5d8ef58f7 100644 --- a/build/dependencies.props +++ b/build/dependencies.props @@ -4,6 +4,7 @@ 2.1.0-* 4.7.1 2.0.0-* + 2.0.0-* 15.3.0-* 2.3.0-beta2-* From c59304a63233b6677c22c956b680774018e37a4e Mon Sep 17 00:00:00 2001 From: Pranav K Date: Wed, 31 May 2017 19:36:00 -0700 Subject: [PATCH 203/296] Branching for rel/2.0.0-preview2 --- NuGet.config | 7 ++++--- build/dependencies.props | 2 +- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/NuGet.config b/NuGet.config index 8e65695611..c4bc056c4d 100644 --- a/NuGet.config +++ b/NuGet.config @@ -1,8 +1,9 @@ - + - + + - + \ No newline at end of file diff --git a/build/dependencies.props b/build/dependencies.props index a5d8ef58f7..eb851f4ef6 100644 --- a/build/dependencies.props +++ b/build/dependencies.props @@ -1,6 +1,6 @@ - 2.0.0-* + 2.0.0-preview2-* 2.1.0-* 4.7.1 2.0.0-* From 8f8f3bce6394e7627cada6837f3ad1ff7b8e53b3 Mon Sep 17 00:00:00 2001 From: Pranav K Date: Wed, 31 May 2017 19:53:08 -0700 Subject: [PATCH 204/296] Updating build scripts to point to 2.0.0-preview2 KoreBuild --- build.ps1 | 2 +- build.sh | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/build.ps1 b/build.ps1 index 5bf0e2c113..3a2476b2b4 100644 --- a/build.ps1 +++ b/build.ps1 @@ -33,7 +33,7 @@ cd $PSScriptRoot $repoFolder = $PSScriptRoot $env:REPO_FOLDER = $repoFolder -$koreBuildZip="https://github.com/aspnet/KoreBuild/archive/dev.zip" +$koreBuildZip="https://github.com/aspnet/KoreBuild/archive/rel/2.0.0-preview2.zip" if ($env:KOREBUILD_ZIP) { $koreBuildZip=$env:KOREBUILD_ZIP diff --git a/build.sh b/build.sh index b0bcadb579..a40bdb87b1 100755 --- a/build.sh +++ b/build.sh @@ -2,7 +2,7 @@ repoFolder="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" cd $repoFolder -koreBuildZip="https://github.com/aspnet/KoreBuild/archive/dev.zip" +koreBuildZip="https://github.com/aspnet/KoreBuild/archive/rel/2.0.0-preview2.zip" if [ ! -z $KOREBUILD_ZIP ]; then koreBuildZip=$KOREBUILD_ZIP fi From b25b664bf8dd0dfb00ddf37b43759a99f338f428 Mon Sep 17 00:00:00 2001 From: Pranav K Date: Thu, 1 Jun 2017 10:46:25 -0700 Subject: [PATCH 205/296] Updating versions to preview3 --- NuGet.config | 3 ++- version.props | 2 +- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/NuGet.config b/NuGet.config index 8e65695611..4e8a1f6de1 100644 --- a/NuGet.config +++ b/NuGet.config @@ -1,6 +1,7 @@ - + + diff --git a/version.props b/version.props index 019fba2829..a327eefab8 100644 --- a/version.props +++ b/version.props @@ -2,6 +2,6 @@ 2.0.0 - preview2 + preview3 \ No newline at end of file From 5870fce03593c1c216983668359d040fb9cc02e7 Mon Sep 17 00:00:00 2001 From: John Luo Date: Mon, 22 May 2017 01:19:34 -0700 Subject: [PATCH 206/296] Add configure delegate for CookieOptions - allows configuration of CookieOptions such as SameSite without explicit duplication of the option on AntiforgeryOptions --- .../AntiforgeryOptions.cs | 16 ++++++++-- .../Internal/DefaultAntiforgeryTokenStore.cs | 32 +++++++++---------- .../DefaultAntiforgeryTokenStoreTest.cs | 8 ++--- 3 files changed, 34 insertions(+), 22 deletions(-) diff --git a/src/Microsoft.AspNetCore.Antiforgery/AntiforgeryOptions.cs b/src/Microsoft.AspNetCore.Antiforgery/AntiforgeryOptions.cs index b8c6e4b816..241edb814e 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/AntiforgeryOptions.cs +++ b/src/Microsoft.AspNetCore.Antiforgery/AntiforgeryOptions.cs @@ -47,18 +47,30 @@ namespace Microsoft.AspNetCore.Antiforgery } /// + /// This is obsolete and will be removed in a future version. + /// The recommended alternative is to use ConfigureCookieOptions. /// The path set on the cookie. If set to null, the "path" attribute on the cookie is set to the current /// request's value. If the value of is /// null or empty, then the "path" attribute is set to the value of . /// + [Obsolete("This is obsolete and will be removed in a future version. The recommended alternative is to use ConfigureCookieOptions.")] public PathString? CookiePath { get; set; } /// - /// The domain set on the cookie. By default its null which results in the "domain" attribute not being - /// set. + /// This is obsolete and will be removed in a future version. + /// The recommended alternative is to use ConfigureCookieOptions. + /// The domain set on the cookie. By default its null which results in the "domain" attribute not being set. /// + [Obsolete("This is obsolete and will be removed in a future version. The recommended alternative is to use ConfigureCookieOptions.")] public string CookieDomain { get; set; } + /// + /// Configures the of the antiforgery cookies. Without additional configuration, the + /// default values antiforgery cookie options are true for , null for + /// and for . + /// + public Action ConfigureCookieOptions { get; set; } + /// /// Specifies the name of the antiforgery token field that is used by the antiforgery system. /// diff --git a/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgeryTokenStore.cs b/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgeryTokenStore.cs index 0a78eddb41..2fd0d9507e 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgeryTokenStore.cs +++ b/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgeryTokenStore.cs @@ -69,34 +69,34 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal Debug.Assert(httpContext != null); Debug.Assert(token != null); - var options = new CookieOptions(); - options.HttpOnly = true; - options.Domain = _options.CookieDomain; - // Note: don't use "newCookie.Secure = _options.RequireSSL;" since the default - // value of newCookie.Secure is populated out of band. - if (_options.RequireSsl) + var options = new CookieOptions { - options.Secure = true; - } - SetCookiePath(httpContext, options); + HttpOnly = true, +#pragma warning disable 618 + Domain = _options.CookieDomain, +#pragma warning restore 618 + SameSite = SameSiteMode.Strict, + Secure = _options.RequireSsl + }; - httpContext.Response.Cookies.Append(_options.CookieName, token, options); - } - - private void SetCookiePath(HttpContext httpContext, CookieOptions cookieOptions) - { +#pragma warning disable 618 if (_options.CookiePath != null) { - cookieOptions.Path = _options.CookiePath.ToString(); + options.Path = _options.CookiePath.ToString(); } +#pragma warning restore 618 else { var pathBase = httpContext.Request.PathBase.ToString(); if (!string.IsNullOrEmpty(pathBase)) { - cookieOptions.Path = pathBase; + options.Path = pathBase; } } + + _options.ConfigureCookieOptions?.Invoke(httpContext, options); + + httpContext.Response.Cookies.Append(_options.CookieName, token, options); } } } diff --git a/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTokenStoreTest.cs b/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTokenStoreTest.cs index f328ff908b..96fd2703fd 100644 --- a/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTokenStoreTest.cs +++ b/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTokenStoreTest.cs @@ -311,7 +311,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal } [Fact] - public void SaveCookieToken_NonNullAntiforgeryOptionsCookiePath_UsesOptionsCookiePath() + public void SaveCookieToken_NonNullAntiforgeryOptionsConfigureCookieOptionsPath_UsesCookieOptionsPath() { // Arrange var expectedCookiePath = "/"; @@ -330,7 +330,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal .Returns("/index.html"); var options = new AntiforgeryOptions(); options.CookieName = _cookieName; - options.CookiePath = expectedCookiePath; + options.ConfigureCookieOptions = (context, cookieOptions) => cookieOptions.Path = expectedCookiePath; var tokenStore = new DefaultAntiforgeryTokenStore(new TestOptionsManager(options)); // Act @@ -346,7 +346,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal } [Fact] - public void SaveCookieToken_NonNullAntiforgeryOptionsCookieDomain_UsesOptionsCookieDomain() + public void SaveCookieToken_NonNullAntiforgeryOptionsConfigureCookieOptionsDomain_UsesCookieOptionsDomain() { // Arrange var expectedCookieDomain = "microsoft.com"; @@ -364,7 +364,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal .Returns("/index.html"); var options = new AntiforgeryOptions(); options.CookieName = _cookieName; - options.CookieDomain = expectedCookieDomain; + options.ConfigureCookieOptions = (context, cookieOptions) => cookieOptions.Domain = expectedCookieDomain; var tokenStore = new DefaultAntiforgeryTokenStore(new TestOptionsManager(options)); // Act From bdf115a5ff20b0987b69982405045afdf84d12ff Mon Sep 17 00:00:00 2001 From: "N. Taylor Mullen" Date: Tue, 6 Jun 2017 17:01:50 -0700 Subject: [PATCH 207/296] Make SHA256 algorithm creation FIPS compliant. #144 --- .../Internal/AntiforgeryOptionsSetup.cs | 3 +-- .../AntiforgerySerializationContext.cs | 2 +- .../Internal/CryptographyAlgorithms.cs | 25 +++++++++++++++++++ 3 files changed, 27 insertions(+), 3 deletions(-) create mode 100644 src/Microsoft.AspNetCore.Antiforgery/Internal/CryptographyAlgorithms.cs diff --git a/src/Microsoft.AspNetCore.Antiforgery/Internal/AntiforgeryOptionsSetup.cs b/src/Microsoft.AspNetCore.Antiforgery/Internal/AntiforgeryOptionsSetup.cs index 1c5a3fa4b8..f503c47053 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/Internal/AntiforgeryOptionsSetup.cs +++ b/src/Microsoft.AspNetCore.Antiforgery/Internal/AntiforgeryOptionsSetup.cs @@ -2,7 +2,6 @@ // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Linq; -using System.Security.Cryptography; using System.Text; using Microsoft.AspNetCore.DataProtection; using Microsoft.AspNetCore.WebUtilities; @@ -28,7 +27,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal private static string ComputeCookieName(string applicationId) { - using (var sha256 = SHA256.Create()) + using (var sha256 = CryptographyAlgorithms.CreateSHA256()) { var hash = sha256.ComputeHash(Encoding.UTF8.GetBytes(applicationId)); var subHash = hash.Take(8).ToArray(); diff --git a/src/Microsoft.AspNetCore.Antiforgery/Internal/AntiforgerySerializationContext.cs b/src/Microsoft.AspNetCore.Antiforgery/Internal/AntiforgerySerializationContext.cs index 5347f6651a..6d697fa0da 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/Internal/AntiforgerySerializationContext.cs +++ b/src/Microsoft.AspNetCore.Antiforgery/Internal/AntiforgerySerializationContext.cs @@ -88,7 +88,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal { if (_sha256 == null) { - _sha256 = SHA256.Create(); + _sha256 = CryptographyAlgorithms.CreateSHA256(); } return _sha256; diff --git a/src/Microsoft.AspNetCore.Antiforgery/Internal/CryptographyAlgorithms.cs b/src/Microsoft.AspNetCore.Antiforgery/Internal/CryptographyAlgorithms.cs new file mode 100644 index 0000000000..644b4e6234 --- /dev/null +++ b/src/Microsoft.AspNetCore.Antiforgery/Internal/CryptographyAlgorithms.cs @@ -0,0 +1,25 @@ +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System.Security.Cryptography; + +namespace Microsoft.AspNetCore.Antiforgery.Internal +{ + public static class CryptographyAlgorithms + { + public static SHA256 CreateSHA256() + { + try + { + return SHA256.Create(); + } + // SHA256.Create is documented to throw this exception on FIPS compliant machines. + // See: https://msdn.microsoft.com/en-us/library/z08hz7ad%28v=vs.110%29.aspx?f=255&MSPPError=-2147217396 + catch (System.Reflection.TargetInvocationException) + { + // Fallback to a FIPS compliant SHA256 algorithm. + return new SHA256CryptoServiceProvider(); + } + } + } +} From 74ffe816a033740a74c9f7a5bdaf90ff31387ce3 Mon Sep 17 00:00:00 2001 From: Nate McMaster Date: Mon, 26 Jun 2017 09:25:11 -0700 Subject: [PATCH 208/296] Add libunwind to travis.yml [skip appveyor] --- .travis.yml | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/.travis.yml b/.travis.yml index 2a46104677..b10be14215 100644 --- a/.travis.yml +++ b/.travis.yml @@ -10,6 +10,10 @@ os: - linux - osx osx_image: xcode8.2 +addons: + apt: + packages: + - libunwind8 branches: only: - master From 85bf94c29b9c7237cdcbde0fcf69c60d24f728ba Mon Sep 17 00:00:00 2001 From: Pranav K Date: Thu, 29 Jun 2017 07:14:03 -0700 Subject: [PATCH 209/296] Update dependencies.props * Update Moq to 4.7.49. * Add NETStandardImplicitPackageVersion --- build/dependencies.props | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/build/dependencies.props b/build/dependencies.props index a5d8ef58f7..787a051c3a 100644 --- a/build/dependencies.props +++ b/build/dependencies.props @@ -1,8 +1,9 @@ - + 2.0.0-* 2.1.0-* - 4.7.1 + 4.7.49 + 2.0.0-* 2.0.0-* 2.0.0-* 15.3.0-* From cfe0e3012ec1763b4da9cf0ced25dbf369ff89c9 Mon Sep 17 00:00:00 2001 From: Ryan Brandenburg Date: Thu, 29 Jun 2017 10:45:20 -0700 Subject: [PATCH 210/296] Remove NETStandard.Library.NETFramework and update Moq (#147) --- build/common.props | 4 ---- 1 file changed, 4 deletions(-) diff --git a/build/common.props b/build/common.props index dc3d395f64..a66094c2a0 100644 --- a/build/common.props +++ b/build/common.props @@ -15,8 +15,4 @@ - - - - From df41fd8ccc450d3e1e424c7828899853c75ca214 Mon Sep 17 00:00:00 2001 From: Nate McMaster Date: Thu, 29 Jun 2017 15:49:13 -0700 Subject: [PATCH 211/296] Replace the ConfigureCookieOptions action property with the CookieBuilder --- .../AntiforgeryOptions.cs | 147 ++++++++++-------- .../Internal/AntiforgeryOptionsSetup.cs | 4 +- .../Internal/DefaultAntiforgery.cs | 13 +- .../Internal/DefaultAntiforgeryTokenStore.cs | 24 +-- .../Properties/Resources.Designer.cs | 120 ++++++-------- .../Resources.resx | 7 +- .../Internal/AntiforgeryOptionsSetupTest.cs | 8 +- .../Internal/DefaultAntiforgeryTest.cs | 31 ++-- .../DefaultAntiforgeryTokenStoreTest.cs | 85 +++++----- 9 files changed, 220 insertions(+), 219 deletions(-) diff --git a/src/Microsoft.AspNetCore.Antiforgery/AntiforgeryOptions.cs b/src/Microsoft.AspNetCore.Antiforgery/AntiforgeryOptions.cs index 241edb814e..f0de2da040 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/AntiforgeryOptions.cs +++ b/src/Microsoft.AspNetCore.Antiforgery/AntiforgeryOptions.cs @@ -14,81 +14,45 @@ namespace Microsoft.AspNetCore.Antiforgery private const string AntiforgeryTokenFieldName = "__RequestVerificationToken"; private const string AntiforgeryTokenHeaderName = "RequestVerificationToken"; - private string _cookieName; private string _formFieldName = AntiforgeryTokenFieldName; + private CookieBuilder _cookieBuilder = new CookieBuilder + { + SameSite = SameSiteMode.Strict, + HttpOnly = true + }; + /// /// The default cookie prefix, which is ".AspNetCore.Antiforgery.". /// public static readonly string DefaultCookiePrefix = ".AspNetCore.Antiforgery."; /// - /// Specifies the name of the cookie that is used by the antiforgery system. + /// Determines the settings used to create the antiforgery cookies. /// /// - /// If an explicit name is not provided, the system will automatically generate a + /// + /// If an explicit is not provided, the system will automatically generate a /// unique name that begins with . + /// + /// + /// defaults to . + /// defaults to true. + /// /// - public string CookieName + public CookieBuilder Cookie { - get - { - return _cookieName; - } - set - { - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } - - _cookieName = value; - } + get => _cookieBuilder; + set => _cookieBuilder = value ?? throw new ArgumentNullException(nameof(value)); } - /// - /// This is obsolete and will be removed in a future version. - /// The recommended alternative is to use ConfigureCookieOptions. - /// The path set on the cookie. If set to null, the "path" attribute on the cookie is set to the current - /// request's value. If the value of is - /// null or empty, then the "path" attribute is set to the value of . - /// - [Obsolete("This is obsolete and will be removed in a future version. The recommended alternative is to use ConfigureCookieOptions.")] - public PathString? CookiePath { get; set; } - - /// - /// This is obsolete and will be removed in a future version. - /// The recommended alternative is to use ConfigureCookieOptions. - /// The domain set on the cookie. By default its null which results in the "domain" attribute not being set. - /// - [Obsolete("This is obsolete and will be removed in a future version. The recommended alternative is to use ConfigureCookieOptions.")] - public string CookieDomain { get; set; } - - /// - /// Configures the of the antiforgery cookies. Without additional configuration, the - /// default values antiforgery cookie options are true for , null for - /// and for . - /// - public Action ConfigureCookieOptions { get; set; } - /// /// Specifies the name of the antiforgery token field that is used by the antiforgery system. /// public string FormFieldName { - get - { - return _formFieldName; - } - set - { - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } - - _formFieldName = value; - } + get => _formFieldName; + set => _formFieldName = value ?? throw new ArgumentNullException(nameof(value)); } /// @@ -97,13 +61,6 @@ namespace Microsoft.AspNetCore.Antiforgery /// public string HeaderName { get; set; } = AntiforgeryTokenHeaderName; - /// - /// Specifies whether SSL is required for the antiforgery system - /// to operate. If this setting is 'true' and a non-SSL request - /// comes into the system, all antiforgery APIs will fail. - /// - public bool RequireSsl { get; set; } - /// /// Specifies whether to suppress the generation of X-Frame-Options header /// which is used to prevent ClickJacking. By default, the X-Frame-Options @@ -111,5 +68,69 @@ namespace Microsoft.AspNetCore.Antiforgery /// the X-Frame-Options header will not be generated for the response. /// public bool SuppressXFrameOptionsHeader { get; set; } + + #region Obsolete API + /// + /// + /// This property is obsolete and will be removed in a future version. The recommended alternative is on . + /// + /// + /// Specifies the name of the cookie that is used by the antiforgery system. + /// + /// + /// + /// If an explicit name is not provided, the system will automatically generate a + /// unique name that begins with . + /// + [Obsolete("This property is obsolete and will be removed in a future version. The recommended alternative is " + nameof(Cookie) + "." + nameof(CookieBuilder.Name) + ".")] + public string CookieName { get => Cookie.Name; set => Cookie.Name = value; } + + /// + /// + /// This property is obsolete and will be removed in a future version. The recommended alternative is on . + /// + /// + /// The path set on the cookie. If set to null, the "path" attribute on the cookie is set to the current + /// request's value. If the value of is + /// null or empty, then the "path" attribute is set to the value of . + /// + /// + [Obsolete("This property is obsolete and will be removed in a future version. The recommended alternative is " + nameof(Cookie) + "." + nameof(CookieBuilder.Path) + ".")] + public PathString? CookiePath { get => Cookie.Path; set => Cookie.Path = value; } + + /// + /// + /// This property is obsolete and will be removed in a future version. The recommended alternative is on . + /// + /// + /// The domain set on the cookie. By default its null which results in the "domain" attribute not being set. + /// + /// + [Obsolete("This property is obsolete and will be removed in a future version. The recommended alternative is " + nameof(Cookie) + "." + nameof(CookieBuilder.Domain) + ".")] + public string CookieDomain { get => Cookie.Domain; set => Cookie.Domain = value; } + + + /// + /// + /// This property is obsolete and will be removed in a future version. + /// The recommended alternative is to set on . + /// + /// + /// true is equivalent to . + /// false is equivalent to . + /// + /// + /// Specifies whether SSL is required for the antiforgery system + /// to operate. If this setting is 'true' and a non-SSL request + /// comes into the system, all antiforgery APIs will fail. + /// + /// + [Obsolete("This property is obsolete and will be removed in a future version. The recommended alternative is to set " + nameof(Cookie) + "." + nameof(CookieBuilder.SecurePolicy) + ".")] + public bool RequireSsl + { + get => Cookie.SecurePolicy == CookieSecurePolicy.Always; + set => Cookie.SecurePolicy = value ? CookieSecurePolicy.Always : CookieSecurePolicy.None; + } + #endregion } -} \ No newline at end of file +} diff --git a/src/Microsoft.AspNetCore.Antiforgery/Internal/AntiforgeryOptionsSetup.cs b/src/Microsoft.AspNetCore.Antiforgery/Internal/AntiforgeryOptionsSetup.cs index f503c47053..a6bc826351 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/Internal/AntiforgeryOptionsSetup.cs +++ b/src/Microsoft.AspNetCore.Antiforgery/Internal/AntiforgeryOptionsSetup.cs @@ -18,10 +18,10 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal public static void ConfigureOptions(AntiforgeryOptions options, DataProtectionOptions dataProtectionOptions) { - if (options.CookieName == null) + if (options.Cookie.Name == null) { var applicationId = dataProtectionOptions.ApplicationDiscriminator ?? string.Empty; - options.CookieName = AntiforgeryOptions.DefaultCookiePrefix + ComputeCookieName(applicationId); + options.Cookie.Name = AntiforgeryOptions.DefaultCookiePrefix + ComputeCookieName(applicationId); } } diff --git a/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgery.cs b/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgery.cs index 5f849335ef..ae28906069 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgery.cs +++ b/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgery.cs @@ -111,7 +111,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal var tokens = await _tokenStore.GetRequestTokensAsync(httpContext); if (tokens.CookieToken == null) { - _logger.MissingCookieToken(_options.CookieName); + _logger.MissingCookieToken(_options.Cookie.Name); return false; } @@ -160,7 +160,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal if (tokens.CookieToken == null) { throw new AntiforgeryValidationException( - Resources.FormatAntiforgery_CookieToken_MustBeProvided(_options.CookieName)); + Resources.FormatAntiforgery_CookieToken_MustBeProvided(_options.Cookie.Name)); } if (tokens.RequestToken == null) @@ -265,12 +265,11 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal private void CheckSSLConfig(HttpContext context) { - if (_options.RequireSsl && !context.Request.IsHttps) + if (_options.Cookie.SecurePolicy == CookieSecurePolicy.Always && !context.Request.IsHttps) { - throw new InvalidOperationException(Resources.FormatAntiforgeryWorker_RequireSSL( - nameof(AntiforgeryOptions), - nameof(AntiforgeryOptions.RequireSsl), - "true")); + throw new InvalidOperationException(Resources.FormatAntiforgery_RequiresSSL( + string.Join(".", nameof(AntiforgeryOptions), nameof(AntiforgeryOptions.Cookie), nameof(CookieBuilder.SecurePolicy)), + nameof(CookieSecurePolicy.Always))); } } diff --git a/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgeryTokenStore.cs b/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgeryTokenStore.cs index 2fd0d9507e..95e6d6f1bc 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgeryTokenStore.cs +++ b/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgeryTokenStore.cs @@ -28,7 +28,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal { Debug.Assert(httpContext != null); - var requestCookie = httpContext.Request.Cookies[_options.CookieName]; + var requestCookie = httpContext.Request.Cookies[_options.Cookie.Name]; if (string.IsNullOrEmpty(requestCookie)) { // unable to find the cookie. @@ -42,7 +42,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal { Debug.Assert(httpContext != null); - var cookieToken = httpContext.Request.Cookies[_options.CookieName]; + var cookieToken = httpContext.Request.Cookies[_options.Cookie.Name]; // We want to delay reading the form as much as possible, for example in case of large file uploads, // request token could be part of the header. @@ -69,22 +69,12 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal Debug.Assert(httpContext != null); Debug.Assert(token != null); - var options = new CookieOptions - { - HttpOnly = true, -#pragma warning disable 618 - Domain = _options.CookieDomain, -#pragma warning restore 618 - SameSite = SameSiteMode.Strict, - Secure = _options.RequireSsl - }; + var options = _options.Cookie.Build(httpContext); -#pragma warning disable 618 - if (_options.CookiePath != null) + if (_options.Cookie.Path != null) { - options.Path = _options.CookiePath.ToString(); + options.Path = _options.Cookie.Path.ToString(); } -#pragma warning restore 618 else { var pathBase = httpContext.Request.PathBase.ToString(); @@ -94,9 +84,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal } } - _options.ConfigureCookieOptions?.Invoke(httpContext, options); - - httpContext.Response.Cookies.Append(_options.CookieName, token, options); + httpContext.Response.Cookies.Append(_options.Cookie.Name, token, options); } } } diff --git a/src/Microsoft.AspNetCore.Antiforgery/Properties/Resources.Designer.cs b/src/Microsoft.AspNetCore.Antiforgery/Properties/Resources.Designer.cs index 6b12221bd8..83811ea2dc 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/Properties/Resources.Designer.cs +++ b/src/Microsoft.AspNetCore.Antiforgery/Properties/Resources.Designer.cs @@ -15,248 +15,224 @@ namespace Microsoft.AspNetCore.Antiforgery ///
internal static string AntiforgeryTokenValidator_AuthenticatedUserWithoutUsername { - get { return GetString("AntiforgeryTokenValidator_AuthenticatedUserWithoutUsername"); } + get => GetString("AntiforgeryTokenValidator_AuthenticatedUserWithoutUsername"); } /// /// The provided identity of type '{0}' is marked {1} = {2} but does not have a value for {3}. By default, the antiforgery system requires that all authenticated identities have a unique {3}. If it is not possible to provide a unique {3} for this identity, consider extending {4} by overriding the {5} or a custom type that can provide some form of unique identifier for the current user. /// internal static string FormatAntiforgeryTokenValidator_AuthenticatedUserWithoutUsername(object p0, object p1, object p2, object p3, object p4, object p5) - { - return string.Format(CultureInfo.CurrentCulture, GetString("AntiforgeryTokenValidator_AuthenticatedUserWithoutUsername"), p0, p1, p2, p3, p4, p5); - } + => string.Format(CultureInfo.CurrentCulture, GetString("AntiforgeryTokenValidator_AuthenticatedUserWithoutUsername"), p0, p1, p2, p3, p4, p5); /// /// The provided antiforgery token failed a custom data check. /// internal static string AntiforgeryToken_AdditionalDataCheckFailed { - get { return GetString("AntiforgeryToken_AdditionalDataCheckFailed"); } + get => GetString("AntiforgeryToken_AdditionalDataCheckFailed"); } /// /// The provided antiforgery token failed a custom data check. /// internal static string FormatAntiforgeryToken_AdditionalDataCheckFailed() - { - return GetString("AntiforgeryToken_AdditionalDataCheckFailed"); - } + => GetString("AntiforgeryToken_AdditionalDataCheckFailed"); /// /// The provided antiforgery token was meant for a different claims-based user than the current user. /// internal static string AntiforgeryToken_ClaimUidMismatch { - get { return GetString("AntiforgeryToken_ClaimUidMismatch"); } + get => GetString("AntiforgeryToken_ClaimUidMismatch"); } /// /// The provided antiforgery token was meant for a different claims-based user than the current user. /// internal static string FormatAntiforgeryToken_ClaimUidMismatch() - { - return GetString("AntiforgeryToken_ClaimUidMismatch"); - } + => GetString("AntiforgeryToken_ClaimUidMismatch"); /// /// The antiforgery token could not be decrypted. /// internal static string AntiforgeryToken_DeserializationFailed { - get { return GetString("AntiforgeryToken_DeserializationFailed"); } + get => GetString("AntiforgeryToken_DeserializationFailed"); } /// /// The antiforgery token could not be decrypted. /// internal static string FormatAntiforgeryToken_DeserializationFailed() - { - return GetString("AntiforgeryToken_DeserializationFailed"); - } + => GetString("AntiforgeryToken_DeserializationFailed"); /// /// The antiforgery cookie token and request token do not match. /// internal static string AntiforgeryToken_SecurityTokenMismatch { - get { return GetString("AntiforgeryToken_SecurityTokenMismatch"); } + get => GetString("AntiforgeryToken_SecurityTokenMismatch"); } /// /// The antiforgery cookie token and request token do not match. /// internal static string FormatAntiforgeryToken_SecurityTokenMismatch() - { - return GetString("AntiforgeryToken_SecurityTokenMismatch"); - } + => GetString("AntiforgeryToken_SecurityTokenMismatch"); /// /// Validation of the provided antiforgery token failed. The cookie token and the request token were swapped. /// internal static string AntiforgeryToken_TokensSwapped { - get { return GetString("AntiforgeryToken_TokensSwapped"); } + get => GetString("AntiforgeryToken_TokensSwapped"); } /// /// Validation of the provided antiforgery token failed. The cookie token and the request token were swapped. /// internal static string FormatAntiforgeryToken_TokensSwapped() - { - return GetString("AntiforgeryToken_TokensSwapped"); - } + => GetString("AntiforgeryToken_TokensSwapped"); /// /// The provided antiforgery token was meant for user "{0}", but the current user is "{1}". /// internal static string AntiforgeryToken_UsernameMismatch { - get { return GetString("AntiforgeryToken_UsernameMismatch"); } + get => GetString("AntiforgeryToken_UsernameMismatch"); } /// /// The provided antiforgery token was meant for user "{0}", but the current user is "{1}". /// internal static string FormatAntiforgeryToken_UsernameMismatch(object p0, object p1) - { - return string.Format(CultureInfo.CurrentCulture, GetString("AntiforgeryToken_UsernameMismatch"), p0, p1); - } + => string.Format(CultureInfo.CurrentCulture, GetString("AntiforgeryToken_UsernameMismatch"), p0, p1); /// - /// The antiforgery system has the configuration value {0}.{1} = {2}, but the current request is not an SSL request. - /// - internal static string AntiforgeryWorker_RequireSSL - { - get { return GetString("AntiforgeryWorker_RequireSSL"); } - } - - /// - /// The antiforgery system has the configuration value {0}.{1} = {2}, but the current request is not an SSL request. - /// - internal static string FormatAntiforgeryWorker_RequireSSL(object p0, object p1, object p2) - { - return string.Format(CultureInfo.CurrentCulture, GetString("AntiforgeryWorker_RequireSSL"), p0, p1, p2); - } - - /// - /// The required antiforgery cookie "{0}" is not present. + /// The antiforgery cookie token is invalid. /// internal static string Antiforgery_CookieToken_IsInvalid { - get { return GetString("Antiforgery_CookieToken_IsInvalid"); } + get => GetString("Antiforgery_CookieToken_IsInvalid"); } + /// + /// The antiforgery cookie token is invalid. + /// + internal static string FormatAntiforgery_CookieToken_IsInvalid() + => GetString("Antiforgery_CookieToken_IsInvalid"); + /// /// The required antiforgery cookie "{0}" is not present. /// internal static string Antiforgery_CookieToken_MustBeProvided { - get { return GetString("Antiforgery_CookieToken_MustBeProvided"); } + get => GetString("Antiforgery_CookieToken_MustBeProvided"); } /// /// The required antiforgery cookie "{0}" is not present. /// internal static string FormatAntiforgery_CookieToken_MustBeProvided(object p0) - { - return string.Format(CultureInfo.CurrentCulture, GetString("Antiforgery_CookieToken_MustBeProvided"), p0); - } + => string.Format(CultureInfo.CurrentCulture, GetString("Antiforgery_CookieToken_MustBeProvided"), p0); /// /// The required antiforgery cookie token must be provided. /// internal static string Antiforgery_CookieToken_MustBeProvided_Generic { - get { return GetString("Antiforgery_CookieToken_MustBeProvided_Generic"); } + get => GetString("Antiforgery_CookieToken_MustBeProvided_Generic"); } /// /// The required antiforgery cookie token must be provided. /// internal static string FormatAntiforgery_CookieToken_MustBeProvided_Generic() - { - return GetString("Antiforgery_CookieToken_MustBeProvided_Generic"); - } + => GetString("Antiforgery_CookieToken_MustBeProvided_Generic"); /// /// The required antiforgery form field "{0}" is not present. /// internal static string Antiforgery_FormToken_MustBeProvided { - get { return GetString("Antiforgery_FormToken_MustBeProvided"); } + get => GetString("Antiforgery_FormToken_MustBeProvided"); } /// /// The required antiforgery form field "{0}" is not present. /// internal static string FormatAntiforgery_FormToken_MustBeProvided(object p0) - { - return string.Format(CultureInfo.CurrentCulture, GetString("Antiforgery_FormToken_MustBeProvided"), p0); - } + => string.Format(CultureInfo.CurrentCulture, GetString("Antiforgery_FormToken_MustBeProvided"), p0); /// /// The required antiforgery header value "{0}" is not present. /// internal static string Antiforgery_HeaderToken_MustBeProvided { - get { return GetString("Antiforgery_HeaderToken_MustBeProvided"); } + get => GetString("Antiforgery_HeaderToken_MustBeProvided"); } /// /// The required antiforgery header value "{0}" is not present. /// internal static string FormatAntiforgery_HeaderToken_MustBeProvided(object p0) - { - return string.Format(CultureInfo.CurrentCulture, GetString("Antiforgery_HeaderToken_MustBeProvided"), p0); - } + => string.Format(CultureInfo.CurrentCulture, GetString("Antiforgery_HeaderToken_MustBeProvided"), p0); /// /// The required antiforgery request token was not provided in either form field "{0}" or header value "{1}". /// internal static string Antiforgery_RequestToken_MustBeProvided { - get { return GetString("Antiforgery_RequestToken_MustBeProvided"); } + get => GetString("Antiforgery_RequestToken_MustBeProvided"); } /// /// The required antiforgery request token was not provided in either form field "{0}" or header value "{1}". /// internal static string FormatAntiforgery_RequestToken_MustBeProvided(object p0, object p1) - { - return string.Format(CultureInfo.CurrentCulture, GetString("Antiforgery_RequestToken_MustBeProvided"), p0, p1); - } + => string.Format(CultureInfo.CurrentCulture, GetString("Antiforgery_RequestToken_MustBeProvided"), p0, p1); /// /// The required antiforgery request token must be provided. /// internal static string Antiforgery_RequestToken_MustBeProvided_Generic { - get { return GetString("Antiforgery_RequestToken_MustBeProvided_Generic"); } + get => GetString("Antiforgery_RequestToken_MustBeProvided_Generic"); } /// /// The required antiforgery request token must be provided. /// internal static string FormatAntiforgery_RequestToken_MustBeProvided_Generic() + => GetString("Antiforgery_RequestToken_MustBeProvided_Generic"); + + /// + /// The antiforgery system has the configuration value {optionName} = {value}, but the current request is not an SSL request. + /// + internal static string Antiforgery_RequiresSSL { - return GetString("Antiforgery_RequestToken_MustBeProvided_Generic"); + get => GetString("Antiforgery_RequiresSSL"); } + /// + /// The antiforgery system has the configuration value {optionName} = {value}, but the current request is not an SSL request. + /// + internal static string FormatAntiforgery_RequiresSSL(object optionName, object value) + => string.Format(CultureInfo.CurrentCulture, GetString("Antiforgery_RequiresSSL", "optionName", "value"), optionName, value); + /// /// Value cannot be null or empty. /// internal static string ArgumentCannotBeNullOrEmpty { - get { return GetString("ArgumentCannotBeNullOrEmpty"); } + get => GetString("ArgumentCannotBeNullOrEmpty"); } /// /// Value cannot be null or empty. /// internal static string FormatArgumentCannotBeNullOrEmpty() - { - return GetString("ArgumentCannotBeNullOrEmpty"); - } + => GetString("ArgumentCannotBeNullOrEmpty"); private static string GetString(string name, params string[] formatterNames) { diff --git a/src/Microsoft.AspNetCore.Antiforgery/Resources.resx b/src/Microsoft.AspNetCore.Antiforgery/Resources.resx index bda2f0f353..eeda70bc63 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/Resources.resx +++ b/src/Microsoft.AspNetCore.Antiforgery/Resources.resx @@ -139,10 +139,6 @@ The provided antiforgery token was meant for user "{0}", but the current user is "{1}". - - The antiforgery system has the configuration value {0}.{1} = {2}, but the current request is not an SSL request. - 0 = nameof(AntiforgeryOptions), 1 = nameof(RequireSsl), 2 = bool.TrueString - The antiforgery cookie token is invalid. @@ -164,6 +160,9 @@ The required antiforgery request token must be provided. + + The antiforgery system has the configuration value {optionName} = {value}, but the current request is not an SSL request. + Value cannot be null or empty. diff --git a/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/AntiforgeryOptionsSetupTest.cs b/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/AntiforgeryOptionsSetupTest.cs index 181c62b3e5..d901eb9dad 100644 --- a/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/AntiforgeryOptionsSetupTest.cs +++ b/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/AntiforgeryOptionsSetupTest.cs @@ -28,7 +28,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal var options = services.GetRequiredService>(); // Act - var cookieName = options.Value.CookieName; + var cookieName = options.Value.Cookie.Name; // Assert Assert.Equal(expectedCookieName, cookieName); @@ -41,8 +41,8 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal var serviceCollection = new ServiceCollection(); serviceCollection.Configure(o => { - Assert.Null(o.CookieName); - o.CookieName = "antiforgery"; + Assert.Null(o.Cookie.Name); + o.Cookie.Name = "antiforgery"; }); serviceCollection.AddAntiforgery(); serviceCollection @@ -53,7 +53,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal var options = services.GetRequiredService>(); // Act - var cookieName = options.Value.CookieName; + var cookieName = options.Value.Cookie.Name; // Assert Assert.Equal("antiforgery", cookieName); diff --git a/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTest.cs b/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTest.cs index e9b56f1c91..4eebaad29f 100644 --- a/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTest.cs +++ b/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTest.cs @@ -28,9 +28,12 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal { // Arrange var httpContext = GetHttpContext(); - var options = new AntiforgeryOptions() + var options = new AntiforgeryOptions { +#pragma warning disable CS0618 + // obsolete property still forwards to correctly to the new API RequireSsl = true +#pragma warning restore CS0618 }; var antiforgery = GetAntiforgery(httpContext, options); @@ -38,7 +41,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal var exception = await Assert.ThrowsAsync( () => antiforgery.ValidateRequestAsync(httpContext)); Assert.Equal( - @"The antiforgery system has the configuration value AntiforgeryOptions.RequireSsl = true, " + + @"The antiforgery system has the configuration value AntiforgeryOptions.Cookie.SecurePolicy = Always, " + "but the current request is not an SSL request.", exception.Message); } @@ -50,7 +53,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal var httpContext = GetHttpContext(); var options = new AntiforgeryOptions() { - RequireSsl = true + Cookie = { SecurePolicy = CookieSecurePolicy.Always } }; var antiforgery = GetAntiforgery(httpContext, options); @@ -59,7 +62,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal var exception = await Assert.ThrowsAsync( () => antiforgery.IsRequestValidAsync(httpContext)); Assert.Equal( - @"The antiforgery system has the configuration value AntiforgeryOptions.RequireSsl = true, " + + @"The antiforgery system has the configuration value AntiforgeryOptions.Cookie.SecurePolicy = Always, " + "but the current request is not an SSL request.", exception.Message); } @@ -71,7 +74,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal var httpContext = GetHttpContext(); var options = new AntiforgeryOptions() { - RequireSsl = true + Cookie = { SecurePolicy = CookieSecurePolicy.Always } }; var antiforgery = GetAntiforgery(httpContext, options); @@ -80,7 +83,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal var exception = Assert.Throws( () => antiforgery.GetAndStoreTokens(httpContext)); Assert.Equal( - @"The antiforgery system has the configuration value AntiforgeryOptions.RequireSsl = true, " + + @"The antiforgery system has the configuration value AntiforgeryOptions.Cookie.SecurePolicy = Always, " + "but the current request is not an SSL request.", exception.Message); } @@ -92,7 +95,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal var httpContext = GetHttpContext(); var options = new AntiforgeryOptions() { - RequireSsl = true + Cookie = { SecurePolicy = CookieSecurePolicy.Always } }; var antiforgery = GetAntiforgery(httpContext, options); @@ -101,7 +104,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal var exception = Assert.Throws( () => antiforgery.GetTokens(httpContext)); Assert.Equal( - @"The antiforgery system has the configuration value AntiforgeryOptions.RequireSsl = true, " + + @"The antiforgery system has the configuration value AntiforgeryOptions.Cookie.SecurePolicy = Always, " + "but the current request is not an SSL request.", exception.Message); } @@ -113,7 +116,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal var httpContext = GetHttpContext(); var options = new AntiforgeryOptions() { - RequireSsl = true + Cookie = { SecurePolicy = CookieSecurePolicy.Always } }; var antiforgery = GetAntiforgery(httpContext, options); @@ -122,7 +125,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal var exception = Assert.Throws( () => antiforgery.SetCookieTokenAndHeader(httpContext)); Assert.Equal( - @"The antiforgery system has the configuration value AntiforgeryOptions.RequireSsl = true, " + + @"The antiforgery system has the configuration value AntiforgeryOptions.Cookie.SecurePolicy = Always, " + "but the current request is not an SSL request.", exception.Message); } @@ -745,7 +748,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal // Arrange var context = CreateMockContext(new AntiforgeryOptions() { - CookieName = "cookie-name", + Cookie = { Name = "cookie-name" }, FormFieldName = "form-field-name", HeaderName = null, }); @@ -769,7 +772,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal // Arrange var context = CreateMockContext(new AntiforgeryOptions() { - CookieName = "cookie-name", + Cookie = { Name = "cookie-name" }, FormFieldName = "form-field-name", HeaderName = null, }); @@ -793,7 +796,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal // Arrange var context = CreateMockContext(new AntiforgeryOptions() { - CookieName = "cookie-name", + Cookie = { Name = "cookie-name" }, FormFieldName = "form-field-name", HeaderName = "header-name", }); @@ -819,7 +822,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal // Arrange var context = CreateMockContext(new AntiforgeryOptions() { - CookieName = "cookie-name", + Cookie = { Name = "cookie-name" }, FormFieldName = "form-field-name", HeaderName = "header-name", }); diff --git a/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTokenStoreTest.cs b/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTokenStoreTest.cs index 96fd2703fd..c66d31dd53 100644 --- a/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTokenStoreTest.cs +++ b/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTokenStoreTest.cs @@ -21,9 +21,9 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal { // Arrange var httpContext = GetHttpContext(new RequestCookieCollection()); - var options = new AntiforgeryOptions() + var options = new AntiforgeryOptions { - CookieName = _cookieName + Cookie = { Name = _cookieName } }; var tokenStore = new DefaultAntiforgeryTokenStore(new TestOptionsManager(options)); @@ -40,9 +40,9 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal { // Arrange var httpContext = GetHttpContext(_cookieName, string.Empty); - var options = new AntiforgeryOptions() + var options = new AntiforgeryOptions { - CookieName = _cookieName + Cookie = { Name = _cookieName } }; var tokenStore = new DefaultAntiforgeryTokenStore(new TestOptionsManager(options)); @@ -61,9 +61,9 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal var expectedToken = "valid-value"; var httpContext = GetHttpContext(_cookieName, expectedToken); - var options = new AntiforgeryOptions() + var options = new AntiforgeryOptions { - CookieName = _cookieName + Cookie = { Name = _cookieName } }; var tokenStore = new DefaultAntiforgeryTokenStore(new TestOptionsManager(options)); @@ -82,9 +82,9 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal var httpContext = GetHttpContext(new RequestCookieCollection()); httpContext.Request.Form = FormCollection.Empty; - var options = new AntiforgeryOptions() + var options = new AntiforgeryOptions { - CookieName = "cookie-name", + Cookie = { Name = "cookie-name" }, FormFieldName = "form-field-name", }; @@ -110,9 +110,9 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal }); // header value has priority. httpContext.Request.Headers.Add("header-name", "header-value"); - var options = new AntiforgeryOptions() + var options = new AntiforgeryOptions { - CookieName = "cookie-name", + Cookie = { Name = "cookie-name" }, FormFieldName = "form-field-name", HeaderName = "header-name", }; @@ -138,9 +138,9 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal { "form-field-name", "form-value" }, }); - var options = new AntiforgeryOptions() + var options = new AntiforgeryOptions { - CookieName = "cookie-name", + Cookie = { Name = "cookie-name" }, FormFieldName = "form-field-name", HeaderName = "header-name", }; @@ -166,9 +166,9 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal // Will not be accessed httpContext.Request.Form = null; - var options = new AntiforgeryOptions() + var options = new AntiforgeryOptions { - CookieName = "cookie-name", + Cookie = { Name = "cookie-name" }, FormFieldName = "form-field-name", HeaderName = "header-name", }; @@ -193,9 +193,9 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal // Will not be accessed httpContext.Request.Form = null; - var options = new AntiforgeryOptions() + var options = new AntiforgeryOptions { - CookieName = "cookie-name", + Cookie = { Name = "cookie-name" }, FormFieldName = "form-field-name", HeaderName = "header-name", }; @@ -218,9 +218,9 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal httpContext.Request.ContentType = "application/x-www-form-urlencoded"; httpContext.Request.Form = FormCollection.Empty; - var options = new AntiforgeryOptions() + var options = new AntiforgeryOptions { - CookieName = "cookie-name", + Cookie = { Name = "cookie-name" }, FormFieldName = "form-field-name", HeaderName = "header-name", }; @@ -236,9 +236,9 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal } [Theory] - [InlineData(true, true)] - [InlineData(false, null)] - public void SaveCookieToken(bool requireSsl, bool? expectedCookieSecureFlag) + [InlineData(CookieSecurePolicy.Always, true)] + [InlineData(CookieSecurePolicy.None, null)] + public void SaveCookieToken(CookieSecurePolicy policy, bool? expectedCookieSecureFlag) { // Arrange var token = "serialized-value"; @@ -255,8 +255,11 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal var options = new AntiforgeryOptions() { - CookieName = _cookieName, - RequireSsl = requireSsl + Cookie = + { + Name = _cookieName, + SecurePolicy = policy + }, }; var tokenStore = new DefaultAntiforgeryTokenStore(new TestOptionsManager(options)); @@ -294,8 +297,10 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal httpContext .SetupGet(hc => hc.Request.Path) .Returns("/index.html"); - var options = new AntiforgeryOptions(); - options.CookieName = _cookieName; + var options = new AntiforgeryOptions + { + Cookie = { Name = _cookieName } + }; var tokenStore = new DefaultAntiforgeryTokenStore(new TestOptionsManager(options)); // Act @@ -328,9 +333,14 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal httpContext .SetupGet(hc => hc.Request.Path) .Returns("/index.html"); - var options = new AntiforgeryOptions(); - options.CookieName = _cookieName; - options.ConfigureCookieOptions = (context, cookieOptions) => cookieOptions.Path = expectedCookiePath; + var options = new AntiforgeryOptions + { + Cookie = + { + Name = _cookieName, + Path = expectedCookiePath + } + }; var tokenStore = new DefaultAntiforgeryTokenStore(new TestOptionsManager(options)); // Act @@ -362,9 +372,14 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal httpContext .SetupGet(hc => hc.Request.Path) .Returns("/index.html"); - var options = new AntiforgeryOptions(); - options.CookieName = _cookieName; - options.ConfigureCookieOptions = (context, cookieOptions) => cookieOptions.Domain = expectedCookieDomain; + var options = new AntiforgeryOptions + { + Cookie = + { + Name = _cookieName, + Domain = expectedCookieDomain + } + }; var tokenStore = new DefaultAntiforgeryTokenStore(new TestOptionsManager(options)); // Act @@ -407,10 +422,10 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal public void Append(string key, string value, CookieOptions options) { - this.Key = key; - this.Value = value; - this.Options = options; - this.Count++; + Key = key; + Value = value; + Options = options; + Count++; } public void Append(string key, string value) From aa8e9d1f84363d32fc7badd1c7b378ff46145b0b Mon Sep 17 00:00:00 2001 From: Pranav K Date: Mon, 3 Jul 2017 14:04:15 -0700 Subject: [PATCH 212/296] Update LICENSE.txt text --- LICENSE.txt | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/LICENSE.txt b/LICENSE.txt index 0bdc1962b6..7b2956ecee 100644 --- a/LICENSE.txt +++ b/LICENSE.txt @@ -1,10 +1,12 @@ -Copyright (c) .NET Foundation. All rights reserved. +Copyright (c) .NET Foundation and Contributors + +All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use -these files except in compliance with the License. You may obtain a copy of the +this file except in compliance with the License. You may obtain a copy of the License at -http://www.apache.org/licenses/LICENSE-2.0 + http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR From f292fa8db5fbf89ab80eaff7f4c8a469fbe6813b Mon Sep 17 00:00:00 2001 From: Mike Harder Date: Mon, 3 Jul 2017 16:56:46 -0700 Subject: [PATCH 213/296] Set "TreatWarningsAsErrors" before NuGet restore (#150) * Ensures our build stays clean of NuGet warnings --- build/common.props | 1 + 1 file changed, 1 insertion(+) diff --git a/build/common.props b/build/common.props index a66094c2a0..27fd36493a 100644 --- a/build/common.props +++ b/build/common.props @@ -10,6 +10,7 @@ true true $(VersionSuffix)-$(BuildNumber) + true From 30e9db3009443a83a35a3b7c97cd95e33afc474a Mon Sep 17 00:00:00 2001 From: Nate McMaster Date: Thu, 6 Jul 2017 10:34:27 -0700 Subject: [PATCH 214/296] React to aspnet/BuildTools#293 [ci skip] --- build/dependencies.props | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/build/dependencies.props b/build/dependencies.props index 787a051c3a..20d47945e9 100644 --- a/build/dependencies.props +++ b/build/dependencies.props @@ -1,7 +1,7 @@  2.0.0-* - 2.1.0-* + 2.0.1-* 4.7.49 2.0.0-* 2.0.0-* From f17e2098fc81d75ee3b80c2915b7c71755e5e538 Mon Sep 17 00:00:00 2001 From: Pranav K Date: Thu, 6 Jul 2017 15:07:50 -0700 Subject: [PATCH 215/296] Update version suffix for 2.0.0 RTM release --- version.props | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/version.props b/version.props index a327eefab8..4c3cc829ad 100644 --- a/version.props +++ b/version.props @@ -2,6 +2,6 @@ 2.0.0 - preview3 + rtm \ No newline at end of file From 3230531cd343d9dd01c97ada348a32bb4d64c17d Mon Sep 17 00:00:00 2001 From: Pranav K Date: Mon, 10 Jul 2017 11:40:23 -0700 Subject: [PATCH 216/296] Branching for 2.0.0 rtm --- NuGet.config | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/NuGet.config b/NuGet.config index 4e8a1f6de1..37f0d27ea0 100644 --- a/NuGet.config +++ b/NuGet.config @@ -2,7 +2,7 @@ - + From e2a4591384cdb8a9cd10f26b6f0f7046c4a78842 Mon Sep 17 00:00:00 2001 From: Pranav K Date: Mon, 10 Jul 2017 11:57:53 -0700 Subject: [PATCH 217/296] Updating KoreBuild branch --- build.ps1 | 2 +- build.sh | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/build.ps1 b/build.ps1 index 5bf0e2c113..1785334385 100644 --- a/build.ps1 +++ b/build.ps1 @@ -33,7 +33,7 @@ cd $PSScriptRoot $repoFolder = $PSScriptRoot $env:REPO_FOLDER = $repoFolder -$koreBuildZip="https://github.com/aspnet/KoreBuild/archive/dev.zip" +$koreBuildZip="https://github.com/aspnet/KoreBuild/archive/rel/2.0.0.zip" if ($env:KOREBUILD_ZIP) { $koreBuildZip=$env:KOREBUILD_ZIP diff --git a/build.sh b/build.sh index b0bcadb579..5e27ed8efb 100755 --- a/build.sh +++ b/build.sh @@ -2,7 +2,7 @@ repoFolder="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" cd $repoFolder -koreBuildZip="https://github.com/aspnet/KoreBuild/archive/dev.zip" +koreBuildZip="https://github.com/aspnet/KoreBuild/archive/rel/2.0.0.zip" if [ ! -z $KOREBUILD_ZIP ]; then koreBuildZip=$KOREBUILD_ZIP fi From 17ff73dd87ec5b123748648318d5eb728052011f Mon Sep 17 00:00:00 2001 From: Ryan Brandenburg Date: Fri, 7 Jul 2017 14:53:53 -0700 Subject: [PATCH 218/296] Skip first time experience on Appveyor --- appveyor.yml | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/appveyor.yml b/appveyor.yml index 1041615c68..31efd8196f 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -1,4 +1,4 @@ -init: +init: - git config --global core.autocrlf true branches: only: @@ -9,6 +9,10 @@ branches: build_script: - ps: .\build.ps1 clone_depth: 1 +environment: + global: + DOTNET_SKIP_FIRST_TIME_EXPERIENCE: true + DOTNET_CLI_TELEMETRY_OPTOUT: 1 test: off deploy: off os: Visual Studio 2017 From 5456b8bc7cfe5dec7681cd0c3f3a04c3781e98e6 Mon Sep 17 00:00:00 2001 From: Ryan Brandenburg Date: Fri, 21 Jul 2017 12:56:24 -0700 Subject: [PATCH 219/296] 2.0.0-rtm to 2.1.0-preview1 --- version.props | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/version.props b/version.props index 4c3cc829ad..b32d3db0a8 100644 --- a/version.props +++ b/version.props @@ -1,7 +1,7 @@ - 2.0.0 - rtm + 2.1.0 + preview1 \ No newline at end of file From 95617ba1d79fd108bb2c63d39cfbec8358e18a9e Mon Sep 17 00:00:00 2001 From: Ryan Brandenburg Date: Mon, 24 Jul 2017 17:54:02 -0700 Subject: [PATCH 220/296] Set AspNetCoreVersion --- build/dependencies.props | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/build/dependencies.props b/build/dependencies.props index 20d47945e9..686753a6b7 100644 --- a/build/dependencies.props +++ b/build/dependencies.props @@ -1,6 +1,6 @@ - + - 2.0.0-* + 2.1.0-* 2.0.1-* 4.7.49 2.0.0-* From 2614a4a8583a5f3775be99caa804066879a8cfd5 Mon Sep 17 00:00:00 2001 From: Pranav K Date: Tue, 25 Jul 2017 15:11:42 -0700 Subject: [PATCH 221/296] Updating to InternalAspNetCoreSdkVersion 2.1.1-* --- build/dependencies.props | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/build/dependencies.props b/build/dependencies.props index 686753a6b7..3945007fb2 100644 --- a/build/dependencies.props +++ b/build/dependencies.props @@ -1,7 +1,7 @@ 2.1.0-* - 2.0.1-* + 2.1.1-* 4.7.49 2.0.0-* 2.0.0-* From 7d053b49a77c78d507e4c0c8a12cc037bda74aa8 Mon Sep 17 00:00:00 2001 From: Nate McMaster Date: Tue, 25 Jul 2017 16:30:20 -0700 Subject: [PATCH 222/296] Update bootstrappers to use the compiled version of KoreBuild [ci skip] --- .gitignore | 1 + build.cmd | 2 +- build.ps1 | 218 +++++++++++++++++++++++++--------- build.sh | 224 +++++++++++++++++++++++++++++------ build/common.props | 2 +- version.props => version.xml | 5 +- 6 files changed, 357 insertions(+), 95 deletions(-) rename version.props => version.xml (51%) diff --git a/.gitignore b/.gitignore index 6da3c6a3e9..a7fdfd773b 100644 --- a/.gitignore +++ b/.gitignore @@ -38,3 +38,4 @@ node_modules .build/ .testPublish/ global.json +korebuild-lock.txt diff --git a/build.cmd b/build.cmd index 7d4894cb4a..b6c8d24864 100644 --- a/build.cmd +++ b/build.cmd @@ -1,2 +1,2 @@ @ECHO OFF -PowerShell -NoProfile -NoLogo -ExecutionPolicy unrestricted -Command "[System.Threading.Thread]::CurrentThread.CurrentCulture = ''; [System.Threading.Thread]::CurrentThread.CurrentUICulture = '';& '%~dp0build.ps1' %*; exit $LASTEXITCODE" \ No newline at end of file +PowerShell -NoProfile -NoLogo -ExecutionPolicy unrestricted -Command "[System.Threading.Thread]::CurrentThread.CurrentCulture = ''; [System.Threading.Thread]::CurrentThread.CurrentUICulture = '';& '%~dp0build.ps1' %*; exit $LASTEXITCODE" diff --git a/build.ps1 b/build.ps1 index 5bf0e2c113..d5eb4d5cf2 100644 --- a/build.ps1 +++ b/build.ps1 @@ -1,67 +1,177 @@ -$ErrorActionPreference = "Stop" +#!/usr/bin/env powershell +#requires -version 4 -function DownloadWithRetry([string] $url, [string] $downloadLocation, [int] $retries) -{ - while($true) - { - try - { - Invoke-WebRequest $url -OutFile $downloadLocation - break - } - catch - { - $exceptionMessage = $_.Exception.Message - Write-Host "Failed to download '$url': $exceptionMessage" - if ($retries -gt 0) { - $retries-- - Write-Host "Waiting 10 seconds before retrying. Retries left: $retries" - Start-Sleep -Seconds 10 +<# +.SYNOPSIS +Build this repository +.DESCRIPTION +Downloads korebuild if required. Then builds the repository. + +.PARAMETER Path +The folder to build. Defaults to the folder containing this script. + +.PARAMETER Channel +The channel of KoreBuild to download. Overrides the value from the config file. + +.PARAMETER DotNetHome +The directory where .NET Core tools will be stored. + +.PARAMETER ToolsSource +The base url where build tools can be downloaded. Overrides the value from the config file. + +.PARAMETER Update +Updates KoreBuild to the latest version even if a lock file is present. + +.PARAMETER ConfigFile +The path to the configuration file that stores values. Defaults to version.xml. + +.PARAMETER MSBuildArgs +Arguments to be passed to MSBuild + +.NOTES +This function will create a file $PSScriptRoot/korebuild-lock.txt. This lock file can be committed to source, but does not have to be. +When the lockfile is not present, KoreBuild will create one using latest available version from $Channel. + +The $ConfigFile is expected to be an XML file. It is optional, and the configuration values in it are optional as well. + +.EXAMPLE +Example config file: +```xml + + + + dev + https://aspnetcore.blob.core.windows.net/buildtools + + +``` +#> +[CmdletBinding(PositionalBinding = $false)] +param( + [string]$Path = $PSScriptRoot, + [Alias('c')] + [string]$Channel, + [Alias('d')] + [string]$DotNetHome, + [Alias('s')] + [string]$ToolsSource, + [Alias('u')] + [switch]$Update, + [string]$ConfigFile = (Join-Path $PSScriptRoot 'version.xml'), + [Parameter(ValueFromRemainingArguments = $true)] + [string[]]$MSBuildArgs +) + +Set-StrictMode -Version 2 +$ErrorActionPreference = 'Stop' + +# +# Functions +# + +function Get-KoreBuild { + + $lockFile = Join-Path $Path 'korebuild-lock.txt' + + if (!(Test-Path $lockFile) -or $Update) { + Get-RemoteFile "$ToolsSource/korebuild/channels/$Channel/latest.txt" $lockFile + } + + $version = Get-Content $lockFile | Where-Object { $_ -like 'version:*' } | Select-Object -first 1 + if (!$version) { + Write-Error "Failed to parse version from $lockFile. Expected a line that begins with 'version:'" + } + $version = $version.TrimStart('version:').Trim() + $korebuildPath = Join-Paths $DotNetHome ('buildtools', 'korebuild', $version) + + if (!(Test-Path $korebuildPath)) { + Write-Host -ForegroundColor Magenta "Downloading KoreBuild $version" + New-Item -ItemType Directory -Path $korebuildPath | Out-Null + $remotePath = "$ToolsSource/korebuild/artifacts/$version/korebuild.$version.zip" + + try { + $tmpfile = Join-Path ([IO.Path]::GetTempPath()) "KoreBuild-$([guid]::NewGuid()).zip" + Get-RemoteFile $remotePath $tmpfile + if (Get-Command -Name 'Expand-Archive' -ErrorAction Ignore) { + # Use built-in commands where possible as they are cross-plat compatible + Expand-Archive -Path $tmpfile -DestinationPath $korebuildPath } - else - { - $exception = $_.Exception - throw $exception + else { + # Fallback to old approach for old installations of PowerShell + Add-Type -AssemblyName System.IO.Compression.FileSystem + [System.IO.Compression.ZipFile]::ExtractToDirectory($tmpfile, $korebuildPath) } } + catch { + Remove-Item -Recurse -Force $korebuildPath -ErrorAction Ignore + throw + } + finally { + Remove-Item $tmpfile -ErrorAction Ignore + } } + + return $korebuildPath } -cd $PSScriptRoot - -$repoFolder = $PSScriptRoot -$env:REPO_FOLDER = $repoFolder - -$koreBuildZip="https://github.com/aspnet/KoreBuild/archive/dev.zip" -if ($env:KOREBUILD_ZIP) -{ - $koreBuildZip=$env:KOREBUILD_ZIP +function Join-Paths([string]$path, [string[]]$childPaths) { + $childPaths | ForEach-Object { $path = Join-Path $path $_ } + return $path } -$buildFolder = ".build" -$buildFile="$buildFolder\KoreBuild.ps1" - -if (!(Test-Path $buildFolder)) { - Write-Host "Downloading KoreBuild from $koreBuildZip" - - $tempFolder=$env:TEMP + "\KoreBuild-" + [guid]::NewGuid() - New-Item -Path "$tempFolder" -Type directory | Out-Null - - $localZipFile="$tempFolder\korebuild.zip" - - DownloadWithRetry -url $koreBuildZip -downloadLocation $localZipFile -retries 6 - - Add-Type -AssemblyName System.IO.Compression.FileSystem - [System.IO.Compression.ZipFile]::ExtractToDirectory($localZipFile, $tempFolder) - - New-Item -Path "$buildFolder" -Type directory | Out-Null - copy-item "$tempFolder\**\build\*" $buildFolder -Recurse - - # Cleanup - if (Test-Path $tempFolder) { - Remove-Item -Recurse -Force $tempFolder +function Get-RemoteFile([string]$RemotePath, [string]$LocalPath) { + if ($RemotePath -notlike 'http*') { + Copy-Item $RemotePath $LocalPath + return } + + $retries = 10 + while ($retries -gt 0) { + $retries -= 1 + try { + Invoke-WebRequest -UseBasicParsing -Uri $RemotePath -OutFile $LocalPath + return + } + catch { + Write-Verbose "Request failed. $retries retries remaining" + } + } + + Write-Error "Download failed: '$RemotePath'." } -&"$buildFile" @args +# +# Main +# + +# Load configuration or set defaults + +if (Test-Path $ConfigFile) { + [xml] $config = Get-Content $ConfigFile + if (!($Channel)) { [string] $Channel = Select-Xml -Xml $config -XPath '/Project/PropertyGroup/KoreBuildChannel' } + if (!($ToolsSource)) { [string] $ToolsSource = Select-Xml -Xml $config -XPath '/Project/PropertyGroup/KoreBuildToolsSource' } +} + +if (!$DotNetHome) { + $DotNetHome = if ($env:DOTNET_HOME) { $env:DOTNET_HOME } ` + elseif ($env:USERPROFILE) { Join-Path $env:USERPROFILE '.dotnet'} ` + elseif ($env:HOME) {Join-Path $env:HOME '.dotnet'}` + else { Join-Path $PSScriptRoot '.dotnet'} +} + +if (!$Channel) { $Channel = 'dev' } +if (!$ToolsSource) { $ToolsSource = 'https://aspnetcore.blob.core.windows.net/buildtools' } + +# Execute + +$korebuildPath = Get-KoreBuild +Import-Module -Force -Scope Local (Join-Path $korebuildPath 'KoreBuild.psd1') + +try { + Install-Tools $ToolsSource $DotNetHome + Invoke-RepositoryBuild $Path @MSBuildArgs +} +finally { + Remove-Module 'KoreBuild' -ErrorAction Ignore +} diff --git a/build.sh b/build.sh index b0bcadb579..ab590e62f1 100755 --- a/build.sh +++ b/build.sh @@ -1,46 +1,196 @@ #!/usr/bin/env bash -repoFolder="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" -cd $repoFolder -koreBuildZip="https://github.com/aspnet/KoreBuild/archive/dev.zip" -if [ ! -z $KOREBUILD_ZIP ]; then - koreBuildZip=$KOREBUILD_ZIP -fi +set -euo pipefail -buildFolder=".build" -buildFile="$buildFolder/KoreBuild.sh" +# +# variables +# -if test ! -d $buildFolder; then - echo "Downloading KoreBuild from $koreBuildZip" +RESET="\033[0m" +RED="\033[0;31m" +MAGENTA="\033[0;95m" +DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" +[ -z "${DOTNET_HOME:-}"] && DOTNET_HOME="$HOME/.dotnet" +config_file="$DIR/version.xml" +verbose=false +update=false +repo_path="$DIR" +channel='' +tools_source='' - tempFolder="/tmp/KoreBuild-$(uuidgen)" - mkdir $tempFolder +# +# Functions +# +__usage() { + echo "Usage: $(basename ${BASH_SOURCE[0]}) [options] [[--] ...]" + echo "" + echo "Arguments:" + echo " ... Arguments passed to MSBuild. Variable number of arguments allowed." + echo "" + echo "Options:" + echo " --verbose Show verbose output." + echo " -c|--channel The channel of KoreBuild to download. Overrides the value from the config file.." + echo " --config-file TThe path to the configuration file that stores values. Defaults to version.xml." + echo " -d|--dotnet-home The directory where .NET Core tools will be stored. Defaults to '\$DOTNET_HOME' or '\$HOME/.dotnet." + echo " --path The directory to build. Defaults to the directory containing the script." + echo " -s|--tools-source The base url where build tools can be downloaded. Overrides the value from the config file." + echo " -u|--update Update to the latest KoreBuild even if the lock file is present." + echo "" + echo "Description:" + echo " This function will create a file \$DIR/korebuild-lock.txt. This lock file can be committed to source, but does not have to be." + echo " When the lockfile is not present, KoreBuild will create one using latest available version from \$channel." - localZipFile="$tempFolder/korebuild.zip" - - retries=6 - until (wget -O $localZipFile $koreBuildZip 2>/dev/null || curl -o $localZipFile --location $koreBuildZip 2>/dev/null) - do - echo "Failed to download '$koreBuildZip'" - if [ "$retries" -le 0 ]; then - exit 1 - fi - retries=$((retries - 1)) - echo "Waiting 10 seconds before retrying. Retries left: $retries" - sleep 10s - done - - unzip -q -d $tempFolder $localZipFile - - mkdir $buildFolder - cp -r $tempFolder/**/build/** $buildFolder - - chmod +x $buildFile - - # Cleanup - if test -d $tempFolder; then - rm -rf $tempFolder + if [[ "${1:-}" != '--no-exit' ]]; then + exit 2 fi +} + +get_korebuild() { + local lock_file="$repo_path/korebuild-lock.txt" + if [ ! -f $lock_file ] || [ "$update" = true ]; then + __get_remote_file "$tools_source/korebuild/channels/$channel/latest.txt" $lock_file + fi + local version="$(grep 'version:*' -m 1 $lock_file)" + if [[ "$version" == '' ]]; then + __error "Failed to parse version from $lock_file. Expected a line that begins with 'version:'" + return 1 + fi + version="$(echo ${version#version:} | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//')" + local korebuild_path="$DOTNET_HOME/buildtools/korebuild/$version" + + { + if [ ! -d "$korebuild_path" ]; then + mkdir -p "$korebuild_path" + local remote_path="$tools_source/korebuild/artifacts/$version/korebuild.$version.zip" + tmpfile="$(mktemp)" + echo -e "${MAGENTA}Downloading KoreBuild ${version}${RESET}" + if __get_remote_file $remote_path $tmpfile; then + unzip -q -d "$korebuild_path" $tmpfile + fi + rm $tmpfile || true + fi + + source "$korebuild_path/KoreBuild.sh" + } || { + if [ -d "$korebuild_path" ]; then + echo "Cleaning up after failed installation" + rm -rf "$korebuild_path" || true + fi + return 1 + } +} + +__error() { + echo -e "${RED}$@${RESET}" 1>&2 +} + +__machine_has() { + hash "$1" > /dev/null 2>&1 + return $? +} + +__get_remote_file() { + local remote_path=$1 + local local_path=$2 + + if [[ "$remote_path" != 'http'* ]]; then + cp $remote_path $local_path + return 0 + fi + + failed=false + if __machine_has wget; then + wget --tries 10 --quiet -O $local_path $remote_path || failed=true + fi + + if [ "$failed" = true ] && __machine_has curl; then + failed=false + curl --retry 10 -sSL -f --create-dirs -o $local_path $remote_path || failed=true + fi + + if [ "$failed" = true ]; then + __error "Download failed: $remote_path" 1>&2 + return 1 + fi +} + +__read_dom () { local IFS=\> ; read -d \< ENTITY CONTENT ;} + +# +# main +# + +while [[ $# > 0 ]]; do + case $1 in + -\?|-h|--help) + __usage --no-exit + exit 0 + ;; + -c|--channel|-Channel) + shift + channel=${1:-} + [ -z "$channel" ] && __usage + ;; + --config-file|-ConfigFile) + shift + config_file="${1:-}" + [ -z "$config_file" ] && __usage + ;; + -d|--dotnet-home|-DotNetHome) + shift + DOTNET_HOME=${1:-} + [ -z "$DOTNET_HOME" ] && __usage + ;; + --path|-Path) + shift + repo_path="${1:-}" + [ -z "$repo_path" ] && __usage + ;; + -s|--tools-source|-ToolsSource) + shift + tools_source="${1:-}" + [ -z "$tools_source" ] && __usage + ;; + -u|--update|-Update) + update=true + ;; + --verbose|-Verbose) + verbose=true + ;; + --) + shift + break + ;; + *) + break + ;; + esac + shift +done + +if ! __machine_has unzip; then + __error 'Missing required command: unzip' + exit 1 fi -$buildFile -r $repoFolder "$@" +if ! __machine_has curl && ! __machine_has wget; then + __error 'Missing required command. Either wget or curl is required.' + exit 1 +fi + +if [ -f $config_file ]; then + comment=false + while __read_dom; do + if [ "$comment" = true ]; then [[ $CONTENT == *'-->'* ]] && comment=false ; continue; fi + if [[ $ENTITY == '!--'* ]]; then comment=true; continue; fi + if [ -z "$channel" ] && [[ $ENTITY == "KoreBuildChannel" ]]; then channel=$CONTENT; fi + if [ -z "$tools_source" ] && [[ $ENTITY == "KoreBuildToolsSource" ]]; then tools_source=$CONTENT; fi + done < $config_file +fi + +[ -z "$channel" ] && channel='dev' +[ -z "$tools_source" ] && tools_source='https://aspnetcore.blob.core.windows.net/buildtools' + +get_korebuild +install_tools "$tools_source" "$DOTNET_HOME" +invoke_repository_build "$repo_path" $@ diff --git a/build/common.props b/build/common.props index 27fd36493a..69a42f2736 100644 --- a/build/common.props +++ b/build/common.props @@ -1,6 +1,6 @@ - + Microsoft ASP.NET Core diff --git a/version.props b/version.xml similarity index 51% rename from version.props rename to version.xml index b32d3db0a8..3c05022b7d 100644 --- a/version.props +++ b/version.xml @@ -1,7 +1,8 @@ - + + dev 2.1.0 preview1 - \ No newline at end of file + From 3ce2d54d3beec4f7a51eee9d80fa3fae124db227 Mon Sep 17 00:00:00 2001 From: Nate McMaster Date: Wed, 26 Jul 2017 10:26:22 -0700 Subject: [PATCH 223/296] Fix syntax warning when running build.sh on older versions of bash [ci skip] --- build.sh | 41 +++++++++++++++++++++-------------------- 1 file changed, 21 insertions(+), 20 deletions(-) diff --git a/build.sh b/build.sh index ab590e62f1..5568c6182a 100755 --- a/build.sh +++ b/build.sh @@ -10,7 +10,7 @@ RESET="\033[0m" RED="\033[0;31m" MAGENTA="\033[0;95m" DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" -[ -z "${DOTNET_HOME:-}"] && DOTNET_HOME="$HOME/.dotnet" +[ -z "${DOTNET_HOME:-}" ] && DOTNET_HOME="$HOME/.dotnet" config_file="$DIR/version.xml" verbose=false update=false @@ -22,7 +22,7 @@ tools_source='' # Functions # __usage() { - echo "Usage: $(basename ${BASH_SOURCE[0]}) [options] [[--] ...]" + echo "Usage: $(basename "${BASH_SOURCE[0]}") [options] [[--] ...]" echo "" echo "Arguments:" echo " ... Arguments passed to MSBuild. Variable number of arguments allowed." @@ -46,16 +46,17 @@ __usage() { } get_korebuild() { + local version local lock_file="$repo_path/korebuild-lock.txt" - if [ ! -f $lock_file ] || [ "$update" = true ]; then - __get_remote_file "$tools_source/korebuild/channels/$channel/latest.txt" $lock_file + if [ ! -f "$lock_file" ] || [ "$update" = true ]; then + __get_remote_file "$tools_source/korebuild/channels/$channel/latest.txt" "$lock_file" fi - local version="$(grep 'version:*' -m 1 $lock_file)" + version="$(grep 'version:*' -m 1 "$lock_file")" if [[ "$version" == '' ]]; then __error "Failed to parse version from $lock_file. Expected a line that begins with 'version:'" return 1 fi - version="$(echo ${version#version:} | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//')" + version="$(echo "${version#version:}" | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//')" local korebuild_path="$DOTNET_HOME/buildtools/korebuild/$version" { @@ -64,10 +65,10 @@ get_korebuild() { local remote_path="$tools_source/korebuild/artifacts/$version/korebuild.$version.zip" tmpfile="$(mktemp)" echo -e "${MAGENTA}Downloading KoreBuild ${version}${RESET}" - if __get_remote_file $remote_path $tmpfile; then - unzip -q -d "$korebuild_path" $tmpfile + if __get_remote_file "$remote_path" "$tmpfile"; then + unzip -q -d "$korebuild_path" "$tmpfile" fi - rm $tmpfile || true + rm "$tmpfile" || true fi source "$korebuild_path/KoreBuild.sh" @@ -81,7 +82,7 @@ get_korebuild() { } __error() { - echo -e "${RED}$@${RESET}" 1>&2 + echo -e "${RED}$*${RESET}" 1>&2 } __machine_has() { @@ -94,18 +95,18 @@ __get_remote_file() { local local_path=$2 if [[ "$remote_path" != 'http'* ]]; then - cp $remote_path $local_path + cp "$remote_path" "$local_path" return 0 fi failed=false if __machine_has wget; then - wget --tries 10 --quiet -O $local_path $remote_path || failed=true + wget --tries 10 --quiet -O "$local_path" "$remote_path" || failed=true fi if [ "$failed" = true ] && __machine_has curl; then failed=false - curl --retry 10 -sSL -f --create-dirs -o $local_path $remote_path || failed=true + curl --retry 10 -sSL -f --create-dirs -o "$local_path" "$remote_path" || failed=true fi if [ "$failed" = true ]; then @@ -114,13 +115,13 @@ __get_remote_file() { fi } -__read_dom () { local IFS=\> ; read -d \< ENTITY CONTENT ;} +__read_dom () { local IFS=\> ; read -r -d \< ENTITY CONTENT ;} # # main # -while [[ $# > 0 ]]; do +while [[ $# -gt 0 ]]; do case $1 in -\?|-h|--help) __usage --no-exit @@ -128,7 +129,7 @@ while [[ $# > 0 ]]; do ;; -c|--channel|-Channel) shift - channel=${1:-} + channel="${1:-}" [ -z "$channel" ] && __usage ;; --config-file|-ConfigFile) @@ -138,7 +139,7 @@ while [[ $# > 0 ]]; do ;; -d|--dotnet-home|-DotNetHome) shift - DOTNET_HOME=${1:-} + DOTNET_HOME="${1:-}" [ -z "$DOTNET_HOME" ] && __usage ;; --path|-Path) @@ -178,14 +179,14 @@ if ! __machine_has curl && ! __machine_has wget; then exit 1 fi -if [ -f $config_file ]; then +if [ -f "$config_file" ]; then comment=false while __read_dom; do if [ "$comment" = true ]; then [[ $CONTENT == *'-->'* ]] && comment=false ; continue; fi if [[ $ENTITY == '!--'* ]]; then comment=true; continue; fi if [ -z "$channel" ] && [[ $ENTITY == "KoreBuildChannel" ]]; then channel=$CONTENT; fi if [ -z "$tools_source" ] && [[ $ENTITY == "KoreBuildToolsSource" ]]; then tools_source=$CONTENT; fi - done < $config_file + done < "$config_file" fi [ -z "$channel" ] && channel='dev' @@ -193,4 +194,4 @@ fi get_korebuild install_tools "$tools_source" "$DOTNET_HOME" -invoke_repository_build "$repo_path" $@ +invoke_repository_build "$repo_path" "$@" From 791e4dc38bafd626aad048b5cc820de624255420 Mon Sep 17 00:00:00 2001 From: John Luo Date: Wed, 2 Aug 2017 12:44:42 -0700 Subject: [PATCH 224/296] Update __get_remote_file logic --- build.sh | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/build.sh b/build.sh index 5568c6182a..8eace4c20d 100755 --- a/build.sh +++ b/build.sh @@ -99,17 +99,16 @@ __get_remote_file() { return 0 fi - failed=false + local succeeded=false if __machine_has wget; then - wget --tries 10 --quiet -O "$local_path" "$remote_path" || failed=true + wget --tries 10 --quiet -O "$local_path" "$remote_path" && succeeded=true fi - if [ "$failed" = true ] && __machine_has curl; then - failed=false - curl --retry 10 -sSL -f --create-dirs -o "$local_path" "$remote_path" || failed=true + if [ "$succeeded" = false ] && __machine_has curl; then + curl --retry 10 -sSL -f --create-dirs -o "$local_path" "$remote_path" && succeeded=true fi - if [ "$failed" = true ]; then + if [ "$succeeded" = false ]; then __error "Download failed: $remote_path" 1>&2 return 1 fi From 48396215b44adc812fe8ff37b25a269be6edef5f Mon Sep 17 00:00:00 2001 From: John Luo Date: Wed, 2 Aug 2017 14:30:21 -0700 Subject: [PATCH 225/296] Ensure fallback to curl after failed wget --- build.sh | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/build.sh b/build.sh index 8eace4c20d..11cdbe5504 100755 --- a/build.sh +++ b/build.sh @@ -99,16 +99,19 @@ __get_remote_file() { return 0 fi - local succeeded=false + local failed=false if __machine_has wget; then - wget --tries 10 --quiet -O "$local_path" "$remote_path" && succeeded=true + wget --tries 10 --quiet -O "$local_path" "$remote_path" || failed=true + else + failed=true fi - if [ "$succeeded" = false ] && __machine_has curl; then - curl --retry 10 -sSL -f --create-dirs -o "$local_path" "$remote_path" && succeeded=true + if [ "$failed" = true ] && __machine_has curl; then + failed=false + curl --retry 10 -sSL -f --create-dirs -o "$local_path" "$remote_path" || failed=true fi - if [ "$succeeded" = false ]; then + if [ "$failed" = true ]; then __error "Download failed: $remote_path" 1>&2 return 1 fi From 3f065cb77431514b277c1a9ea3d32fa792e2b3d2 Mon Sep 17 00:00:00 2001 From: Nate McMaster Date: Tue, 22 Aug 2017 10:42:42 -0700 Subject: [PATCH 226/296] Upgrade to xunit 2.3.0-beta4 --- build/dependencies.props | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/build/dependencies.props b/build/dependencies.props index 3945007fb2..d065721b60 100644 --- a/build/dependencies.props +++ b/build/dependencies.props @@ -6,7 +6,7 @@ 2.0.0-* 2.0.0-* 2.0.0-* - 15.3.0-* - 2.3.0-beta2-* + 15.3.0 + 2.3.0-beta4-build3742 From ab2730ea4f63deb1a945258d724a8d91249277a6 Mon Sep 17 00:00:00 2001 From: Nate McMaster Date: Mon, 28 Aug 2017 10:37:05 -0700 Subject: [PATCH 227/296] Use Directory.Build.targets/props --- build/common.props => Directory.Build.props | 8 ++++---- Directory.Build.targets | 2 ++ .../Microsoft.AspNetCore.Antiforgery.csproj | 2 -- .../Microsoft.AspNetCore.Antiforgery.Test.csproj | 4 +--- 4 files changed, 7 insertions(+), 9 deletions(-) rename build/common.props => Directory.Build.props (76%) create mode 100644 Directory.Build.targets diff --git a/build/common.props b/Directory.Build.props similarity index 76% rename from build/common.props rename to Directory.Build.props index 69a42f2736..236b23f856 100644 --- a/build/common.props +++ b/Directory.Build.props @@ -1,12 +1,12 @@ - - - + + + Microsoft ASP.NET Core https://github.com/aspnet/Antiforgery git - $(MSBuildThisFileDirectory)Key.snk + $(MSBuildThisFileDirectory)build\Key.snk true true $(VersionSuffix)-$(BuildNumber) diff --git a/Directory.Build.targets b/Directory.Build.targets new file mode 100644 index 0000000000..f75adf7e4d --- /dev/null +++ b/Directory.Build.targets @@ -0,0 +1,2 @@ + + diff --git a/src/Microsoft.AspNetCore.Antiforgery/Microsoft.AspNetCore.Antiforgery.csproj b/src/Microsoft.AspNetCore.Antiforgery/Microsoft.AspNetCore.Antiforgery.csproj index 2e8ce21e1a..b349eb9496 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/Microsoft.AspNetCore.Antiforgery.csproj +++ b/src/Microsoft.AspNetCore.Antiforgery/Microsoft.AspNetCore.Antiforgery.csproj @@ -1,7 +1,5 @@  - - An antiforgery system for ASP.NET Core designed to generate and validate tokens to prevent Cross-Site Request Forgery attacks. netstandard2.0 diff --git a/test/Microsoft.AspNetCore.Antiforgery.Test/Microsoft.AspNetCore.Antiforgery.Test.csproj b/test/Microsoft.AspNetCore.Antiforgery.Test/Microsoft.AspNetCore.Antiforgery.Test.csproj index 021d56162a..1f8826d6ee 100644 --- a/test/Microsoft.AspNetCore.Antiforgery.Test/Microsoft.AspNetCore.Antiforgery.Test.csproj +++ b/test/Microsoft.AspNetCore.Antiforgery.Test/Microsoft.AspNetCore.Antiforgery.Test.csproj @@ -1,6 +1,4 @@ - - - + netcoreapp2.0;net461 From ac0ce9c8eecdef58b8eedc478d27cd31ccffc16c Mon Sep 17 00:00:00 2001 From: Nate McMaster Date: Mon, 28 Aug 2017 14:19:18 -0700 Subject: [PATCH 228/296] Use PackageLineup to manage PackageReference versions (#162) --- appveyor.yml => .appveyor.yml | 0 Directory.Build.props | 3 +-- Directory.Build.targets | 14 ++++++++++++- NuGet.config | 1 - build/dependencies.props | 12 ----------- build/repo.props | 6 ++++++ .../Microsoft.AspNetCore.Antiforgery.csproj | 10 +++++----- ...crosoft.AspNetCore.Antiforgery.Test.csproj | 20 +++++++++---------- 8 files changed, 35 insertions(+), 31 deletions(-) rename appveyor.yml => .appveyor.yml (100%) delete mode 100644 build/dependencies.props create mode 100644 build/repo.props diff --git a/appveyor.yml b/.appveyor.yml similarity index 100% rename from appveyor.yml rename to .appveyor.yml diff --git a/Directory.Build.props b/Directory.Build.props index 236b23f856..29f2734566 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -1,5 +1,4 @@  - @@ -14,6 +13,6 @@ - + diff --git a/Directory.Build.targets b/Directory.Build.targets index f75adf7e4d..bc118fd907 100644 --- a/Directory.Build.targets +++ b/Directory.Build.targets @@ -1,2 +1,14 @@ - + + + + <_BootstrapperFile Condition=" $([MSBuild]::IsOSUnixLike()) ">build.sh + <_BootstrapperFile Condition="! $([MSBuild]::IsOSUnixLike()) ">build.cmd + <_BootstrapperError> + Package references have not been pinned. Run './$(_BootstrapperFile) /t:Pin'. + Also, you can run './$(_BootstrapperFile) /t:Restore' which will pin *and* restore packages. '$(_BootstrapperFile)' can be found in '$(MSBuildThisFileDirectory)'. + + + + + diff --git a/NuGet.config b/NuGet.config index 4e8a1f6de1..20060c934e 100644 --- a/NuGet.config +++ b/NuGet.config @@ -3,7 +3,6 @@ - diff --git a/build/dependencies.props b/build/dependencies.props deleted file mode 100644 index d065721b60..0000000000 --- a/build/dependencies.props +++ /dev/null @@ -1,12 +0,0 @@ - - - 2.1.0-* - 2.1.1-* - 4.7.49 - 2.0.0-* - 2.0.0-* - 2.0.0-* - 15.3.0 - 2.3.0-beta4-build3742 - - diff --git a/build/repo.props b/build/repo.props new file mode 100644 index 0000000000..13fe1c296a --- /dev/null +++ b/build/repo.props @@ -0,0 +1,6 @@ + + + + + + diff --git a/src/Microsoft.AspNetCore.Antiforgery/Microsoft.AspNetCore.Antiforgery.csproj b/src/Microsoft.AspNetCore.Antiforgery/Microsoft.AspNetCore.Antiforgery.csproj index b349eb9496..051809e5de 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/Microsoft.AspNetCore.Antiforgery.csproj +++ b/src/Microsoft.AspNetCore.Antiforgery/Microsoft.AspNetCore.Antiforgery.csproj @@ -9,11 +9,11 @@ - - - - - + + + + + diff --git a/test/Microsoft.AspNetCore.Antiforgery.Test/Microsoft.AspNetCore.Antiforgery.Test.csproj b/test/Microsoft.AspNetCore.Antiforgery.Test/Microsoft.AspNetCore.Antiforgery.Test.csproj index 1f8826d6ee..f6a72152bb 100644 --- a/test/Microsoft.AspNetCore.Antiforgery.Test/Microsoft.AspNetCore.Antiforgery.Test.csproj +++ b/test/Microsoft.AspNetCore.Antiforgery.Test/Microsoft.AspNetCore.Antiforgery.Test.csproj @@ -10,16 +10,16 @@ - - - - - - - - - - + + + + + + + + + + From 12e9430d89b85c1be0029ba2cded7840b2c59999 Mon Sep 17 00:00:00 2001 From: Kiran Challa Date: Tue, 29 Aug 2017 11:24:36 -0700 Subject: [PATCH 229/296] Sets the default cookie secure policy to None --- .../AntiforgeryOptions.cs | 9 ++++++++- .../Internal/AntiforgeryOptionsSetupTest.cs | 11 +++++++++++ .../Internal/DefaultAntiforgeryTokenStoreTest.cs | 16 +++++++++++++--- 3 files changed, 32 insertions(+), 4 deletions(-) diff --git a/src/Microsoft.AspNetCore.Antiforgery/AntiforgeryOptions.cs b/src/Microsoft.AspNetCore.Antiforgery/AntiforgeryOptions.cs index f0de2da040..405905b587 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/AntiforgeryOptions.cs +++ b/src/Microsoft.AspNetCore.Antiforgery/AntiforgeryOptions.cs @@ -19,7 +19,14 @@ namespace Microsoft.AspNetCore.Antiforgery private CookieBuilder _cookieBuilder = new CookieBuilder { SameSite = SameSiteMode.Strict, - HttpOnly = true + HttpOnly = true, + + // Some browsers do not allow non-secure endpoints to set cookies with a 'secure' flag or overwrite cookies + // whose 'secure' flag is set (http://httpwg.org/http-extensions/draft-ietf-httpbis-cookie-alone.html). + // Since mixing secure and non-secure endpoints is a common scenario in applications, we are relaxing the + // restriction on secure policy on some cookies by setting to 'None'. Cookies related to authentication or + // authorization use a stronger policy than 'None'. + SecurePolicy = CookieSecurePolicy.None, }; /// diff --git a/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/AntiforgeryOptionsSetupTest.cs b/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/AntiforgeryOptionsSetupTest.cs index d901eb9dad..b0acff572d 100644 --- a/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/AntiforgeryOptionsSetupTest.cs +++ b/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/AntiforgeryOptionsSetupTest.cs @@ -2,6 +2,7 @@ // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using Microsoft.AspNetCore.DataProtection; +using Microsoft.AspNetCore.Http; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Options; using Xunit; @@ -58,5 +59,15 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal // Assert Assert.Equal("antiforgery", cookieName); } + + [Fact] + public void AntiforgeryOptions_SetsCookieSecurePolicy_ToNone_ByDefault() + { + // Arrange & Act + var options = new AntiforgeryOptions(); + + // Assert + Assert.Equal(CookieSecurePolicy.None, options.Cookie.SecurePolicy); + } } } diff --git a/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTokenStoreTest.cs b/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTokenStoreTest.cs index c66d31dd53..1ca1f57fc5 100644 --- a/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTokenStoreTest.cs +++ b/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTokenStoreTest.cs @@ -236,9 +236,16 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal } [Theory] - [InlineData(CookieSecurePolicy.Always, true)] - [InlineData(CookieSecurePolicy.None, null)] - public void SaveCookieToken(CookieSecurePolicy policy, bool? expectedCookieSecureFlag) + [InlineData(false, CookieSecurePolicy.SameAsRequest, null)] + [InlineData(true, CookieSecurePolicy.SameAsRequest, true)] + [InlineData(false, CookieSecurePolicy.Always, true)] + [InlineData(true, CookieSecurePolicy.Always, true)] + [InlineData(false, CookieSecurePolicy.None, null)] + [InlineData(true, CookieSecurePolicy.None, null)] + public void SaveCookieToken_HonorsCookieSecurePolicy_OnOptions( + bool isRequestSecure, + CookieSecurePolicy policy, + bool? expectedCookieSecureFlag) { // Arrange var token = "serialized-value"; @@ -246,6 +253,9 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal var cookies = new MockResponseCookieCollection(); var httpContext = new Mock(); + httpContext + .Setup(hc => hc.Request.IsHttps) + .Returns(isRequestSecure); httpContext .Setup(o => o.Response.Cookies) .Returns(cookies); From 68889167bdd101cf64849a2e583d56ffc715a0ce Mon Sep 17 00:00:00 2001 From: Nate McMaster Date: Fri, 1 Sep 2017 17:16:20 -0700 Subject: [PATCH 230/296] Rename version.xml => version.props --- Directory.Build.props | 3 +-- version.xml => version.props | 2 +- 2 files changed, 2 insertions(+), 3 deletions(-) rename version.xml => version.props (59%) diff --git a/Directory.Build.props b/Directory.Build.props index 29f2734566..95cb477c45 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -1,5 +1,5 @@  - + Microsoft ASP.NET Core @@ -8,7 +8,6 @@ $(MSBuildThisFileDirectory)build\Key.snk true true - $(VersionSuffix)-$(BuildNumber) true diff --git a/version.xml b/version.props similarity index 59% rename from version.xml rename to version.props index 3c05022b7d..cf1954f5c5 100644 --- a/version.xml +++ b/version.props @@ -1,8 +1,8 @@ - dev 2.1.0 preview1 + $(VersionSuffix)-$(BuildNumber) From b6a2732a8284d711a9e01af7837accc67d33ef26 Mon Sep 17 00:00:00 2001 From: Justin Kotalik Date: Thu, 21 Sep 2017 17:34:19 -0700 Subject: [PATCH 231/296] Increase Minimum Version of Visual Studio to 15.3.0 --- Antiforgery.sln | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Antiforgery.sln b/Antiforgery.sln index 44bca25a08..a4f13419cd 100644 --- a/Antiforgery.sln +++ b/Antiforgery.sln @@ -1,7 +1,7 @@ Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio 15 VisualStudioVersion = 15.0.26208.0 -MinimumVisualStudioVersion = 10.0.40219.1 +MinimumVisualStudioVersion = 15.0.26730.03 Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{71D070C4-B325-48F7-9F25-DD4E91C2BBCA}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "test", "test", "{6EDD8B57-4DE8-4246-A6A3-47ECD92740B4}" From 7f111956fd04647dd8a5ef6d9f2e1671e3d36b2d Mon Sep 17 00:00:00 2001 From: Ryan Brandenburg Date: Wed, 20 Sep 2017 13:17:47 -0700 Subject: [PATCH 232/296] Update bootstrappers --- .appveyor.yml | 4 +- build.cmd | 2 +- build.sh | 197 +------------------------------------- run.cmd | 2 + build.ps1 => run.ps1 | 56 +++++++---- run.sh | 223 +++++++++++++++++++++++++++++++++++++++++++ 6 files changed, 266 insertions(+), 218 deletions(-) create mode 100644 run.cmd rename build.ps1 => run.ps1 (73%) create mode 100755 run.sh diff --git a/.appveyor.yml b/.appveyor.yml index 31efd8196f..46038786c9 100644 --- a/.appveyor.yml +++ b/.appveyor.yml @@ -1,4 +1,4 @@ -init: +init: - git config --global core.autocrlf true branches: only: @@ -7,7 +7,7 @@ branches: - dev - /^(.*\/)?ci-.*$/ build_script: - - ps: .\build.ps1 + - ps: .\run.ps1 default-build clone_depth: 1 environment: global: diff --git a/build.cmd b/build.cmd index b6c8d24864..c0050bda12 100644 --- a/build.cmd +++ b/build.cmd @@ -1,2 +1,2 @@ @ECHO OFF -PowerShell -NoProfile -NoLogo -ExecutionPolicy unrestricted -Command "[System.Threading.Thread]::CurrentThread.CurrentCulture = ''; [System.Threading.Thread]::CurrentThread.CurrentUICulture = '';& '%~dp0build.ps1' %*; exit $LASTEXITCODE" +PowerShell -NoProfile -NoLogo -ExecutionPolicy unrestricted -Command "[System.Threading.Thread]::CurrentThread.CurrentCulture = ''; [System.Threading.Thread]::CurrentThread.CurrentUICulture = '';& '%~dp0run.ps1' default-build %*; exit $LASTEXITCODE" diff --git a/build.sh b/build.sh index 11cdbe5504..98a4b22765 100755 --- a/build.sh +++ b/build.sh @@ -1,199 +1,8 @@ #!/usr/bin/env bash set -euo pipefail - -# -# variables -# - -RESET="\033[0m" -RED="\033[0;31m" -MAGENTA="\033[0;95m" DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" -[ -z "${DOTNET_HOME:-}" ] && DOTNET_HOME="$HOME/.dotnet" -config_file="$DIR/version.xml" -verbose=false -update=false -repo_path="$DIR" -channel='' -tools_source='' -# -# Functions -# -__usage() { - echo "Usage: $(basename "${BASH_SOURCE[0]}") [options] [[--] ...]" - echo "" - echo "Arguments:" - echo " ... Arguments passed to MSBuild. Variable number of arguments allowed." - echo "" - echo "Options:" - echo " --verbose Show verbose output." - echo " -c|--channel The channel of KoreBuild to download. Overrides the value from the config file.." - echo " --config-file TThe path to the configuration file that stores values. Defaults to version.xml." - echo " -d|--dotnet-home The directory where .NET Core tools will be stored. Defaults to '\$DOTNET_HOME' or '\$HOME/.dotnet." - echo " --path The directory to build. Defaults to the directory containing the script." - echo " -s|--tools-source The base url where build tools can be downloaded. Overrides the value from the config file." - echo " -u|--update Update to the latest KoreBuild even if the lock file is present." - echo "" - echo "Description:" - echo " This function will create a file \$DIR/korebuild-lock.txt. This lock file can be committed to source, but does not have to be." - echo " When the lockfile is not present, KoreBuild will create one using latest available version from \$channel." - - if [[ "${1:-}" != '--no-exit' ]]; then - exit 2 - fi -} - -get_korebuild() { - local version - local lock_file="$repo_path/korebuild-lock.txt" - if [ ! -f "$lock_file" ] || [ "$update" = true ]; then - __get_remote_file "$tools_source/korebuild/channels/$channel/latest.txt" "$lock_file" - fi - version="$(grep 'version:*' -m 1 "$lock_file")" - if [[ "$version" == '' ]]; then - __error "Failed to parse version from $lock_file. Expected a line that begins with 'version:'" - return 1 - fi - version="$(echo "${version#version:}" | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//')" - local korebuild_path="$DOTNET_HOME/buildtools/korebuild/$version" - - { - if [ ! -d "$korebuild_path" ]; then - mkdir -p "$korebuild_path" - local remote_path="$tools_source/korebuild/artifacts/$version/korebuild.$version.zip" - tmpfile="$(mktemp)" - echo -e "${MAGENTA}Downloading KoreBuild ${version}${RESET}" - if __get_remote_file "$remote_path" "$tmpfile"; then - unzip -q -d "$korebuild_path" "$tmpfile" - fi - rm "$tmpfile" || true - fi - - source "$korebuild_path/KoreBuild.sh" - } || { - if [ -d "$korebuild_path" ]; then - echo "Cleaning up after failed installation" - rm -rf "$korebuild_path" || true - fi - return 1 - } -} - -__error() { - echo -e "${RED}$*${RESET}" 1>&2 -} - -__machine_has() { - hash "$1" > /dev/null 2>&1 - return $? -} - -__get_remote_file() { - local remote_path=$1 - local local_path=$2 - - if [[ "$remote_path" != 'http'* ]]; then - cp "$remote_path" "$local_path" - return 0 - fi - - local failed=false - if __machine_has wget; then - wget --tries 10 --quiet -O "$local_path" "$remote_path" || failed=true - else - failed=true - fi - - if [ "$failed" = true ] && __machine_has curl; then - failed=false - curl --retry 10 -sSL -f --create-dirs -o "$local_path" "$remote_path" || failed=true - fi - - if [ "$failed" = true ]; then - __error "Download failed: $remote_path" 1>&2 - return 1 - fi -} - -__read_dom () { local IFS=\> ; read -r -d \< ENTITY CONTENT ;} - -# -# main -# - -while [[ $# -gt 0 ]]; do - case $1 in - -\?|-h|--help) - __usage --no-exit - exit 0 - ;; - -c|--channel|-Channel) - shift - channel="${1:-}" - [ -z "$channel" ] && __usage - ;; - --config-file|-ConfigFile) - shift - config_file="${1:-}" - [ -z "$config_file" ] && __usage - ;; - -d|--dotnet-home|-DotNetHome) - shift - DOTNET_HOME="${1:-}" - [ -z "$DOTNET_HOME" ] && __usage - ;; - --path|-Path) - shift - repo_path="${1:-}" - [ -z "$repo_path" ] && __usage - ;; - -s|--tools-source|-ToolsSource) - shift - tools_source="${1:-}" - [ -z "$tools_source" ] && __usage - ;; - -u|--update|-Update) - update=true - ;; - --verbose|-Verbose) - verbose=true - ;; - --) - shift - break - ;; - *) - break - ;; - esac - shift -done - -if ! __machine_has unzip; then - __error 'Missing required command: unzip' - exit 1 -fi - -if ! __machine_has curl && ! __machine_has wget; then - __error 'Missing required command. Either wget or curl is required.' - exit 1 -fi - -if [ -f "$config_file" ]; then - comment=false - while __read_dom; do - if [ "$comment" = true ]; then [[ $CONTENT == *'-->'* ]] && comment=false ; continue; fi - if [[ $ENTITY == '!--'* ]]; then comment=true; continue; fi - if [ -z "$channel" ] && [[ $ENTITY == "KoreBuildChannel" ]]; then channel=$CONTENT; fi - if [ -z "$tools_source" ] && [[ $ENTITY == "KoreBuildToolsSource" ]]; then tools_source=$CONTENT; fi - done < "$config_file" -fi - -[ -z "$channel" ] && channel='dev' -[ -z "$tools_source" ] && tools_source='https://aspnetcore.blob.core.windows.net/buildtools' - -get_korebuild -install_tools "$tools_source" "$DOTNET_HOME" -invoke_repository_build "$repo_path" "$@" +# Call "sync" between "chmod" and execution to prevent "text file busy" error in Docker (aufs) +chmod +x "$DIR/run.sh"; sync +"$DIR/run.sh" default-build "$@" diff --git a/run.cmd b/run.cmd new file mode 100644 index 0000000000..d52d5c7e68 --- /dev/null +++ b/run.cmd @@ -0,0 +1,2 @@ +@ECHO OFF +PowerShell -NoProfile -NoLogo -ExecutionPolicy unrestricted -Command "[System.Threading.Thread]::CurrentThread.CurrentCulture = ''; [System.Threading.Thread]::CurrentThread.CurrentUICulture = '';& '%~dp0run.ps1' %*; exit $LASTEXITCODE" diff --git a/build.ps1 b/run.ps1 similarity index 73% rename from build.ps1 rename to run.ps1 index d5eb4d5cf2..49c2899856 100644 --- a/build.ps1 +++ b/run.ps1 @@ -3,10 +3,13 @@ <# .SYNOPSIS -Build this repository +Executes KoreBuild commands. .DESCRIPTION -Downloads korebuild if required. Then builds the repository. +Downloads korebuild if required. Then executes the KoreBuild command. To see available commands, execute with `-Command help`. + +.PARAMETER Command +The KoreBuild command to run. .PARAMETER Path The folder to build. Defaults to the folder containing this script. @@ -24,31 +27,32 @@ The base url where build tools can be downloaded. Overrides the value from the c Updates KoreBuild to the latest version even if a lock file is present. .PARAMETER ConfigFile -The path to the configuration file that stores values. Defaults to version.xml. +The path to the configuration file that stores values. Defaults to korebuild.json. -.PARAMETER MSBuildArgs -Arguments to be passed to MSBuild +.PARAMETER Arguments +Arguments to be passed to the command .NOTES This function will create a file $PSScriptRoot/korebuild-lock.txt. This lock file can be committed to source, but does not have to be. When the lockfile is not present, KoreBuild will create one using latest available version from $Channel. -The $ConfigFile is expected to be an XML file. It is optional, and the configuration values in it are optional as well. +The $ConfigFile is expected to be an JSON file. It is optional, and the configuration values in it are optional as well. Any options set +in the file are overridden by command line parameters. .EXAMPLE Example config file: -```xml - - - - dev - https://aspnetcore.blob.core.windows.net/buildtools - - +```json +{ + "$schema": "https://raw.githubusercontent.com/aspnet/BuildTools/dev/tools/korebuild.schema.json", + "channel": "dev", + "toolsSource": "https://aspnetcore.blob.core.windows.net/buildtools" +} ``` #> [CmdletBinding(PositionalBinding = $false)] param( + [Parameter(Mandatory=$true, Position = 0)] + [string]$Command, [string]$Path = $PSScriptRoot, [Alias('c')] [string]$Channel, @@ -58,9 +62,9 @@ param( [string]$ToolsSource, [Alias('u')] [switch]$Update, - [string]$ConfigFile = (Join-Path $PSScriptRoot 'version.xml'), + [string]$ConfigFile, [Parameter(ValueFromRemainingArguments = $true)] - [string[]]$MSBuildArgs + [string[]]$Arguments ) Set-StrictMode -Version 2 @@ -147,10 +151,20 @@ function Get-RemoteFile([string]$RemotePath, [string]$LocalPath) { # Load configuration or set defaults +$Path = Resolve-Path $Path +if (!$ConfigFile) { $ConfigFile = Join-Path $Path 'korebuild.json' } + if (Test-Path $ConfigFile) { - [xml] $config = Get-Content $ConfigFile - if (!($Channel)) { [string] $Channel = Select-Xml -Xml $config -XPath '/Project/PropertyGroup/KoreBuildChannel' } - if (!($ToolsSource)) { [string] $ToolsSource = Select-Xml -Xml $config -XPath '/Project/PropertyGroup/KoreBuildToolsSource' } + try { + $config = Get-Content -Raw -Encoding UTF8 -Path $ConfigFile | ConvertFrom-Json + if ($config) { + if (!($Channel) -and (Get-Member -Name 'channel' -InputObject $config)) { [string] $Channel = $config.channel } + if (!($ToolsSource) -and (Get-Member -Name 'toolsSource' -InputObject $config)) { [string] $ToolsSource = $config.toolsSource} + } + } catch { + Write-Warning "$ConfigFile could not be read. Its settings will be ignored." + Write-Warning $Error[0] + } } if (!$DotNetHome) { @@ -169,8 +183,8 @@ $korebuildPath = Get-KoreBuild Import-Module -Force -Scope Local (Join-Path $korebuildPath 'KoreBuild.psd1') try { - Install-Tools $ToolsSource $DotNetHome - Invoke-RepositoryBuild $Path @MSBuildArgs + Set-KoreBuildSettings -ToolsSource $ToolsSource -DotNetHome $DotNetHome -RepoPath $Path -ConfigFile $ConfigFile + Invoke-KoreBuildCommand $Command @Arguments } finally { Remove-Module 'KoreBuild' -ErrorAction Ignore diff --git a/run.sh b/run.sh new file mode 100755 index 0000000000..c278423acc --- /dev/null +++ b/run.sh @@ -0,0 +1,223 @@ +#!/usr/bin/env bash + +set -euo pipefail + +# +# variables +# + +RESET="\033[0m" +RED="\033[0;31m" +YELLOW="\033[0;33m" +MAGENTA="\033[0;95m" +DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" +[ -z "${DOTNET_HOME:-}" ] && DOTNET_HOME="$HOME/.dotnet" +verbose=false +update=false +repo_path="$DIR" +channel='' +tools_source='' + +# +# Functions +# +__usage() { + echo "Usage: $(basename "${BASH_SOURCE[0]}") command [options] [[--] ...]" + echo "" + echo "Arguments:" + echo " command The command to be run." + echo " ... Arguments passed to the command. Variable number of arguments allowed." + echo "" + echo "Options:" + echo " --verbose Show verbose output." + echo " -c|--channel The channel of KoreBuild to download. Overrides the value from the config file.." + echo " --config-file The path to the configuration file that stores values. Defaults to korebuild.json." + echo " -d|--dotnet-home The directory where .NET Core tools will be stored. Defaults to '\$DOTNET_HOME' or '\$HOME/.dotnet." + echo " --path The directory to build. Defaults to the directory containing the script." + echo " -s|--tools-source|-ToolsSource The base url where build tools can be downloaded. Overrides the value from the config file." + echo " -u|--update Update to the latest KoreBuild even if the lock file is present." + echo "" + echo "Description:" + echo " This function will create a file \$DIR/korebuild-lock.txt. This lock file can be committed to source, but does not have to be." + echo " When the lockfile is not present, KoreBuild will create one using latest available version from \$channel." + + if [[ "${1:-}" != '--no-exit' ]]; then + exit 2 + fi +} + +get_korebuild() { + local version + local lock_file="$repo_path/korebuild-lock.txt" + if [ ! -f "$lock_file" ] || [ "$update" = true ]; then + __get_remote_file "$tools_source/korebuild/channels/$channel/latest.txt" "$lock_file" + fi + version="$(grep 'version:*' -m 1 "$lock_file")" + if [[ "$version" == '' ]]; then + __error "Failed to parse version from $lock_file. Expected a line that begins with 'version:'" + return 1 + fi + version="$(echo "${version#version:}" | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//')" + local korebuild_path="$DOTNET_HOME/buildtools/korebuild/$version" + + { + if [ ! -d "$korebuild_path" ]; then + mkdir -p "$korebuild_path" + local remote_path="$tools_source/korebuild/artifacts/$version/korebuild.$version.zip" + tmpfile="$(mktemp)" + echo -e "${MAGENTA}Downloading KoreBuild ${version}${RESET}" + if __get_remote_file "$remote_path" "$tmpfile"; then + unzip -q -d "$korebuild_path" "$tmpfile" + fi + rm "$tmpfile" || true + fi + + source "$korebuild_path/KoreBuild.sh" + } || { + if [ -d "$korebuild_path" ]; then + echo "Cleaning up after failed installation" + rm -rf "$korebuild_path" || true + fi + return 1 + } +} + +__error() { + echo -e "${RED}error: $*${RESET}" 1>&2 +} + +__warn() { + echo -e "${YELLOW}warning: $*${RESET}" +} + +__machine_has() { + hash "$1" > /dev/null 2>&1 + return $? +} + +__get_remote_file() { + local remote_path=$1 + local local_path=$2 + + if [[ "$remote_path" != 'http'* ]]; then + cp "$remote_path" "$local_path" + return 0 + fi + + local failed=false + if __machine_has wget; then + wget --tries 10 --quiet -O "$local_path" "$remote_path" || failed=true + else + failed=true + fi + + if [ "$failed" = true ] && __machine_has curl; then + failed=false + curl --retry 10 -sSL -f --create-dirs -o "$local_path" "$remote_path" || failed=true + fi + + if [ "$failed" = true ]; then + __error "Download failed: $remote_path" 1>&2 + return 1 + fi +} + +# +# main +# + +command="${1:-}" +shift + +while [[ $# -gt 0 ]]; do + case $1 in + -\?|-h|--help) + __usage --no-exit + exit 0 + ;; + -c|--channel|-Channel) + shift + channel="${1:-}" + [ -z "$channel" ] && __usage + ;; + --config-file|-ConfigFile) + shift + config_file="${1:-}" + [ -z "$config_file" ] && __usage + if [ ! -f "$config_file" ]; then + __error "Invalid value for --config-file. $config_file does not exist." + exit 1 + fi + ;; + -d|--dotnet-home|-DotNetHome) + shift + DOTNET_HOME="${1:-}" + [ -z "$DOTNET_HOME" ] && __usage + ;; + --path|-Path) + shift + repo_path="${1:-}" + [ -z "$repo_path" ] && __usage + ;; + -s|--tools-source|-ToolsSource) + shift + tools_source="${1:-}" + [ -z "$tools_source" ] && __usage + ;; + -u|--update|-Update) + update=true + ;; + --verbose|-Verbose) + verbose=true + ;; + --) + shift + break + ;; + *) + break + ;; + esac + shift +done + +if ! __machine_has unzip; then + __error 'Missing required command: unzip' + exit 1 +fi + +if ! __machine_has curl && ! __machine_has wget; then + __error 'Missing required command. Either wget or curl is required.' + exit 1 +fi + +[ -z "${config_file:-}" ] && config_file="$repo_path/korebuild.json" +if [ -f "$config_file" ]; then + if __machine_has jq ; then + if jq '.' "$config_file" >/dev/null ; then + config_channel="$(jq -r 'select(.channel!=null) | .channel' "$config_file")" + config_tools_source="$(jq -r 'select(.toolsSource!=null) | .toolsSource' "$config_file")" + else + __warn "$config_file is invalid JSON. Its settings will be ignored." + fi + elif __machine_has python ; then + if python -c "import json,codecs;obj=json.load(codecs.open('$config_file', 'r', 'utf-8-sig'))" >/dev/null ; then + config_channel="$(python -c "import json,codecs;obj=json.load(codecs.open('$config_file', 'r', 'utf-8-sig'));print(obj['channel'] if 'channel' in obj else '')")" + config_tools_source="$(python -c "import json,codecs;obj=json.load(codecs.open('$config_file', 'r', 'utf-8-sig'));print(obj['toolsSource'] if 'toolsSource' in obj else '')")" + else + __warn "$config_file is invalid JSON. Its settings will be ignored." + fi + else + __warn 'Missing required command: jq or pyton. Could not parse the JSON file. Its settings will be ignored.' + fi + + [ ! -z "${config_channel:-}" ] && channel="$config_channel" + [ ! -z "${config_tools_source:-}" ] && tools_source="$config_tools_source" +fi + +[ -z "$channel" ] && channel='dev' +[ -z "$tools_source" ] && tools_source='https://aspnetcore.blob.core.windows.net/buildtools' + +get_korebuild +set_korebuildsettings "$tools_source" "$DOTNET_HOME" "$repo_path" "$config_file" +invoke_korebuild_command "$command" "$@" From 743ab4f74e2909a493dd9c89528cf332309d8b01 Mon Sep 17 00:00:00 2001 From: Ryan Brandenburg Date: Mon, 16 Oct 2017 12:47:14 -0700 Subject: [PATCH 233/296] Add RepositoryRoot --- Directory.Build.props | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Directory.Build.props b/Directory.Build.props index 95cb477c45..bec69077d1 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -1,10 +1,11 @@ - + Microsoft ASP.NET Core https://github.com/aspnet/Antiforgery git + $(MSBuildThisFileDirectory) $(MSBuildThisFileDirectory)build\Key.snk true true From df486e54a8fc7e68b75b28d9076b5a9f1c29f49e Mon Sep 17 00:00:00 2001 From: Nate McMaster Date: Thu, 26 Oct 2017 09:30:36 -0700 Subject: [PATCH 234/296] Pin tools and package versions to make builds more repeatable --- .gitignore | 1 - Directory.Build.props | 2 +- Directory.Build.targets | 17 +++--------- NuGet.config | 1 + README.md | 4 +-- build/dependencies.props | 26 +++++++++++++++++++ build/repo.props | 8 +++--- korebuild-lock.txt | 2 ++ korebuild.json | 4 +++ .../Microsoft.AspNetCore.Antiforgery.csproj | 10 +++---- ...crosoft.AspNetCore.Antiforgery.Test.csproj | 20 +++++++------- version.props | 5 ++-- 12 files changed, 62 insertions(+), 38 deletions(-) create mode 100644 build/dependencies.props create mode 100644 korebuild-lock.txt create mode 100644 korebuild.json diff --git a/.gitignore b/.gitignore index a7fdfd773b..6da3c6a3e9 100644 --- a/.gitignore +++ b/.gitignore @@ -38,4 +38,3 @@ node_modules .build/ .testPublish/ global.json -korebuild-lock.txt diff --git a/Directory.Build.props b/Directory.Build.props index bec69077d1..c9fd7d291a 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -13,6 +13,6 @@ - + diff --git a/Directory.Build.targets b/Directory.Build.targets index bc118fd907..e83ff95e39 100644 --- a/Directory.Build.targets +++ b/Directory.Build.targets @@ -1,14 +1,5 @@ - - - - <_BootstrapperFile Condition=" $([MSBuild]::IsOSUnixLike()) ">build.sh - <_BootstrapperFile Condition="! $([MSBuild]::IsOSUnixLike()) ">build.cmd - <_BootstrapperError> - Package references have not been pinned. Run './$(_BootstrapperFile) /t:Pin'. - Also, you can run './$(_BootstrapperFile) /t:Restore' which will pin *and* restore packages. '$(_BootstrapperFile)' can be found in '$(MSBuildThisFileDirectory)'. - - - - - + + + $(MicrosoftNETCoreApp20PackageVersion) + diff --git a/NuGet.config b/NuGet.config index 20060c934e..4e8a1f6de1 100644 --- a/NuGet.config +++ b/NuGet.config @@ -3,6 +3,7 @@ + diff --git a/README.md b/README.md index b0430c7868..692348309d 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,5 @@ Antiforgery -=== +=========== AppVeyor: [![AppVeyor](https://ci.appveyor.com/api/projects/status/17l06rulbn328v4k/branch/dev?svg=true)](https://ci.appveyor.com/project/aspnetci/Antiforgery/branch/dev) @@ -11,4 +11,4 @@ This project is part of ASP.NET Core. You can find documentation and getting sta Samples can be found in [Entropy](https://github.com/aspnet/Entropy). The [MVC](https://github.com/aspnet/Entropy/tree/dev/samples/Antiforgery.MvcWithAuthAndAjax) sample shows how to use Antiforgery in MVC when making AJAX requests. -The [Angular](https://github.com/aspnet/Entropy/tree/dev/samples/Antiforgery.Angular1) sample shows how to use Antiforgery with Angular 1. \ No newline at end of file +The [Angular](https://github.com/aspnet/Entropy/tree/dev/samples/Antiforgery.Angular1) sample shows how to use Antiforgery with Angular 1. diff --git a/build/dependencies.props b/build/dependencies.props new file mode 100644 index 0000000000..203f4c839f --- /dev/null +++ b/build/dependencies.props @@ -0,0 +1,26 @@ + + + $(MSBuildAllProjects);$(MSBuildThisFileFullPath) + + + 2.1.0-preview1-15541 + 2.1.0-preview1-27430 + 2.1.0-preview1-27430 + 2.1.0-preview1-27430 + 2.1.0-preview1-27430 + 2.1.0-preview1-27430 + 2.1.0-preview1-27430 + 2.1.0-preview1-27430 + 2.1.0-preview1-27430 + 2.1.0-preview1-27430 + 2.1.0-preview1-27430 + 2.1.0-preview1-27430 + 2.0.0 + 15.3.0 + 4.7.49 + 2.0.0 + 2.3.0 + 2.3.0 + + + diff --git a/build/repo.props b/build/repo.props index 13fe1c296a..4bcc41619b 100644 --- a/build/repo.props +++ b/build/repo.props @@ -1,6 +1,6 @@  - - - - + + Internal.AspNetCore.Universe.Lineup + https://dotnet.myget.org/F/aspnetcore-ci-dev/api/v3/index.json + diff --git a/korebuild-lock.txt b/korebuild-lock.txt new file mode 100644 index 0000000000..5dfe0a2e0d --- /dev/null +++ b/korebuild-lock.txt @@ -0,0 +1,2 @@ +version:2.1.0-preview1-15541 +commithash:0f388d759de1c87fe58383bc9eb1020228885d4d diff --git a/korebuild.json b/korebuild.json new file mode 100644 index 0000000000..bd5d51a51b --- /dev/null +++ b/korebuild.json @@ -0,0 +1,4 @@ +{ + "$schema": "https://raw.githubusercontent.com/aspnet/BuildTools/dev/tools/korebuild.schema.json", + "channel": "dev" +} diff --git a/src/Microsoft.AspNetCore.Antiforgery/Microsoft.AspNetCore.Antiforgery.csproj b/src/Microsoft.AspNetCore.Antiforgery/Microsoft.AspNetCore.Antiforgery.csproj index 051809e5de..e196bf7f56 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/Microsoft.AspNetCore.Antiforgery.csproj +++ b/src/Microsoft.AspNetCore.Antiforgery/Microsoft.AspNetCore.Antiforgery.csproj @@ -9,11 +9,11 @@ - - - - - + + + + + diff --git a/test/Microsoft.AspNetCore.Antiforgery.Test/Microsoft.AspNetCore.Antiforgery.Test.csproj b/test/Microsoft.AspNetCore.Antiforgery.Test/Microsoft.AspNetCore.Antiforgery.Test.csproj index f6a72152bb..3fd4c8ec75 100644 --- a/test/Microsoft.AspNetCore.Antiforgery.Test/Microsoft.AspNetCore.Antiforgery.Test.csproj +++ b/test/Microsoft.AspNetCore.Antiforgery.Test/Microsoft.AspNetCore.Antiforgery.Test.csproj @@ -10,16 +10,16 @@ - - - - - - - - - - + + + + + + + + + + diff --git a/version.props b/version.props index cf1954f5c5..e5fd0676de 100644 --- a/version.props +++ b/version.props @@ -1,8 +1,9 @@ - 2.1.0 preview1 - $(VersionSuffix)-$(BuildNumber) + $(VersionPrefix) + $(VersionPrefix)-$(VersionSuffix)-final + $(VersionSuffix)-$(BuildNumber) From 521b9bdd5e43f7beb0650341d90d94ab312d3113 Mon Sep 17 00:00:00 2001 From: Nate McMaster Date: Thu, 26 Oct 2017 09:37:58 -0700 Subject: [PATCH 235/296] Add missing import --- Directory.Build.props | 1 + 1 file changed, 1 insertion(+) diff --git a/Directory.Build.props b/Directory.Build.props index c9fd7d291a..5debe76ecc 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -1,5 +1,6 @@ + Microsoft ASP.NET Core From e1884586775c85e27f1b5f2dcad80ba1d84b2f21 Mon Sep 17 00:00:00 2001 From: Nate McMaster Date: Tue, 31 Oct 2017 14:23:13 -0700 Subject: [PATCH 236/296] Upgrade build tools to 2.1.0-preview1-15549 and aspnetcore to 2.1.0-preview1-27475 [auto-updated: dependencies] [auto-updated: buildtools] --- build/dependencies.props | 25 ++++++++++++------------- korebuild-lock.txt | 4 ++-- version.props | 1 + 3 files changed, 15 insertions(+), 15 deletions(-) diff --git a/build/dependencies.props b/build/dependencies.props index 203f4c839f..5fa9cd8a58 100644 --- a/build/dependencies.props +++ b/build/dependencies.props @@ -3,22 +3,21 @@ $(MSBuildAllProjects);$(MSBuildThisFileFullPath) - 2.1.0-preview1-15541 - 2.1.0-preview1-27430 - 2.1.0-preview1-27430 - 2.1.0-preview1-27430 - 2.1.0-preview1-27430 - 2.1.0-preview1-27430 - 2.1.0-preview1-27430 - 2.1.0-preview1-27430 - 2.1.0-preview1-27430 - 2.1.0-preview1-27430 - 2.1.0-preview1-27430 - 2.1.0-preview1-27430 + 2.1.0-preview1-15549 + 2.1.0-preview1-27475 + 2.1.0-preview1-27475 + 2.1.0-preview1-27475 + 2.1.0-preview1-27475 + 2.1.0-preview1-27475 + 2.1.0-preview1-27475 + 2.1.0-preview1-27475 + 2.1.0-preview1-27475 + 2.1.0-preview1-27475 + 2.1.0-preview1-27475 + 2.1.0-preview1-27475 2.0.0 15.3.0 4.7.49 - 2.0.0 2.3.0 2.3.0 diff --git a/korebuild-lock.txt b/korebuild-lock.txt index 5dfe0a2e0d..45463cc71e 100644 --- a/korebuild-lock.txt +++ b/korebuild-lock.txt @@ -1,2 +1,2 @@ -version:2.1.0-preview1-15541 -commithash:0f388d759de1c87fe58383bc9eb1020228885d4d +version:2.1.0-preview1-15549 +commithash:f570e08585fec510dd60cd4bfe8795388b757a95 diff --git a/version.props b/version.props index e5fd0676de..5c4a7c32d1 100644 --- a/version.props +++ b/version.props @@ -4,6 +4,7 @@ preview1 $(VersionPrefix) $(VersionPrefix)-$(VersionSuffix)-final + t000 $(VersionSuffix)-$(BuildNumber) From 9edeb74ce1ebc46ff85c1e37ec1bf4c0baaaac37 Mon Sep 17 00:00:00 2001 From: Pranav K Date: Fri, 10 Nov 2017 16:51:46 -0800 Subject: [PATCH 237/296] Target netcoreapp2.1 in tests and samples --- Directory.Build.props | 4 ++++ korebuild-lock.txt | 4 ++-- test/Directory.Build.props | 10 ++++++++++ .../Microsoft.AspNetCore.Antiforgery.Test.csproj | 3 +-- 4 files changed, 17 insertions(+), 4 deletions(-) create mode 100644 test/Directory.Build.props diff --git a/Directory.Build.props b/Directory.Build.props index 5debe76ecc..b749378351 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -1,4 +1,8 @@ + + diff --git a/korebuild-lock.txt b/korebuild-lock.txt index 45463cc71e..07a4d73a83 100644 --- a/korebuild-lock.txt +++ b/korebuild-lock.txt @@ -1,2 +1,2 @@ -version:2.1.0-preview1-15549 -commithash:f570e08585fec510dd60cd4bfe8795388b757a95 +version:2.1.0-preview1-15564 +commithash:1f3f14382764e06b7e691e5ee89d12a280249284 diff --git a/test/Directory.Build.props b/test/Directory.Build.props new file mode 100644 index 0000000000..eb4ed371f3 --- /dev/null +++ b/test/Directory.Build.props @@ -0,0 +1,10 @@ + + + + + netcoreapp2.1 + $(DeveloperBuildTestTfms) + netcoreapp2.1;netcoreapp2.0 + $(StandardTestTfms);net461 + + \ No newline at end of file diff --git a/test/Microsoft.AspNetCore.Antiforgery.Test/Microsoft.AspNetCore.Antiforgery.Test.csproj b/test/Microsoft.AspNetCore.Antiforgery.Test/Microsoft.AspNetCore.Antiforgery.Test.csproj index 3fd4c8ec75..6b82710c8a 100644 --- a/test/Microsoft.AspNetCore.Antiforgery.Test/Microsoft.AspNetCore.Antiforgery.Test.csproj +++ b/test/Microsoft.AspNetCore.Antiforgery.Test/Microsoft.AspNetCore.Antiforgery.Test.csproj @@ -1,8 +1,7 @@  - netcoreapp2.0;net461 - netcoreapp2.0 + $(StandardTestTfms) From 83c6a1187c92dff752c0fd1be8f6c1c01f80dc7f Mon Sep 17 00:00:00 2001 From: Pranav K Date: Fri, 17 Nov 2017 13:00:24 -0800 Subject: [PATCH 238/296] Use MicrosoftNETCoreApp21PackageVersion to determine the runtime framework in netcoreapp2.1 --- Directory.Build.targets | 1 + build/dependencies.props | 3 ++- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/Directory.Build.targets b/Directory.Build.targets index e83ff95e39..894b1d0cf8 100644 --- a/Directory.Build.targets +++ b/Directory.Build.targets @@ -1,5 +1,6 @@  $(MicrosoftNETCoreApp20PackageVersion) + $(MicrosoftNETCoreApp21PackageVersion) diff --git a/build/dependencies.props b/build/dependencies.props index 5fa9cd8a58..adc3b5b852 100644 --- a/build/dependencies.props +++ b/build/dependencies.props @@ -1,4 +1,4 @@ - + $(MSBuildAllProjects);$(MSBuildThisFileFullPath) @@ -16,6 +16,7 @@ 2.1.0-preview1-27475 2.1.0-preview1-27475 2.0.0 + 2.1.0-preview1-25907-02 15.3.0 4.7.49 2.3.0 From 181c7faa120fb467500b987bb4a900e0a6df781b Mon Sep 17 00:00:00 2001 From: Nate McMaster Date: Mon, 20 Nov 2017 12:15:36 -0800 Subject: [PATCH 239/296] Use MSBuild to set NuGet feeds instead of NuGet.config --- Directory.Build.props | 3 ++- NuGet.config | 4 +--- build/sources.props | 16 ++++++++++++++++ 3 files changed, 19 insertions(+), 4 deletions(-) create mode 100644 build/sources.props diff --git a/Directory.Build.props b/Directory.Build.props index b749378351..1008441f18 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -1,10 +1,11 @@ - + + Microsoft ASP.NET Core diff --git a/NuGet.config b/NuGet.config index 4e8a1f6de1..e32bddfd51 100644 --- a/NuGet.config +++ b/NuGet.config @@ -2,8 +2,6 @@ - - - + diff --git a/build/sources.props b/build/sources.props new file mode 100644 index 0000000000..c03f3ddb60 --- /dev/null +++ b/build/sources.props @@ -0,0 +1,16 @@ + + + + + $(DotNetRestoreSources) + + $(RestoreSources); + https://dotnet.myget.org/F/aspnetcore-ci-dev/api/v3/index.json; + https://dotnet.myget.org/F/aspnetcore-tools/api/v3/index.json; + + + $(RestoreSources); + https://api.nuget.org/v3/index.json; + + + From 77485a2d23be1cbf0758246bd457039d5016fcf6 Mon Sep 17 00:00:00 2001 From: Pranav K Date: Tue, 21 Nov 2017 16:26:51 -0800 Subject: [PATCH 240/296] Replace aspnetcore-ci-dev feed with aspnetcore-dev --- build/dependencies.props | 26 +++++++++++++------------- build/repo.props | 2 +- build/sources.props | 2 +- korebuild-lock.txt | 4 ++-- 4 files changed, 17 insertions(+), 17 deletions(-) diff --git a/build/dependencies.props b/build/dependencies.props index adc3b5b852..937860fa30 100644 --- a/build/dependencies.props +++ b/build/dependencies.props @@ -1,20 +1,20 @@ - + $(MSBuildAllProjects);$(MSBuildThisFileFullPath) - 2.1.0-preview1-15549 - 2.1.0-preview1-27475 - 2.1.0-preview1-27475 - 2.1.0-preview1-27475 - 2.1.0-preview1-27475 - 2.1.0-preview1-27475 - 2.1.0-preview1-27475 - 2.1.0-preview1-27475 - 2.1.0-preview1-27475 - 2.1.0-preview1-27475 - 2.1.0-preview1-27475 - 2.1.0-preview1-27475 + 2.1.0-preview1-15576 + 2.1.0-preview1-27644 + 2.1.0-preview1-27644 + 2.1.0-preview1-27644 + 2.1.0-preview1-27644 + 2.1.0-preview1-27644 + 2.1.0-preview1-27644 + 2.1.0-preview1-27644 + 2.1.0-preview1-27644 + 2.1.0-preview1-27644 + 2.1.0-preview1-27644 + 2.1.0-preview1-27644 2.0.0 2.1.0-preview1-25907-02 15.3.0 diff --git a/build/repo.props b/build/repo.props index 4bcc41619b..e0adcf1e80 100644 --- a/build/repo.props +++ b/build/repo.props @@ -1,6 +1,6 @@  Internal.AspNetCore.Universe.Lineup - https://dotnet.myget.org/F/aspnetcore-ci-dev/api/v3/index.json + https://dotnet.myget.org/F/aspnetcore-dev/api/v3/index.json diff --git a/build/sources.props b/build/sources.props index c03f3ddb60..9feff29d09 100644 --- a/build/sources.props +++ b/build/sources.props @@ -5,7 +5,7 @@ $(DotNetRestoreSources) $(RestoreSources); - https://dotnet.myget.org/F/aspnetcore-ci-dev/api/v3/index.json; + https://dotnet.myget.org/F/aspnetcore-dev/api/v3/index.json; https://dotnet.myget.org/F/aspnetcore-tools/api/v3/index.json; diff --git a/korebuild-lock.txt b/korebuild-lock.txt index 07a4d73a83..1a99066b7c 100644 --- a/korebuild-lock.txt +++ b/korebuild-lock.txt @@ -1,2 +1,2 @@ -version:2.1.0-preview1-15564 -commithash:1f3f14382764e06b7e691e5ee89d12a280249284 +version:2.1.0-preview1-15576 +commithash:2f3856d2ba4f659fcb9253215b83946a06794a27 From eee21844551d232316177d922850a6649de9ba04 Mon Sep 17 00:00:00 2001 From: Pranav K Date: Wed, 29 Nov 2017 13:46:18 -0800 Subject: [PATCH 241/296] Specify runtime versions to install --- build/repo.props | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/build/repo.props b/build/repo.props index e0adcf1e80..ebbe645751 100644 --- a/build/repo.props +++ b/build/repo.props @@ -1,6 +1,13 @@  + + Internal.AspNetCore.Universe.Lineup https://dotnet.myget.org/F/aspnetcore-dev/api/v3/index.json + + + + + From e30d20bbbcc60702d8f88dbfb687a2abe2040817 Mon Sep 17 00:00:00 2001 From: Ryan Brandenburg Date: Fri, 1 Dec 2017 10:20:23 -0800 Subject: [PATCH 242/296] Update bootstrappers --- run.ps1 | 17 +++++++++++------ run.sh | 30 +++++++++++++++++++----------- 2 files changed, 30 insertions(+), 17 deletions(-) diff --git a/run.ps1 b/run.ps1 index 49c2899856..27dcf848f8 100644 --- a/run.ps1 +++ b/run.ps1 @@ -29,6 +29,9 @@ Updates KoreBuild to the latest version even if a lock file is present. .PARAMETER ConfigFile The path to the configuration file that stores values. Defaults to korebuild.json. +.PARAMETER ToolsSourceSuffix +The Suffix to append to the end of the ToolsSource. Useful for query strings in blob stores. + .PARAMETER Arguments Arguments to be passed to the command @@ -51,7 +54,7 @@ Example config file: #> [CmdletBinding(PositionalBinding = $false)] param( - [Parameter(Mandatory=$true, Position = 0)] + [Parameter(Mandatory = $true, Position = 0)] [string]$Command, [string]$Path = $PSScriptRoot, [Alias('c')] @@ -63,6 +66,7 @@ param( [Alias('u')] [switch]$Update, [string]$ConfigFile, + [string]$ToolsSourceSuffix, [Parameter(ValueFromRemainingArguments = $true)] [string[]]$Arguments ) @@ -79,7 +83,7 @@ function Get-KoreBuild { $lockFile = Join-Path $Path 'korebuild-lock.txt' if (!(Test-Path $lockFile) -or $Update) { - Get-RemoteFile "$ToolsSource/korebuild/channels/$Channel/latest.txt" $lockFile + Get-RemoteFile "$ToolsSource/korebuild/channels/$Channel/latest.txt" $lockFile $ToolsSourceSuffix } $version = Get-Content $lockFile | Where-Object { $_ -like 'version:*' } | Select-Object -first 1 @@ -96,7 +100,7 @@ function Get-KoreBuild { try { $tmpfile = Join-Path ([IO.Path]::GetTempPath()) "KoreBuild-$([guid]::NewGuid()).zip" - Get-RemoteFile $remotePath $tmpfile + Get-RemoteFile $remotePath $tmpfile $ToolsSourceSuffix if (Get-Command -Name 'Expand-Archive' -ErrorAction Ignore) { # Use built-in commands where possible as they are cross-plat compatible Expand-Archive -Path $tmpfile -DestinationPath $korebuildPath @@ -124,7 +128,7 @@ function Join-Paths([string]$path, [string[]]$childPaths) { return $path } -function Get-RemoteFile([string]$RemotePath, [string]$LocalPath) { +function Get-RemoteFile([string]$RemotePath, [string]$LocalPath, [string]$RemoteSuffix) { if ($RemotePath -notlike 'http*') { Copy-Item $RemotePath $LocalPath return @@ -134,7 +138,7 @@ function Get-RemoteFile([string]$RemotePath, [string]$LocalPath) { while ($retries -gt 0) { $retries -= 1 try { - Invoke-WebRequest -UseBasicParsing -Uri $RemotePath -OutFile $LocalPath + Invoke-WebRequest -UseBasicParsing -Uri $($RemotePath + $RemoteSuffix) -OutFile $LocalPath return } catch { @@ -161,7 +165,8 @@ if (Test-Path $ConfigFile) { if (!($Channel) -and (Get-Member -Name 'channel' -InputObject $config)) { [string] $Channel = $config.channel } if (!($ToolsSource) -and (Get-Member -Name 'toolsSource' -InputObject $config)) { [string] $ToolsSource = $config.toolsSource} } - } catch { + } + catch { Write-Warning "$ConfigFile could not be read. Its settings will be ignored." Write-Warning $Error[0] } diff --git a/run.sh b/run.sh index c278423acc..834961fc3a 100755 --- a/run.sh +++ b/run.sh @@ -17,6 +17,7 @@ update=false repo_path="$DIR" channel='' tools_source='' +tools_source_suffix='' # # Functions @@ -29,13 +30,14 @@ __usage() { echo " ... Arguments passed to the command. Variable number of arguments allowed." echo "" echo "Options:" - echo " --verbose Show verbose output." - echo " -c|--channel The channel of KoreBuild to download. Overrides the value from the config file.." - echo " --config-file The path to the configuration file that stores values. Defaults to korebuild.json." - echo " -d|--dotnet-home The directory where .NET Core tools will be stored. Defaults to '\$DOTNET_HOME' or '\$HOME/.dotnet." - echo " --path The directory to build. Defaults to the directory containing the script." - echo " -s|--tools-source|-ToolsSource The base url where build tools can be downloaded. Overrides the value from the config file." - echo " -u|--update Update to the latest KoreBuild even if the lock file is present." + echo " --verbose Show verbose output." + echo " -c|--channel The channel of KoreBuild to download. Overrides the value from the config file.." + echo " --config-file The path to the configuration file that stores values. Defaults to korebuild.json." + echo " -d|--dotnet-home The directory where .NET Core tools will be stored. Defaults to '\$DOTNET_HOME' or '\$HOME/.dotnet." + echo " --path The directory to build. Defaults to the directory containing the script." + echo " -s|--tools-source|-ToolsSource The base url where build tools can be downloaded. Overrides the value from the config file." + echo " --tools-source-suffix|-ToolsSourceSuffix The suffix to append to tools-source. Useful for query strings." + echo " -u|--update Update to the latest KoreBuild even if the lock file is present." echo "" echo "Description:" echo " This function will create a file \$DIR/korebuild-lock.txt. This lock file can be committed to source, but does not have to be." @@ -50,7 +52,7 @@ get_korebuild() { local version local lock_file="$repo_path/korebuild-lock.txt" if [ ! -f "$lock_file" ] || [ "$update" = true ]; then - __get_remote_file "$tools_source/korebuild/channels/$channel/latest.txt" "$lock_file" + __get_remote_file "$tools_source/korebuild/channels/$channel/latest.txt" "$lock_file" "$tools_source_suffix" fi version="$(grep 'version:*' -m 1 "$lock_file")" if [[ "$version" == '' ]]; then @@ -66,7 +68,7 @@ get_korebuild() { local remote_path="$tools_source/korebuild/artifacts/$version/korebuild.$version.zip" tmpfile="$(mktemp)" echo -e "${MAGENTA}Downloading KoreBuild ${version}${RESET}" - if __get_remote_file "$remote_path" "$tmpfile"; then + if __get_remote_file "$remote_path" "$tmpfile" "$tools_source_suffix"; then unzip -q -d "$korebuild_path" "$tmpfile" fi rm "$tmpfile" || true @@ -98,6 +100,7 @@ __machine_has() { __get_remote_file() { local remote_path=$1 local local_path=$2 + local remote_path_suffix=$3 if [[ "$remote_path" != 'http'* ]]; then cp "$remote_path" "$local_path" @@ -106,14 +109,14 @@ __get_remote_file() { local failed=false if __machine_has wget; then - wget --tries 10 --quiet -O "$local_path" "$remote_path" || failed=true + wget --tries 10 --quiet -O "$local_path" "${remote_path}${remote_path_suffix}" || failed=true else failed=true fi if [ "$failed" = true ] && __machine_has curl; then failed=false - curl --retry 10 -sSL -f --create-dirs -o "$local_path" "$remote_path" || failed=true + curl --retry 10 -sSL -f --create-dirs -o "$local_path" "${remote_path}${remote_path_suffix}" || failed=true fi if [ "$failed" = true ]; then @@ -164,6 +167,11 @@ while [[ $# -gt 0 ]]; do tools_source="${1:-}" [ -z "$tools_source" ] && __usage ;; + --tools-source-suffix|-ToolsSourceSuffix) + shift + tools_source_suffix="${1:-}" + [ -z "$tools_source_suffix" ] && __usage + ;; -u|--update|-Update) update=true ;; From d4486c2bf1303e6f05354648a66645bdec347cc1 Mon Sep 17 00:00:00 2001 From: "ASP.NET CI" Date: Sun, 10 Dec 2017 12:05:11 -0800 Subject: [PATCH 243/296] Update dependencies.props [auto-updated: dependencies] --- build/dependencies.props | 30 +++++++++++++++--------------- korebuild-lock.txt | 4 ++-- 2 files changed, 17 insertions(+), 17 deletions(-) diff --git a/build/dependencies.props b/build/dependencies.props index 937860fa30..2c859af972 100644 --- a/build/dependencies.props +++ b/build/dependencies.props @@ -3,24 +3,24 @@ $(MSBuildAllProjects);$(MSBuildThisFileFullPath) - 2.1.0-preview1-15576 - 2.1.0-preview1-27644 - 2.1.0-preview1-27644 - 2.1.0-preview1-27644 - 2.1.0-preview1-27644 - 2.1.0-preview1-27644 - 2.1.0-preview1-27644 - 2.1.0-preview1-27644 - 2.1.0-preview1-27644 - 2.1.0-preview1-27644 - 2.1.0-preview1-27644 - 2.1.0-preview1-27644 + 2.1.0-preview1-15618 + 2.1.0-preview1-27773 + 2.1.0-preview1-27773 + 2.1.0-preview1-27773 + 2.1.0-preview1-27773 + 2.1.0-preview1-27773 + 2.1.0-preview1-27773 + 2.1.0-preview1-27773 + 2.1.0-preview1-27773 + 2.1.0-preview1-27773 + 2.1.0-preview1-27773 + 2.1.0-preview1-27773 2.0.0 - 2.1.0-preview1-25907-02 + 2.1.0-preview1-25915-01 15.3.0 4.7.49 - 2.3.0 - 2.3.0 + 2.3.1 + 2.3.1 diff --git a/korebuild-lock.txt b/korebuild-lock.txt index 1a99066b7c..e7cce93009 100644 --- a/korebuild-lock.txt +++ b/korebuild-lock.txt @@ -1,2 +1,2 @@ -version:2.1.0-preview1-15576 -commithash:2f3856d2ba4f659fcb9253215b83946a06794a27 +version:2.1.0-preview1-15618 +commithash:00ce1383114015fe89b221146036e59e6bc11219 From 62fe8b117289f4fa409c576c823888b61c152ad9 Mon Sep 17 00:00:00 2001 From: "ASP.NET CI" Date: Wed, 13 Dec 2017 20:11:20 +0000 Subject: [PATCH 244/296] Update dependencies.props [auto-updated: dependencies] --- build/dependencies.props | 26 +++++++++++++------------- korebuild-lock.txt | 4 ++-- 2 files changed, 15 insertions(+), 15 deletions(-) diff --git a/build/dependencies.props b/build/dependencies.props index 2c859af972..a1bb064aeb 100644 --- a/build/dependencies.props +++ b/build/dependencies.props @@ -3,20 +3,20 @@ $(MSBuildAllProjects);$(MSBuildThisFileFullPath) - 2.1.0-preview1-15618 - 2.1.0-preview1-27773 - 2.1.0-preview1-27773 - 2.1.0-preview1-27773 - 2.1.0-preview1-27773 - 2.1.0-preview1-27773 - 2.1.0-preview1-27773 - 2.1.0-preview1-27773 - 2.1.0-preview1-27773 - 2.1.0-preview1-27773 - 2.1.0-preview1-27773 - 2.1.0-preview1-27773 + 2.1.0-preview1-15626 + 2.1.0-preview1-27807 + 2.1.0-preview1-27807 + 2.1.0-preview1-27807 + 2.1.0-preview1-27807 + 2.1.0-preview1-27807 + 2.1.0-preview1-27807 + 2.1.0-preview1-27807 + 2.1.0-preview1-27807 + 2.1.0-preview1-27807 + 2.1.0-preview1-27807 + 2.1.0-preview1-27807 2.0.0 - 2.1.0-preview1-25915-01 + 2.1.0-preview1-26008-01 15.3.0 4.7.49 2.3.1 diff --git a/korebuild-lock.txt b/korebuild-lock.txt index e7cce93009..8d52a6128c 100644 --- a/korebuild-lock.txt +++ b/korebuild-lock.txt @@ -1,2 +1,2 @@ -version:2.1.0-preview1-15618 -commithash:00ce1383114015fe89b221146036e59e6bc11219 +version:2.1.0-preview1-15626 +commithash:fd6410e9c90c428bc01238372303ad09cb9ec889 From f1386f2789323e470ebf00268a928d7b25a40124 Mon Sep 17 00:00:00 2001 From: "ASP.NET CI" Date: Mon, 18 Dec 2017 16:25:06 -0800 Subject: [PATCH 245/296] Update dependencies.props [auto-updated: dependencies] --- build/dependencies.props | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/build/dependencies.props b/build/dependencies.props index a1bb064aeb..3afbd3b04b 100644 --- a/build/dependencies.props +++ b/build/dependencies.props @@ -4,19 +4,19 @@ 2.1.0-preview1-15626 - 2.1.0-preview1-27807 - 2.1.0-preview1-27807 - 2.1.0-preview1-27807 - 2.1.0-preview1-27807 - 2.1.0-preview1-27807 - 2.1.0-preview1-27807 - 2.1.0-preview1-27807 - 2.1.0-preview1-27807 - 2.1.0-preview1-27807 - 2.1.0-preview1-27807 - 2.1.0-preview1-27807 + 2.1.0-preview1-27849 + 2.1.0-preview1-27849 + 2.1.0-preview1-27849 + 2.1.0-preview1-27849 + 2.1.0-preview1-27849 + 2.1.0-preview1-27849 + 2.1.0-preview1-27849 + 2.1.0-preview1-27849 + 2.1.0-preview1-27849 + 2.1.0-preview1-27849 + 2.1.0-preview1-27849 2.0.0 - 2.1.0-preview1-26008-01 + 2.1.0-preview1-26016-05 15.3.0 4.7.49 2.3.1 From b4d67776aff867005a4e6ce04c80ad5772da8606 Mon Sep 17 00:00:00 2001 From: "ASP.NET CI" Date: Sun, 31 Dec 2017 20:25:10 +0000 Subject: [PATCH 246/296] Update dependencies.props [auto-updated: dependencies] --- build/dependencies.props | 24 ++++++++++++------------ korebuild-lock.txt | 4 ++-- 2 files changed, 14 insertions(+), 14 deletions(-) diff --git a/build/dependencies.props b/build/dependencies.props index 3afbd3b04b..ecd5cb81c0 100644 --- a/build/dependencies.props +++ b/build/dependencies.props @@ -3,18 +3,18 @@ $(MSBuildAllProjects);$(MSBuildThisFileFullPath) - 2.1.0-preview1-15626 - 2.1.0-preview1-27849 - 2.1.0-preview1-27849 - 2.1.0-preview1-27849 - 2.1.0-preview1-27849 - 2.1.0-preview1-27849 - 2.1.0-preview1-27849 - 2.1.0-preview1-27849 - 2.1.0-preview1-27849 - 2.1.0-preview1-27849 - 2.1.0-preview1-27849 - 2.1.0-preview1-27849 + 2.1.0-preview1-15651 + 2.1.0-preview1-27942 + 2.1.0-preview1-27942 + 2.1.0-preview1-27942 + 2.1.0-preview1-27942 + 2.1.0-preview1-27942 + 2.1.0-preview1-27942 + 2.1.0-preview1-27942 + 2.1.0-preview1-27942 + 2.1.0-preview1-27942 + 2.1.0-preview1-27942 + 2.1.0-preview1-27942 2.0.0 2.1.0-preview1-26016-05 15.3.0 diff --git a/korebuild-lock.txt b/korebuild-lock.txt index 8d52a6128c..7c2e97aa79 100644 --- a/korebuild-lock.txt +++ b/korebuild-lock.txt @@ -1,2 +1,2 @@ -version:2.1.0-preview1-15626 -commithash:fd6410e9c90c428bc01238372303ad09cb9ec889 +version:2.1.0-preview1-15651 +commithash:ebf2365121c2c6a6a0fbfa9b0f37bb5effc89323 From 393b33ea34f0aa8da26dfd9e9e35d62411292f1f Mon Sep 17 00:00:00 2001 From: Eilon Lipton Date: Tue, 2 Jan 2018 14:26:37 -0800 Subject: [PATCH 247/296] Create ISSUE_TEMPLATE.md --- .github/ISSUE_TEMPLATE.md | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 .github/ISSUE_TEMPLATE.md diff --git a/.github/ISSUE_TEMPLATE.md b/.github/ISSUE_TEMPLATE.md new file mode 100644 index 0000000000..101a084f0a --- /dev/null +++ b/.github/ISSUE_TEMPLATE.md @@ -0,0 +1,3 @@ +THIS ISSUE TRACKER IS CLOSED - please log new issues here: https://github.com/aspnet/Home/issues + +For information about this change, see https://github.com/aspnet/Announcements/issues/283 From 09afaf3e3dd9462f1a115d6f0909e85fbb81f4e2 Mon Sep 17 00:00:00 2001 From: "ASP.NET CI" Date: Thu, 4 Jan 2018 00:31:32 +0000 Subject: [PATCH 248/296] Update dependencies.props [auto-updated: dependencies] --- build/dependencies.props | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/build/dependencies.props b/build/dependencies.props index ecd5cb81c0..6519615656 100644 --- a/build/dependencies.props +++ b/build/dependencies.props @@ -4,17 +4,17 @@ 2.1.0-preview1-15651 - 2.1.0-preview1-27942 - 2.1.0-preview1-27942 - 2.1.0-preview1-27942 - 2.1.0-preview1-27942 - 2.1.0-preview1-27942 - 2.1.0-preview1-27942 - 2.1.0-preview1-27942 - 2.1.0-preview1-27942 - 2.1.0-preview1-27942 - 2.1.0-preview1-27942 - 2.1.0-preview1-27942 + 2.1.0-preview1-27965 + 2.1.0-preview1-27965 + 2.1.0-preview1-27965 + 2.1.0-preview1-27965 + 2.1.0-preview1-27965 + 2.1.0-preview1-27965 + 2.1.0-preview1-27965 + 2.1.0-preview1-27965 + 2.1.0-preview1-27965 + 2.1.0-preview1-27965 + 2.1.0-preview1-27965 2.0.0 2.1.0-preview1-26016-05 15.3.0 From 0401377fe4e0afc2c6ba3a08d4466929870c8c26 Mon Sep 17 00:00:00 2001 From: "ASP.NET CI" Date: Sat, 6 Jan 2018 14:01:27 -0800 Subject: [PATCH 249/296] Update dependencies.props [auto-updated: dependencies] --- korebuild-lock.txt | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/korebuild-lock.txt b/korebuild-lock.txt index 7c2e97aa79..2146d006d7 100644 --- a/korebuild-lock.txt +++ b/korebuild-lock.txt @@ -1,2 +1,2 @@ -version:2.1.0-preview1-15651 -commithash:ebf2365121c2c6a6a0fbfa9b0f37bb5effc89323 +version:2.1.0-preview1-15661 +commithash:c9349d4c8a495d3085d9b879214d80f2f45e2193 From d2c27104ddc1761e303fdfe8c8fb5acef67f2107 Mon Sep 17 00:00:00 2001 From: Kiran Challa Date: Mon, 8 Jan 2018 16:56:03 -0800 Subject: [PATCH 250/296] Throwing AntiforgeryValidationException for failure to deserializing tokens --- .../AntiforgeryValidationException.cs | 13 ++++++++- .../Internal/AntiforgeryLoggerExtensions.cs | 10 +++++++ .../Internal/DefaultAntiforgery.cs | 27 ++++++++++++++++++- .../DefaultAntiforgeryTokenSerializer.cs | 2 +- .../DefaultAntiforgeryTokenSerializerTest.cs | 2 +- 5 files changed, 50 insertions(+), 4 deletions(-) diff --git a/src/Microsoft.AspNetCore.Antiforgery/AntiforgeryValidationException.cs b/src/Microsoft.AspNetCore.Antiforgery/AntiforgeryValidationException.cs index b2fb6e9618..f1ade05d34 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/AntiforgeryValidationException.cs +++ b/src/Microsoft.AspNetCore.Antiforgery/AntiforgeryValidationException.cs @@ -12,12 +12,23 @@ namespace Microsoft.AspNetCore.Antiforgery { /// /// Creates a new instance of with the specified - /// exception . + /// exception message. /// /// The message that describes the error. public AntiforgeryValidationException(string message) : base(message) { } + + /// + /// Creates a new instance of with the specified + /// exception message and inner exception. + /// + /// The message that describes the error. + /// The inner . + public AntiforgeryValidationException(string message, Exception innerException) + : base(message, innerException) + { + } } } diff --git a/src/Microsoft.AspNetCore.Antiforgery/Internal/AntiforgeryLoggerExtensions.cs b/src/Microsoft.AspNetCore.Antiforgery/Internal/AntiforgeryLoggerExtensions.cs index 0c8ef5ccfd..232279e4be 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/Internal/AntiforgeryLoggerExtensions.cs +++ b/src/Microsoft.AspNetCore.Antiforgery/Internal/AntiforgeryLoggerExtensions.cs @@ -8,6 +8,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal { internal static class AntiforgeryLoggerExtensions { + private static readonly Action _failedToDeserialzeTokens; private static readonly Action _validationFailed; private static readonly Action _validated; private static readonly Action _missingCookieToken; @@ -54,6 +55,10 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal "The 'Cache-Control' and 'Pragma' headers have been overridden and set to 'no-cache, no-store' and " + "'no-cache' respectively to prevent caching of this response. Any response that uses antiforgery " + "should not be cached."); + _failedToDeserialzeTokens = LoggerMessage.Define( + LogLevel.Debug, + 9, + "Failed to deserialize antiforgery tokens."); } public static void ValidationFailed(this ILogger logger, string message) @@ -95,5 +100,10 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal { _responseCacheHeadersOverridenToNoCache(logger, null); } + + public static void FailedToDeserialzeTokens(this ILogger logger, Exception exception) + { + _failedToDeserialzeTokens(logger, exception); + } } } diff --git a/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgery.cs b/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgery.cs index ae28906069..24aa3cb7d3 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgery.cs +++ b/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgery.cs @@ -124,7 +124,10 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal // Extract cookie & request tokens AntiforgeryToken deserializedCookieToken; AntiforgeryToken deserializedRequestToken; - DeserializeTokens(httpContext, tokens, out deserializedCookieToken, out deserializedRequestToken); + if (!TryDeserializeTokens(httpContext, tokens, out deserializedCookieToken, out deserializedRequestToken)) + { + return false; + } // Validate string message; @@ -197,6 +200,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal // Extract cookie & request tokens AntiforgeryToken deserializedCookieToken; AntiforgeryToken deserializedRequestToken; + DeserializeTokens( httpContext, antiforgeryTokenSet, @@ -430,6 +434,27 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal _options.HeaderName); } + private bool TryDeserializeTokens( + HttpContext httpContext, + AntiforgeryTokenSet antiforgeryTokenSet, + out AntiforgeryToken cookieToken, + out AntiforgeryToken requestToken) + { + try + { + DeserializeTokens(httpContext, antiforgeryTokenSet, out cookieToken, out requestToken); + return true; + } + catch (AntiforgeryValidationException ex) + { + _logger.FailedToDeserialzeTokens(ex); + + cookieToken = null; + requestToken = null; + return false; + } + } + private void DeserializeTokens( HttpContext httpContext, AntiforgeryTokenSet antiforgeryTokenSet, diff --git a/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgeryTokenSerializer.cs b/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgeryTokenSerializer.cs index 474b2fd7a9..d71f2a2185 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgeryTokenSerializer.cs +++ b/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgeryTokenSerializer.cs @@ -75,7 +75,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal } // if we reached this point, something went wrong deserializing - throw new InvalidOperationException(Resources.AntiforgeryToken_DeserializationFailed, innerException); + throw new AntiforgeryValidationException(Resources.AntiforgeryToken_DeserializationFailed, innerException); } /* The serialized format of the anti-XSRF token is as follows: diff --git a/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTokenSerializerTest.cs b/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTokenSerializerTest.cs index 80280de4f3..88ce09b4e2 100644 --- a/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTokenSerializerTest.cs +++ b/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTokenSerializerTest.cs @@ -51,7 +51,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal var testSerializer = new DefaultAntiforgeryTokenSerializer(_dataProtector.Object, _pool); // Act & assert - var ex = Assert.Throws(() => testSerializer.Deserialize(serializedToken)); + var ex = Assert.Throws(() => testSerializer.Deserialize(serializedToken)); Assert.Equal(@"The antiforgery token could not be decrypted.", ex.Message); } From e5de4e672cbe879d598529c257539b6a7d1a7bf9 Mon Sep 17 00:00:00 2001 From: Kiran Challa Date: Wed, 10 Jan 2018 15:34:48 -0800 Subject: [PATCH 251/296] Marked Antiforgery cookie as essential Related to https://github.com/aspnet/Home/issues/2408 : Determine if the antiforgery cookie is considered essential --- src/Microsoft.AspNetCore.Antiforgery/AntiforgeryOptions.cs | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/src/Microsoft.AspNetCore.Antiforgery/AntiforgeryOptions.cs b/src/Microsoft.AspNetCore.Antiforgery/AntiforgeryOptions.cs index 405905b587..e58f3f73c7 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/AntiforgeryOptions.cs +++ b/src/Microsoft.AspNetCore.Antiforgery/AntiforgeryOptions.cs @@ -21,6 +21,9 @@ namespace Microsoft.AspNetCore.Antiforgery SameSite = SameSiteMode.Strict, HttpOnly = true, + // Check the comment on CookieBuilder for more details + IsEssential = true, + // Some browsers do not allow non-secure endpoints to set cookies with a 'secure' flag or overwrite cookies // whose 'secure' flag is set (http://httpwg.org/http-extensions/draft-ietf-httpbis-cookie-alone.html). // Since mixing secure and non-secure endpoints is a common scenario in applications, we are relaxing the @@ -45,6 +48,10 @@ namespace Microsoft.AspNetCore.Antiforgery /// /// defaults to . /// defaults to true. + /// defaults to true. The cookie used by the antiforgery system + /// is part of a security system that is necessary when using cookie-based authentication. It should be + /// considered required for the application to function. + /// defaults to . /// /// public CookieBuilder Cookie From 6138087de65010552dc5b5a7ffc2663f389cab74 Mon Sep 17 00:00:00 2001 From: Artak Mkrtchyan Date: Mon, 22 Jan 2018 14:50:45 -0800 Subject: [PATCH 252/296] Updated the DefaultAntiforgery to set the the cache headers only if they aren't set yet. --- .../Internal/DefaultAntiforgery.cs | 37 +++++++++++++------ 1 file changed, 26 insertions(+), 11 deletions(-) diff --git a/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgery.cs b/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgery.cs index 24aa3cb7d3..a989ea61de 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgery.cs +++ b/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgery.cs @@ -24,11 +24,11 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal private readonly ILogger _logger; public DefaultAntiforgery( - IOptions antiforgeryOptionsAccessor, - IAntiforgeryTokenGenerator tokenGenerator, - IAntiforgeryTokenSerializer tokenSerializer, - IAntiforgeryTokenStore tokenStore, - ILoggerFactory loggerFactory) + IOptions antiforgeryOptionsAccessor, + IAntiforgeryTokenGenerator tokenGenerator, + IAntiforgeryTokenSerializer tokenSerializer, + IAntiforgeryTokenStore tokenStore, + ILoggerFactory loggerFactory) { _options = antiforgeryOptionsAccessor.Value; _tokenGenerator = tokenGenerator; @@ -374,13 +374,28 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal /// The . protected virtual void SetDoNotCacheHeaders(HttpContext httpContext) { - // Since antifogery token generation is not very obvious to the end users (ex: MVC's form tag generates them - // by default), log a warning to let users know of the change in behavior to any cache headers they might - // have set explicitly. - LogCacheHeaderOverrideWarning(httpContext.Response); + bool cacheHeadersChanged = SetHeaderIfNotSet(httpContext, HeaderNames.CacheControl, "no-cache, no-store"); + cacheHeadersChanged |= SetHeaderIfNotSet(httpContext, HeaderNames.Pragma, "no-cache"); - httpContext.Response.Headers[HeaderNames.CacheControl] = "no-cache, no-store"; - httpContext.Response.Headers[HeaderNames.Pragma] = "no-cache"; + if (cacheHeadersChanged) + { + // Since antifogery token generation is not very obvious to the end users (ex: MVC's form tag generates them + // by default), log a warning to let users know of the change in behavior to any cache headers they might + // have set explicitly. + LogCacheHeaderOverrideWarning(httpContext.Response); + } + } + + private static bool SetHeaderIfNotSet(HttpContext context, string headerName, string value) + { + if (!context.Response.Headers.ContainsKey(headerName)) + { + context.Response.Headers[headerName] = value; + + return true; + } + + return false; } private void LogCacheHeaderOverrideWarning(HttpResponse response) From 77b04e3c82491047449abb2008ecebe8072716c3 Mon Sep 17 00:00:00 2001 From: Artak Mkrtchyan Date: Mon, 22 Jan 2018 14:53:46 -0800 Subject: [PATCH 253/296] Removed redundant spacings --- .../Internal/DefaultAntiforgery.cs | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgery.cs b/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgery.cs index a989ea61de..bc7a3d2646 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgery.cs +++ b/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgery.cs @@ -24,11 +24,11 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal private readonly ILogger _logger; public DefaultAntiforgery( - IOptions antiforgeryOptionsAccessor, - IAntiforgeryTokenGenerator tokenGenerator, - IAntiforgeryTokenSerializer tokenSerializer, - IAntiforgeryTokenStore tokenStore, - ILoggerFactory loggerFactory) + IOptions antiforgeryOptionsAccessor, + IAntiforgeryTokenGenerator tokenGenerator, + IAntiforgeryTokenSerializer tokenSerializer, + IAntiforgeryTokenStore tokenStore, + ILoggerFactory loggerFactory) { _options = antiforgeryOptionsAccessor.Value; _tokenGenerator = tokenGenerator; From 4fa975a416b8402aa82c7267e58b118048ec021a Mon Sep 17 00:00:00 2001 From: Artak Mkrtchyan Date: Mon, 22 Jan 2018 16:40:57 -0800 Subject: [PATCH 254/296] Writing header cache values only when the response hasn't yet started --- .../Internal/DefaultAntiforgery.cs | 33 +++++++------------ 1 file changed, 12 insertions(+), 21 deletions(-) diff --git a/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgery.cs b/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgery.cs index bc7a3d2646..5cc860b593 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgery.cs +++ b/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgery.cs @@ -67,9 +67,12 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal } } - // Explicitly set the cache headers to 'no-cache'. This could override any user set value but this is fine - // as a response with antiforgery token must never be cached. - SetDoNotCacheHeaders(httpContext); + if (!httpContext.Response.HasStarted) + { + // Explicitly set the cache headers to 'no-cache'. This could override any user set value but this is fine + // as a response with antiforgery token must never be cached. + SetDoNotCacheHeaders(httpContext); + } return tokenSet; } @@ -247,7 +250,10 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal _logger.ReusedCookieToken(); } - SetDoNotCacheHeaders(httpContext); + if (!httpContext.Response.HasStarted) + { + SetDoNotCacheHeaders(httpContext); + } } private void SaveCookieTokenAndHeader(HttpContext httpContext, string cookieToken) @@ -374,28 +380,13 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal /// The . protected virtual void SetDoNotCacheHeaders(HttpContext httpContext) { - bool cacheHeadersChanged = SetHeaderIfNotSet(httpContext, HeaderNames.CacheControl, "no-cache, no-store"); - cacheHeadersChanged |= SetHeaderIfNotSet(httpContext, HeaderNames.Pragma, "no-cache"); - - if (cacheHeadersChanged) - { // Since antifogery token generation is not very obvious to the end users (ex: MVC's form tag generates them // by default), log a warning to let users know of the change in behavior to any cache headers they might // have set explicitly. LogCacheHeaderOverrideWarning(httpContext.Response); - } - } - private static bool SetHeaderIfNotSet(HttpContext context, string headerName, string value) - { - if (!context.Response.Headers.ContainsKey(headerName)) - { - context.Response.Headers[headerName] = value; - - return true; - } - - return false; + httpContext.Response.Headers[HeaderNames.CacheControl] = "no-cache, no-store"; + httpContext.Response.Headers[HeaderNames.Pragma] = "no-cache"; } private void LogCacheHeaderOverrideWarning(HttpResponse response) From ea38977599ac51e2542985a9815d1dd6107a376b Mon Sep 17 00:00:00 2001 From: Artak Mkrtchyan Date: Mon, 22 Jan 2018 16:41:43 -0800 Subject: [PATCH 255/296] Removed unnecessary spaces --- .../Internal/DefaultAntiforgery.cs | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgery.cs b/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgery.cs index 5cc860b593..cef46be893 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgery.cs +++ b/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgery.cs @@ -380,13 +380,13 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal /// The . protected virtual void SetDoNotCacheHeaders(HttpContext httpContext) { - // Since antifogery token generation is not very obvious to the end users (ex: MVC's form tag generates them - // by default), log a warning to let users know of the change in behavior to any cache headers they might - // have set explicitly. - LogCacheHeaderOverrideWarning(httpContext.Response); + // Since antifogery token generation is not very obvious to the end users (ex: MVC's form tag generates them + // by default), log a warning to let users know of the change in behavior to any cache headers they might + // have set explicitly. + LogCacheHeaderOverrideWarning(httpContext.Response); - httpContext.Response.Headers[HeaderNames.CacheControl] = "no-cache, no-store"; - httpContext.Response.Headers[HeaderNames.Pragma] = "no-cache"; + httpContext.Response.Headers[HeaderNames.CacheControl] = "no-cache, no-store"; + httpContext.Response.Headers[HeaderNames.Pragma] = "no-cache"; } private void LogCacheHeaderOverrideWarning(HttpResponse response) From 763393efc48f410be954d833f706577c06f16038 Mon Sep 17 00:00:00 2001 From: Artak Mkrtchyan Date: Mon, 22 Jan 2018 17:51:13 -0800 Subject: [PATCH 256/296] Added a test verifying that the cache headers are not set after the response has started. --- .../Internal/DefaultAntiforgeryTest.cs | 59 +++++++++++++++++++ 1 file changed, 59 insertions(+) diff --git a/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTest.cs b/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTest.cs index 4eebaad29f..4f041d4fc3 100644 --- a/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTest.cs +++ b/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTest.cs @@ -6,6 +6,7 @@ using System.Linq; using System.Security.Claims; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.Features; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Testing; @@ -1137,6 +1138,47 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal context.TokenSerializer.Verify(s => s.Deserialize(null), Times.Never); } + [Fact] + public void SetCookieTokenAndHeader_DoesNotModifyHeadersAfterResponseHasStarted() + { + // Arrange + var antiforgeryFeature = new AntiforgeryFeature + { + HaveDeserializedCookieToken = false, + HaveGeneratedNewCookieToken = false, + HaveStoredNewCookieToken = true, + NewCookieToken = new AntiforgeryToken(), + NewCookieTokenString = "serialized-cookie-token-from-context", + NewRequestToken = new AntiforgeryToken(), + NewRequestTokenString = "serialized-form-token-from-context", + }; + var context = CreateMockContext( + new AntiforgeryOptions(), + useOldCookie: false, + isOldCookieValid: false, + antiforgeryFeature: antiforgeryFeature); + var testTokenSet = new TestTokenSet + { + OldCookieTokenString = null + }; + + var nullTokenStore = GetTokenStore(context.HttpContext, testTokenSet, false); + var antiforgery = GetAntiforgery( + context.HttpContext, + tokenGenerator: context.TokenGenerator.Object, + tokenStore: nullTokenStore.Object); + + TestResponseFeature testResponse = new TestResponseFeature(); + context.HttpContext.Features.Set(testResponse); + context.HttpContext.Response.Headers["Cache-Control"] = "public"; + testResponse.StartResponse(); + + // Act + antiforgery.SetCookieTokenAndHeader(context.HttpContext); + + Assert.Equal("public", context.HttpContext.Response.Headers["Cache-Control"]); + } + [Fact] public void GetAndStoreTokens_DoesNotLogWarning_IfNoExistingCacheHeadersPresent() { @@ -1196,6 +1238,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal var antiforgery = GetAntiforgery(context); context.HttpContext.Response.Headers[headerName] = headerValue; + //context.HttpContext.Features // Act var tokenSet = antiforgery.GetAndStoreTokens(context.HttpContext); @@ -1435,5 +1478,21 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal { public AntiforgeryOptions Value { get; set; } = new AntiforgeryOptions(); } + + private class TestResponseFeature : HttpResponseFeature + { + private bool _hasStarted = false; + + public override bool HasStarted { get => _hasStarted; } + + public TestResponseFeature() + { + } + + public void StartResponse() + { + _hasStarted = true; + } + } } } From 18bd033d8ec320ef7f58a477d090818822cc257e Mon Sep 17 00:00:00 2001 From: Artak Mkrtchyan Date: Mon, 22 Jan 2018 18:10:01 -0800 Subject: [PATCH 257/296] Removed unnecessary comment --- .../Internal/DefaultAntiforgeryTest.cs | 1 - 1 file changed, 1 deletion(-) diff --git a/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTest.cs b/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTest.cs index 4f041d4fc3..faf895d524 100644 --- a/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTest.cs +++ b/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTest.cs @@ -1238,7 +1238,6 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal var antiforgery = GetAntiforgery(context); context.HttpContext.Response.Headers[headerName] = headerValue; - //context.HttpContext.Features // Act var tokenSet = antiforgery.GetAndStoreTokens(context.HttpContext); From 9022c602580fae6eda761b9ae3d4ad9465dce09f Mon Sep 17 00:00:00 2001 From: Pranav K Date: Tue, 23 Jan 2018 15:28:57 -0800 Subject: [PATCH 258/296] Branching for 2.1.0-preview1 --- build/dependencies.props | 26 +++++++++++++------------- build/repo.props | 4 ++-- build/sources.props | 4 ++-- korebuild-lock.txt | 4 ++-- 4 files changed, 19 insertions(+), 19 deletions(-) diff --git a/build/dependencies.props b/build/dependencies.props index 6519615656..16e0755262 100644 --- a/build/dependencies.props +++ b/build/dependencies.props @@ -3,20 +3,20 @@ $(MSBuildAllProjects);$(MSBuildThisFileFullPath) - 2.1.0-preview1-15651 - 2.1.0-preview1-27965 - 2.1.0-preview1-27965 - 2.1.0-preview1-27965 - 2.1.0-preview1-27965 - 2.1.0-preview1-27965 - 2.1.0-preview1-27965 - 2.1.0-preview1-27965 - 2.1.0-preview1-27965 - 2.1.0-preview1-27965 - 2.1.0-preview1-27965 - 2.1.0-preview1-27965 + 2.1.0-preview1-15679 + 2.1.0-preview1-28153 + 2.1.0-preview1-28153 + 2.1.0-preview1-28153 + 2.1.0-preview1-28153 + 2.1.0-preview1-28153 + 2.1.0-preview1-28153 + 2.1.0-preview1-28153 + 2.1.0-preview1-28153 + 2.1.0-preview1-28153 + 2.1.0-preview1-28153 + 2.1.0-preview1-28153 2.0.0 - 2.1.0-preview1-26016-05 + 2.1.0-preview1-26115-03 15.3.0 4.7.49 2.3.1 diff --git a/build/repo.props b/build/repo.props index ebbe645751..b2cdb7b829 100644 --- a/build/repo.props +++ b/build/repo.props @@ -1,9 +1,9 @@ - + Internal.AspNetCore.Universe.Lineup - https://dotnet.myget.org/F/aspnetcore-dev/api/v3/index.json + https://dotnet.myget.org/F/aspnetcore-release/api/v3/index.json diff --git a/build/sources.props b/build/sources.props index 9feff29d09..5d66393335 100644 --- a/build/sources.props +++ b/build/sources.props @@ -1,11 +1,11 @@ - + $(DotNetRestoreSources) $(RestoreSources); - https://dotnet.myget.org/F/aspnetcore-dev/api/v3/index.json; + https://dotnet.myget.org/F/aspnetcore-release/api/v3/index.json; https://dotnet.myget.org/F/aspnetcore-tools/api/v3/index.json; diff --git a/korebuild-lock.txt b/korebuild-lock.txt index 2146d006d7..a474bc0e35 100644 --- a/korebuild-lock.txt +++ b/korebuild-lock.txt @@ -1,2 +1,2 @@ -version:2.1.0-preview1-15661 -commithash:c9349d4c8a495d3085d9b879214d80f2f45e2193 +version:2.1.0-preview1-15679 +commithash:5347461137cb45a77ddcc0b55b2478092de43338 From fc1a8842bc35754873c44b195f70769027ad917a Mon Sep 17 00:00:00 2001 From: Pranav K Date: Wed, 24 Jan 2018 15:00:26 -0800 Subject: [PATCH 259/296] Updating version to preview2 --- version.props | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/version.props b/version.props index 5c4a7c32d1..370d5ababd 100644 --- a/version.props +++ b/version.props @@ -1,7 +1,7 @@ 2.1.0 - preview1 + preview2 $(VersionPrefix) $(VersionPrefix)-$(VersionSuffix)-final t000 From d2cfd09acf49b13b1fa942e84f35c4062ae9c866 Mon Sep 17 00:00:00 2001 From: Nate McMaster Date: Wed, 31 Jan 2018 15:01:09 -0800 Subject: [PATCH 260/296] Update dependencies.props to 2.1.0-preview-28193, build tools to 2.1.0-preview1-1010 [ci skip] Scripted changes: - updated travis and appveyor.yml files to only build dev, ci, and release branches - updated dependencies.props - updated korebuild-lock.txt - updated korebuild.json to release/2.1 channel --- .appveyor.yml | 15 +++++++-------- .travis.yml | 23 ++++++++++++----------- build/dependencies.props | 26 +++++++++++++------------- korebuild-lock.txt | 4 ++-- korebuild.json | 4 ++-- 5 files changed, 36 insertions(+), 36 deletions(-) diff --git a/.appveyor.yml b/.appveyor.yml index 46038786c9..4eea96ab69 100644 --- a/.appveyor.yml +++ b/.appveyor.yml @@ -1,18 +1,17 @@ init: - - git config --global core.autocrlf true +- git config --global core.autocrlf true branches: only: - - master - - release - - dev - - /^(.*\/)?ci-.*$/ + - dev + - /^release\/.*$/ + - /^(.*\/)?ci-.*$/ build_script: - - ps: .\run.ps1 default-build +- ps: .\run.ps1 default-build clone_depth: 1 environment: global: DOTNET_SKIP_FIRST_TIME_EXPERIENCE: true DOTNET_CLI_TELEMETRY_OPTOUT: 1 -test: off -deploy: off +test: 'off' +deploy: 'off' os: Visual Studio 2017 diff --git a/.travis.yml b/.travis.yml index b10be14215..64bdbb4441 100644 --- a/.travis.yml +++ b/.travis.yml @@ -3,24 +3,25 @@ sudo: false dist: trusty env: global: - - DOTNET_SKIP_FIRST_TIME_EXPERIENCE: true - - DOTNET_CLI_TELEMETRY_OPTOUT: 1 + - DOTNET_SKIP_FIRST_TIME_EXPERIENCE: true + - DOTNET_CLI_TELEMETRY_OPTOUT: 1 mono: none os: - - linux - - osx +- linux +- osx osx_image: xcode8.2 addons: apt: packages: - - libunwind8 + - libunwind8 branches: only: - - master - - release - - dev - - /^(.*\/)?ci-.*$/ + - dev + - /^release\/.*$/ + - /^(.*\/)?ci-.*$/ before_install: - - if test "$TRAVIS_OS_NAME" == "osx"; then brew update; brew install openssl; ln -s /usr/local/opt/openssl/lib/libcrypto.1.0.0.dylib /usr/local/lib/; ln -s /usr/local/opt/openssl/lib/libssl.1.0.0.dylib /usr/local/lib/; fi +- if test "$TRAVIS_OS_NAME" == "osx"; then brew update; brew install openssl; ln -s + /usr/local/opt/openssl/lib/libcrypto.1.0.0.dylib /usr/local/lib/; ln -s /usr/local/opt/openssl/lib/libssl.1.0.0.dylib + /usr/local/lib/; fi script: - - ./build.sh +- ./build.sh diff --git a/build/dependencies.props b/build/dependencies.props index 16e0755262..e177fa768a 100644 --- a/build/dependencies.props +++ b/build/dependencies.props @@ -3,20 +3,20 @@ $(MSBuildAllProjects);$(MSBuildThisFileFullPath) - 2.1.0-preview1-15679 - 2.1.0-preview1-28153 - 2.1.0-preview1-28153 - 2.1.0-preview1-28153 - 2.1.0-preview1-28153 - 2.1.0-preview1-28153 - 2.1.0-preview1-28153 - 2.1.0-preview1-28153 - 2.1.0-preview1-28153 - 2.1.0-preview1-28153 - 2.1.0-preview1-28153 - 2.1.0-preview1-28153 + 2.1.0-preview1-1010 + 2.1.0-preview1-28193 + 2.1.0-preview1-28193 + 2.1.0-preview1-28193 + 2.1.0-preview1-28193 + 2.1.0-preview1-28193 + 2.1.0-preview1-28193 + 2.1.0-preview1-28193 + 2.1.0-preview1-28193 + 2.1.0-preview1-28193 + 2.1.0-preview1-28193 + 2.1.0-preview1-28193 2.0.0 - 2.1.0-preview1-26115-03 + 2.1.0-preview1-26122-01 15.3.0 4.7.49 2.3.1 diff --git a/korebuild-lock.txt b/korebuild-lock.txt index a474bc0e35..851bfbf203 100644 --- a/korebuild-lock.txt +++ b/korebuild-lock.txt @@ -1,2 +1,2 @@ -version:2.1.0-preview1-15679 -commithash:5347461137cb45a77ddcc0b55b2478092de43338 +version:2.1.0-preview1-1010 +commithash:75ca924dfbd673c38841025b04c4dcd93b84f56d diff --git a/korebuild.json b/korebuild.json index bd5d51a51b..678d8bb948 100644 --- a/korebuild.json +++ b/korebuild.json @@ -1,4 +1,4 @@ { - "$schema": "https://raw.githubusercontent.com/aspnet/BuildTools/dev/tools/korebuild.schema.json", - "channel": "dev" + "$schema": "https://raw.githubusercontent.com/aspnet/BuildTools/release/2.1/tools/korebuild.schema.json", + "channel": "release/2.1" } From aaa3f20a8610f7e7704b827a4ef5b8592dd673d8 Mon Sep 17 00:00:00 2001 From: "ASP.NET CI" Date: Thu, 1 Feb 2018 02:47:04 +0000 Subject: [PATCH 261/296] Update dependencies.props [auto-updated: dependencies] --- build/dependencies.props | 26 +++++++++++++------------- korebuild-lock.txt | 4 ++-- 2 files changed, 15 insertions(+), 15 deletions(-) diff --git a/build/dependencies.props b/build/dependencies.props index 6519615656..bc8dcddad9 100644 --- a/build/dependencies.props +++ b/build/dependencies.props @@ -3,20 +3,20 @@ $(MSBuildAllProjects);$(MSBuildThisFileFullPath) - 2.1.0-preview1-15651 - 2.1.0-preview1-27965 - 2.1.0-preview1-27965 - 2.1.0-preview1-27965 - 2.1.0-preview1-27965 - 2.1.0-preview1-27965 - 2.1.0-preview1-27965 - 2.1.0-preview1-27965 - 2.1.0-preview1-27965 - 2.1.0-preview1-27965 - 2.1.0-preview1-27965 - 2.1.0-preview1-27965 + 2.1.0-preview2-15692 + 2.1.0-preview2-28215 + 2.1.0-preview2-28215 + 2.1.0-preview2-28215 + 2.1.0-preview2-28215 + 2.1.0-preview2-28215 + 2.1.0-preview2-28215 + 2.1.0-preview2-28215 + 2.1.0-preview2-28215 + 2.1.0-preview2-28215 + 2.1.0-preview2-28215 + 2.1.0-preview2-28215 2.0.0 - 2.1.0-preview1-26016-05 + 2.1.0-preview2-26130-04 15.3.0 4.7.49 2.3.1 diff --git a/korebuild-lock.txt b/korebuild-lock.txt index 2146d006d7..232cb858c2 100644 --- a/korebuild-lock.txt +++ b/korebuild-lock.txt @@ -1,2 +1,2 @@ -version:2.1.0-preview1-15661 -commithash:c9349d4c8a495d3085d9b879214d80f2f45e2193 +version:2.1.0-preview2-15692 +commithash:5d9f445ce3f8492451a6f461df7e739bbed6a7f8 From c8490e95eb569ded13f694a8b9c20cf3dcb2b2d1 Mon Sep 17 00:00:00 2001 From: "ASP.NET CI" Date: Sat, 3 Feb 2018 02:32:52 +0000 Subject: [PATCH 262/296] Update dependencies.props [auto-updated: dependencies] --- build/dependencies.props | 24 ++++++++++++------------ korebuild-lock.txt | 4 ++-- 2 files changed, 14 insertions(+), 14 deletions(-) diff --git a/build/dependencies.props b/build/dependencies.props index bc8dcddad9..88cb2195ff 100644 --- a/build/dependencies.props +++ b/build/dependencies.props @@ -3,18 +3,18 @@ $(MSBuildAllProjects);$(MSBuildThisFileFullPath) - 2.1.0-preview2-15692 - 2.1.0-preview2-28215 - 2.1.0-preview2-28215 - 2.1.0-preview2-28215 - 2.1.0-preview2-28215 - 2.1.0-preview2-28215 - 2.1.0-preview2-28215 - 2.1.0-preview2-28215 - 2.1.0-preview2-28215 - 2.1.0-preview2-28215 - 2.1.0-preview2-28215 - 2.1.0-preview2-28215 + 2.1.0-preview2-15694 + 2.1.0-preview2-30020 + 2.1.0-preview2-30020 + 2.1.0-preview2-30020 + 2.1.0-preview2-30020 + 2.1.0-preview2-30020 + 2.1.0-preview2-30020 + 2.1.0-preview2-30020 + 2.1.0-preview2-30020 + 2.1.0-preview2-30020 + 2.1.0-preview2-30020 + 2.1.0-preview2-30020 2.0.0 2.1.0-preview2-26130-04 15.3.0 diff --git a/korebuild-lock.txt b/korebuild-lock.txt index 232cb858c2..6f294ef0e6 100644 --- a/korebuild-lock.txt +++ b/korebuild-lock.txt @@ -1,2 +1,2 @@ -version:2.1.0-preview2-15692 -commithash:5d9f445ce3f8492451a6f461df7e739bbed6a7f8 +version:2.1.0-preview2-15694 +commithash:f61af02b48e89592c9aadb7ebaebe84228666c3b From b30a9785bee5d1af03b198ab02a99d915fc755ff Mon Sep 17 00:00:00 2001 From: "ASP.NET CI" Date: Fri, 9 Feb 2018 11:30:35 -0800 Subject: [PATCH 263/296] Update dependencies.props [auto-updated: dependencies] --- build/dependencies.props | 24 ++++++++++++------------ korebuild-lock.txt | 4 ++-- 2 files changed, 14 insertions(+), 14 deletions(-) diff --git a/build/dependencies.props b/build/dependencies.props index 88cb2195ff..dd399aa43a 100644 --- a/build/dependencies.props +++ b/build/dependencies.props @@ -3,18 +3,18 @@ $(MSBuildAllProjects);$(MSBuildThisFileFullPath) - 2.1.0-preview2-15694 - 2.1.0-preview2-30020 - 2.1.0-preview2-30020 - 2.1.0-preview2-30020 - 2.1.0-preview2-30020 - 2.1.0-preview2-30020 - 2.1.0-preview2-30020 - 2.1.0-preview2-30020 - 2.1.0-preview2-30020 - 2.1.0-preview2-30020 - 2.1.0-preview2-30020 - 2.1.0-preview2-30020 + 2.1.0-preview2-15698 + 2.1.0-preview2-30066 + 2.1.0-preview2-30066 + 2.1.0-preview2-30066 + 2.1.0-preview2-30066 + 2.1.0-preview2-30066 + 2.1.0-preview2-30066 + 2.1.0-preview2-30066 + 2.1.0-preview2-30066 + 2.1.0-preview2-30066 + 2.1.0-preview2-30066 + 2.1.0-preview2-30066 2.0.0 2.1.0-preview2-26130-04 15.3.0 diff --git a/korebuild-lock.txt b/korebuild-lock.txt index 6f294ef0e6..3e2b56b91b 100644 --- a/korebuild-lock.txt +++ b/korebuild-lock.txt @@ -1,2 +1,2 @@ -version:2.1.0-preview2-15694 -commithash:f61af02b48e89592c9aadb7ebaebe84228666c3b +version:2.1.0-preview2-15698 +commithash:7216e5068cb1957e09d45fcbe58a744dd5c2de73 From 35784501ecef56f768369e78b30d9324489a7a38 Mon Sep 17 00:00:00 2001 From: "ASP.NET CI" Date: Sun, 11 Feb 2018 12:12:21 -0800 Subject: [PATCH 264/296] Update dependencies.props [auto-updated: dependencies] --- build/dependencies.props | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/build/dependencies.props b/build/dependencies.props index dd399aa43a..586010737f 100644 --- a/build/dependencies.props +++ b/build/dependencies.props @@ -4,23 +4,23 @@ 2.1.0-preview2-15698 - 2.1.0-preview2-30066 - 2.1.0-preview2-30066 - 2.1.0-preview2-30066 - 2.1.0-preview2-30066 - 2.1.0-preview2-30066 - 2.1.0-preview2-30066 - 2.1.0-preview2-30066 - 2.1.0-preview2-30066 - 2.1.0-preview2-30066 - 2.1.0-preview2-30066 - 2.1.0-preview2-30066 + 2.1.0-preview2-30077 + 2.1.0-preview2-30077 + 2.1.0-preview2-30077 + 2.1.0-preview2-30077 + 2.1.0-preview2-30077 + 2.1.0-preview2-30077 + 2.1.0-preview2-30077 + 2.1.0-preview2-30077 + 2.1.0-preview2-30077 + 2.1.0-preview2-30077 + 2.1.0-preview2-30077 2.0.0 2.1.0-preview2-26130-04 15.3.0 4.7.49 2.3.1 - 2.3.1 + 2.4.0-beta.1.build3945 From 7ab86d5505756ea8c502379cd672627f43adeea8 Mon Sep 17 00:00:00 2001 From: "ASP.NET CI" Date: Sun, 18 Feb 2018 12:08:18 -0800 Subject: [PATCH 265/296] Update dependencies.props [auto-updated: dependencies] --- build/dependencies.props | 24 ++++++++++++------------ korebuild-lock.txt | 4 ++-- 2 files changed, 14 insertions(+), 14 deletions(-) diff --git a/build/dependencies.props b/build/dependencies.props index 586010737f..3f0e78d6c8 100644 --- a/build/dependencies.props +++ b/build/dependencies.props @@ -3,18 +3,18 @@ $(MSBuildAllProjects);$(MSBuildThisFileFullPath) - 2.1.0-preview2-15698 - 2.1.0-preview2-30077 - 2.1.0-preview2-30077 - 2.1.0-preview2-30077 - 2.1.0-preview2-30077 - 2.1.0-preview2-30077 - 2.1.0-preview2-30077 - 2.1.0-preview2-30077 - 2.1.0-preview2-30077 - 2.1.0-preview2-30077 - 2.1.0-preview2-30077 - 2.1.0-preview2-30077 + 2.1.0-preview2-15707 + 2.1.0-preview2-30131 + 2.1.0-preview2-30131 + 2.1.0-preview2-30131 + 2.1.0-preview2-30131 + 2.1.0-preview2-30131 + 2.1.0-preview2-30131 + 2.1.0-preview2-30131 + 2.1.0-preview2-30131 + 2.1.0-preview2-30131 + 2.1.0-preview2-30131 + 2.1.0-preview2-30131 2.0.0 2.1.0-preview2-26130-04 15.3.0 diff --git a/korebuild-lock.txt b/korebuild-lock.txt index 3e2b56b91b..89d0ad3d15 100644 --- a/korebuild-lock.txt +++ b/korebuild-lock.txt @@ -1,2 +1,2 @@ -version:2.1.0-preview2-15698 -commithash:7216e5068cb1957e09d45fcbe58a744dd5c2de73 +version:2.1.0-preview2-15707 +commithash:e74e53f129ab34332947fea7ac7b7591b027cb22 From 6f9e7728cadc76bc3223058a1f56ba2297bf5bd7 Mon Sep 17 00:00:00 2001 From: Pranav K Date: Wed, 21 Feb 2018 14:54:45 -0800 Subject: [PATCH 266/296] Use FeatureBranchVersionSuffix when generating VersionSuffix --- version.props | 1 + 1 file changed, 1 insertion(+) diff --git a/version.props b/version.props index 370d5ababd..65c8a07e37 100644 --- a/version.props +++ b/version.props @@ -5,6 +5,7 @@ $(VersionPrefix) $(VersionPrefix)-$(VersionSuffix)-final t000 + $(VersionSuffix)-$([System.Text.RegularExpressions.Regex]::Replace('$(FeatureBranchVersionSuffix)', '[^\w-]', '-')) $(VersionSuffix)-$(BuildNumber) From 828036796f89edaca1c24977a8d66bb1075e22a0 Mon Sep 17 00:00:00 2001 From: "ASP.NET CI" Date: Mon, 26 Feb 2018 10:51:09 -0800 Subject: [PATCH 267/296] Update dependencies.props [auto-updated: dependencies] --- build/dependencies.props | 26 +++++++++++++------------- korebuild-lock.txt | 4 ++-- 2 files changed, 15 insertions(+), 15 deletions(-) diff --git a/build/dependencies.props b/build/dependencies.props index 3f0e78d6c8..0de51cd2a5 100644 --- a/build/dependencies.props +++ b/build/dependencies.props @@ -3,21 +3,21 @@ $(MSBuildAllProjects);$(MSBuildThisFileFullPath) - 2.1.0-preview2-15707 - 2.1.0-preview2-30131 - 2.1.0-preview2-30131 - 2.1.0-preview2-30131 - 2.1.0-preview2-30131 - 2.1.0-preview2-30131 - 2.1.0-preview2-30131 - 2.1.0-preview2-30131 - 2.1.0-preview2-30131 - 2.1.0-preview2-30131 - 2.1.0-preview2-30131 - 2.1.0-preview2-30131 + 2.1.0-preview2-15721 + 2.1.0-preview2-30187 + 2.1.0-preview2-30187 + 2.1.0-preview2-30187 + 2.1.0-preview2-30187 + 2.1.0-preview2-30187 + 2.1.0-preview2-30187 + 2.1.0-preview2-30187 + 2.1.0-preview2-30187 + 2.1.0-preview2-30187 + 2.1.0-preview2-30187 + 2.1.0-preview2-30187 2.0.0 2.1.0-preview2-26130-04 - 15.3.0 + 15.6.0 4.7.49 2.3.1 2.4.0-beta.1.build3945 diff --git a/korebuild-lock.txt b/korebuild-lock.txt index 89d0ad3d15..e6c7fddffa 100644 --- a/korebuild-lock.txt +++ b/korebuild-lock.txt @@ -1,2 +1,2 @@ -version:2.1.0-preview2-15707 -commithash:e74e53f129ab34332947fea7ac7b7591b027cb22 +version:2.1.0-preview2-15721 +commithash:f9bb4be59e39938ec59a6975257e26099b0d03c1 From 6e84db5e068975e4078b42eea8f0d7e2a00200b1 Mon Sep 17 00:00:00 2001 From: Pranav K Date: Tue, 6 Mar 2018 10:02:11 -0800 Subject: [PATCH 268/296] Use dotnet-core feed in repos --- build/sources.props | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/build/sources.props b/build/sources.props index 9feff29d09..9215df9751 100644 --- a/build/sources.props +++ b/build/sources.props @@ -1,10 +1,11 @@ - + $(DotNetRestoreSources) $(RestoreSources); + https://dotnet.myget.org/F/dotnet-core/api/v3/index.json; https://dotnet.myget.org/F/aspnetcore-dev/api/v3/index.json; https://dotnet.myget.org/F/aspnetcore-tools/api/v3/index.json; From 26f65bd70e3f9f8b3bea1c03f96b6c606726b277 Mon Sep 17 00:00:00 2001 From: Pranav K Date: Tue, 6 Mar 2018 10:02:12 -0800 Subject: [PATCH 269/296] Prepend FeatureBranchVersionPrefix if FeatureBranchVersionSuffix is specified --- version.props | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/version.props b/version.props index 65c8a07e37..a11ea1ed52 100644 --- a/version.props +++ b/version.props @@ -5,7 +5,8 @@ $(VersionPrefix) $(VersionPrefix)-$(VersionSuffix)-final t000 - $(VersionSuffix)-$([System.Text.RegularExpressions.Regex]::Replace('$(FeatureBranchVersionSuffix)', '[^\w-]', '-')) + a- + $(FeatureBranchVersionPrefix)$(VersionSuffix)-$([System.Text.RegularExpressions.Regex]::Replace('$(FeatureBranchVersionSuffix)', '[^\w-]', '-')) $(VersionSuffix)-$(BuildNumber) From d53db529fcf8c99feffc3cbed786a091dd17c7fc Mon Sep 17 00:00:00 2001 From: "ASP.NET CI" Date: Thu, 8 Mar 2018 12:50:29 -0800 Subject: [PATCH 270/296] Update dependencies.props [auto-updated: dependencies] --- build/dependencies.props | 26 +++++++++++++------------- korebuild-lock.txt | 4 ++-- 2 files changed, 15 insertions(+), 15 deletions(-) diff --git a/build/dependencies.props b/build/dependencies.props index 0de51cd2a5..c3acbe9ba4 100644 --- a/build/dependencies.props +++ b/build/dependencies.props @@ -3,20 +3,20 @@ $(MSBuildAllProjects);$(MSBuildThisFileFullPath) - 2.1.0-preview2-15721 - 2.1.0-preview2-30187 - 2.1.0-preview2-30187 - 2.1.0-preview2-30187 - 2.1.0-preview2-30187 - 2.1.0-preview2-30187 - 2.1.0-preview2-30187 - 2.1.0-preview2-30187 - 2.1.0-preview2-30187 - 2.1.0-preview2-30187 - 2.1.0-preview2-30187 - 2.1.0-preview2-30187 + 2.1.0-preview2-15728 + 2.1.0-preview2-30272 + 2.1.0-preview2-30272 + 2.1.0-preview2-30272 + 2.1.0-preview2-30272 + 2.1.0-preview2-30272 + 2.1.0-preview2-30272 + 2.1.0-preview2-30272 + 2.1.0-preview2-30272 + 2.1.0-preview2-30272 + 2.1.0-preview2-30272 + 2.1.0-preview2-30272 2.0.0 - 2.1.0-preview2-26130-04 + 2.1.0-preview2-26225-03 15.6.0 4.7.49 2.3.1 diff --git a/korebuild-lock.txt b/korebuild-lock.txt index e6c7fddffa..138d848db1 100644 --- a/korebuild-lock.txt +++ b/korebuild-lock.txt @@ -1,2 +1,2 @@ -version:2.1.0-preview2-15721 -commithash:f9bb4be59e39938ec59a6975257e26099b0d03c1 +version:2.1.0-preview2-15728 +commithash:393377068ddcf51dfee0536536d455f57a828b06 From 1ef20c7b65f5c99e83479571f046665ecc21e4af Mon Sep 17 00:00:00 2001 From: Pranav K Date: Fri, 16 Mar 2018 11:12:26 -0700 Subject: [PATCH 271/296] Branching for 2.1.0-preview2 --- build/dependencies.props | 26 +++++++++++++------------- build/repo.props | 4 ++-- build/sources.props | 2 +- korebuild-lock.txt | 4 ++-- 4 files changed, 18 insertions(+), 18 deletions(-) diff --git a/build/dependencies.props b/build/dependencies.props index c3acbe9ba4..f1330cf76a 100644 --- a/build/dependencies.props +++ b/build/dependencies.props @@ -3,20 +3,20 @@ $(MSBuildAllProjects);$(MSBuildThisFileFullPath) - 2.1.0-preview2-15728 - 2.1.0-preview2-30272 - 2.1.0-preview2-30272 - 2.1.0-preview2-30272 - 2.1.0-preview2-30272 - 2.1.0-preview2-30272 - 2.1.0-preview2-30272 - 2.1.0-preview2-30272 - 2.1.0-preview2-30272 - 2.1.0-preview2-30272 - 2.1.0-preview2-30272 - 2.1.0-preview2-30272 + 2.1.0-preview2-15742 + 2.1.0-preview2-30355 + 2.1.0-preview2-30355 + 2.1.0-preview2-30355 + 2.1.0-preview2-30355 + 2.1.0-preview2-30355 + 2.1.0-preview2-30355 + 2.1.0-preview2-30355 + 2.1.0-preview2-30355 + 2.1.0-preview2-30355 + 2.1.0-preview2-30355 + 2.1.0-preview2-30355 2.0.0 - 2.1.0-preview2-26225-03 + 2.1.0-preview2-26314-02 15.6.0 4.7.49 2.3.1 diff --git a/build/repo.props b/build/repo.props index ebbe645751..b2cdb7b829 100644 --- a/build/repo.props +++ b/build/repo.props @@ -1,9 +1,9 @@ - + Internal.AspNetCore.Universe.Lineup - https://dotnet.myget.org/F/aspnetcore-dev/api/v3/index.json + https://dotnet.myget.org/F/aspnetcore-release/api/v3/index.json diff --git a/build/sources.props b/build/sources.props index 9215df9751..36045f12b5 100644 --- a/build/sources.props +++ b/build/sources.props @@ -6,7 +6,7 @@ $(RestoreSources); https://dotnet.myget.org/F/dotnet-core/api/v3/index.json; - https://dotnet.myget.org/F/aspnetcore-dev/api/v3/index.json; + https://dotnet.myget.org/F/aspnetcore-release/api/v3/index.json; https://dotnet.myget.org/F/aspnetcore-tools/api/v3/index.json; diff --git a/korebuild-lock.txt b/korebuild-lock.txt index 138d848db1..e40ef6651b 100644 --- a/korebuild-lock.txt +++ b/korebuild-lock.txt @@ -1,2 +1,2 @@ -version:2.1.0-preview2-15728 -commithash:393377068ddcf51dfee0536536d455f57a828b06 +version:2.1.0-preview2-15742 +commithash:21fbb0f2c3fe4a9216e2d59632b98cfd7d685962 From e734266504fc3106a6d88f0a792f06f7eda70489 Mon Sep 17 00:00:00 2001 From: Pranav K Date: Fri, 16 Mar 2018 11:24:43 -0700 Subject: [PATCH 272/296] Update version prefix to preview3 --- version.props | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/version.props b/version.props index a11ea1ed52..24f2b00a0a 100644 --- a/version.props +++ b/version.props @@ -1,7 +1,7 @@ 2.1.0 - preview2 + preview3 $(VersionPrefix) $(VersionPrefix)-$(VersionSuffix)-final t000 From 878ed82365b47a21a1e229d38977652c320a912f Mon Sep 17 00:00:00 2001 From: Pranav K Date: Fri, 16 Mar 2018 12:25:01 -0700 Subject: [PATCH 273/296] Update KoreBuild channel --- korebuild.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/korebuild.json b/korebuild.json index bd5d51a51b..678d8bb948 100644 --- a/korebuild.json +++ b/korebuild.json @@ -1,4 +1,4 @@ { - "$schema": "https://raw.githubusercontent.com/aspnet/BuildTools/dev/tools/korebuild.schema.json", - "channel": "dev" + "$schema": "https://raw.githubusercontent.com/aspnet/BuildTools/release/2.1/tools/korebuild.schema.json", + "channel": "release/2.1" } From bb52bcf11b48a5a76b751a8f0ba48cb65ed2eabc Mon Sep 17 00:00:00 2001 From: Ryan Brandenburg Date: Wed, 14 Mar 2018 15:32:59 -0700 Subject: [PATCH 274/296] Set 2.0 baselines --- build/dependencies.props | 2 +- korebuild-lock.txt | 4 +- .../baseline.netcore.json | 116 ++++++++++++++++-- .../Internal/DefaultClaimUidExtractorTest.cs | 1 - 4 files changed, 110 insertions(+), 13 deletions(-) diff --git a/build/dependencies.props b/build/dependencies.props index f1330cf76a..958a582fff 100644 --- a/build/dependencies.props +++ b/build/dependencies.props @@ -3,7 +3,7 @@ $(MSBuildAllProjects);$(MSBuildThisFileFullPath) - 2.1.0-preview2-15742 + 2.1.0-preview2-15744 2.1.0-preview2-30355 2.1.0-preview2-30355 2.1.0-preview2-30355 diff --git a/korebuild-lock.txt b/korebuild-lock.txt index e40ef6651b..f531e7b0f7 100644 --- a/korebuild-lock.txt +++ b/korebuild-lock.txt @@ -1,2 +1,2 @@ -version:2.1.0-preview2-15742 -commithash:21fbb0f2c3fe4a9216e2d59632b98cfd7d685962 +version:2.1.0-preview2-15744 +commithash:9e15cb6062ab5b9790d3fa699e018543a6950713 diff --git a/src/Microsoft.AspNetCore.Antiforgery/baseline.netcore.json b/src/Microsoft.AspNetCore.Antiforgery/baseline.netcore.json index 9117fb75fd..c095a3501b 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/baseline.netcore.json +++ b/src/Microsoft.AspNetCore.Antiforgery/baseline.netcore.json @@ -1,5 +1,5 @@ { - "AssemblyIdentity": "Microsoft.AspNetCore.Antiforgery, Version=1.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60", + "AssemblyIdentity": "Microsoft.AspNetCore.Antiforgery, Version=2.0.2.0, Culture=neutral, PublicKeyToken=adb9793829ddae60", "Types": [ { "Name": "Microsoft.Extensions.DependencyInjection.AntiforgeryServiceCollectionExtensions", @@ -55,19 +55,19 @@ "Members": [ { "Kind": "Method", - "Name": "get_CookieName", + "Name": "get_Cookie", "Parameters": [], - "ReturnType": "System.String", + "ReturnType": "Microsoft.AspNetCore.Http.CookieBuilder", "Visibility": "Public", "GenericParameter": [] }, { "Kind": "Method", - "Name": "set_CookieName", + "Name": "set_Cookie", "Parameters": [ { "Name": "value", - "Type": "System.String" + "Type": "Microsoft.AspNetCore.Http.CookieBuilder" } ], "ReturnType": "System.Void", @@ -118,7 +118,7 @@ }, { "Kind": "Method", - "Name": "get_RequireSsl", + "Name": "get_SuppressXFrameOptionsHeader", "Parameters": [], "ReturnType": "System.Boolean", "Visibility": "Public", @@ -126,7 +126,7 @@ }, { "Kind": "Method", - "Name": "set_RequireSsl", + "Name": "set_SuppressXFrameOptionsHeader", "Parameters": [ { "Name": "value", @@ -139,7 +139,70 @@ }, { "Kind": "Method", - "Name": "get_SuppressXFrameOptionsHeader", + "Name": "get_CookieName", + "Parameters": [], + "ReturnType": "System.String", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "set_CookieName", + "Parameters": [ + { + "Name": "value", + "Type": "System.String" + } + ], + "ReturnType": "System.Void", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "get_CookiePath", + "Parameters": [], + "ReturnType": "System.Nullable", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "set_CookiePath", + "Parameters": [ + { + "Name": "value", + "Type": "System.Nullable" + } + ], + "ReturnType": "System.Void", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "get_CookieDomain", + "Parameters": [], + "ReturnType": "System.String", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "set_CookieDomain", + "Parameters": [ + { + "Name": "value", + "Type": "System.String" + } + ], + "ReturnType": "System.Void", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "get_RequireSsl", "Parameters": [], "ReturnType": "System.Boolean", "Visibility": "Public", @@ -147,7 +210,7 @@ }, { "Kind": "Method", - "Name": "set_SuppressXFrameOptionsHeader", + "Name": "set_RequireSsl", "Parameters": [ { "Name": "value", @@ -1034,6 +1097,27 @@ ], "GenericParameters": [] }, + { + "Name": "Microsoft.AspNetCore.Antiforgery.Internal.CryptographyAlgorithms", + "Visibility": "Public", + "Kind": "Class", + "Abstract": true, + "Static": true, + "Sealed": true, + "ImplementedInterfaces": [], + "Members": [ + { + "Kind": "Method", + "Name": "CreateSHA256", + "Parameters": [], + "ReturnType": "System.Security.Cryptography.SHA256", + "Static": true, + "Visibility": "Public", + "GenericParameter": [] + } + ], + "GenericParameters": [] + }, { "Name": "Microsoft.AspNetCore.Antiforgery.Internal.DefaultAntiforgery", "Visibility": "Public", @@ -1122,6 +1206,20 @@ "Visibility": "Public", "GenericParameter": [] }, + { + "Kind": "Method", + "Name": "SetDoNotCacheHeaders", + "Parameters": [ + { + "Name": "httpContext", + "Type": "Microsoft.AspNetCore.Http.HttpContext" + } + ], + "ReturnType": "System.Void", + "Virtual": true, + "Visibility": "Protected", + "GenericParameter": [] + }, { "Kind": "Constructor", "Name": ".ctor", diff --git a/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultClaimUidExtractorTest.cs b/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultClaimUidExtractorTest.cs index aa5234c690..1852b910da 100644 --- a/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultClaimUidExtractorTest.cs +++ b/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultClaimUidExtractorTest.cs @@ -3,7 +3,6 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using System.Linq; using System.Security.Claims; using Microsoft.Extensions.ObjectPool; From 370ee3ad5964e0ba622233cd27854ebe7e3fd807 Mon Sep 17 00:00:00 2001 From: "ASP.NET CI" Date: Sun, 25 Mar 2018 15:28:49 -0700 Subject: [PATCH 275/296] Update dependencies.props [auto-updated: dependencies] --- build/dependencies.props | 28 ++++++++++++++-------------- korebuild-lock.txt | 4 ++-- 2 files changed, 16 insertions(+), 16 deletions(-) diff --git a/build/dependencies.props b/build/dependencies.props index c3acbe9ba4..c1e4b706d5 100644 --- a/build/dependencies.props +++ b/build/dependencies.props @@ -3,21 +3,21 @@ $(MSBuildAllProjects);$(MSBuildThisFileFullPath) - 2.1.0-preview2-15728 - 2.1.0-preview2-30272 - 2.1.0-preview2-30272 - 2.1.0-preview2-30272 - 2.1.0-preview2-30272 - 2.1.0-preview2-30272 - 2.1.0-preview2-30272 - 2.1.0-preview2-30272 - 2.1.0-preview2-30272 - 2.1.0-preview2-30272 - 2.1.0-preview2-30272 - 2.1.0-preview2-30272 + 2.1.0-preview3-17001 + 2.1.0-preview3-32037 + 2.1.0-preview3-32037 + 2.1.0-preview3-32037 + 2.1.0-preview3-32037 + 2.1.0-preview3-32037 + 2.1.0-preview3-32037 + 2.1.0-preview3-32037 + 2.1.0-preview3-32037 + 2.1.0-preview3-32037 + 2.1.0-preview3-32037 + 2.1.0-preview3-32037 2.0.0 - 2.1.0-preview2-26225-03 - 15.6.0 + 2.1.0-preview2-26314-02 + 15.6.1 4.7.49 2.3.1 2.4.0-beta.1.build3945 diff --git a/korebuild-lock.txt b/korebuild-lock.txt index 138d848db1..3a326c7d58 100644 --- a/korebuild-lock.txt +++ b/korebuild-lock.txt @@ -1,2 +1,2 @@ -version:2.1.0-preview2-15728 -commithash:393377068ddcf51dfee0536536d455f57a828b06 +version:2.1.0-preview3-17001 +commithash:dda68c56abf0d3b911fe6a2315872c446b314585 From 7627df6bdc3f87026b3f180152f0613de4cfa1c4 Mon Sep 17 00:00:00 2001 From: "Nate McMaster (automated)" Date: Wed, 28 Mar 2018 10:29:19 -0700 Subject: [PATCH 276/296] Update dependencies.props [auto-updated: dependencies] --- build/dependencies.props | 28 ++++++++++++++-------------- korebuild-lock.txt | 4 ++-- 2 files changed, 16 insertions(+), 16 deletions(-) diff --git a/build/dependencies.props b/build/dependencies.props index 958a582fff..d518717eb8 100644 --- a/build/dependencies.props +++ b/build/dependencies.props @@ -3,21 +3,21 @@ $(MSBuildAllProjects);$(MSBuildThisFileFullPath) - 2.1.0-preview2-15744 - 2.1.0-preview2-30355 - 2.1.0-preview2-30355 - 2.1.0-preview2-30355 - 2.1.0-preview2-30355 - 2.1.0-preview2-30355 - 2.1.0-preview2-30355 - 2.1.0-preview2-30355 - 2.1.0-preview2-30355 - 2.1.0-preview2-30355 - 2.1.0-preview2-30355 - 2.1.0-preview2-30355 + 2.1.0-preview2-15749 + 2.1.0-preview2-30478 + 2.1.0-preview2-30478 + 2.1.0-preview2-30478 + 2.1.0-preview2-30478 + 2.1.0-preview2-30478 + 2.1.0-preview2-30478 + 2.1.0-preview2-30478 + 2.1.0-preview2-30478 + 2.1.0-preview2-30478 + 2.1.0-preview2-30478 + 2.1.0-preview2-30478 2.0.0 - 2.1.0-preview2-26314-02 - 15.6.0 + 2.1.0-preview2-26326-03 + 15.6.1 4.7.49 2.3.1 2.4.0-beta.1.build3945 diff --git a/korebuild-lock.txt b/korebuild-lock.txt index f531e7b0f7..b8e036fe2c 100644 --- a/korebuild-lock.txt +++ b/korebuild-lock.txt @@ -1,2 +1,2 @@ -version:2.1.0-preview2-15744 -commithash:9e15cb6062ab5b9790d3fa699e018543a6950713 +version:2.1.0-preview2-15749 +commithash:5544c9ab20fa5e24b9e155d8958a3c3b6f5f9df9 From 9d8cf718509d8d6683f00256afd9ae175652de15 Mon Sep 17 00:00:00 2001 From: "ASP.NET CI" Date: Tue, 3 Apr 2018 22:16:16 +0000 Subject: [PATCH 277/296] Update dependencies.props [auto-updated: dependencies] --- build/dependencies.props | 26 +++++++++++++------------- korebuild-lock.txt | 4 ++-- 2 files changed, 15 insertions(+), 15 deletions(-) diff --git a/build/dependencies.props b/build/dependencies.props index c1e4b706d5..6af83a32c8 100644 --- a/build/dependencies.props +++ b/build/dependencies.props @@ -3,20 +3,20 @@ $(MSBuildAllProjects);$(MSBuildThisFileFullPath) - 2.1.0-preview3-17001 - 2.1.0-preview3-32037 - 2.1.0-preview3-32037 - 2.1.0-preview3-32037 - 2.1.0-preview3-32037 - 2.1.0-preview3-32037 - 2.1.0-preview3-32037 - 2.1.0-preview3-32037 - 2.1.0-preview3-32037 - 2.1.0-preview3-32037 - 2.1.0-preview3-32037 - 2.1.0-preview3-32037 + 2.1.0-preview3-17002 + 2.1.0-preview3-32110 + 2.1.0-preview3-32110 + 2.1.0-preview3-32110 + 2.1.0-preview3-32110 + 2.1.0-preview3-32110 + 2.1.0-preview3-32110 + 2.1.0-preview3-32110 + 2.1.0-preview3-32110 + 2.1.0-preview3-32110 + 2.1.0-preview3-32110 + 2.1.0-preview3-32110 2.0.0 - 2.1.0-preview2-26314-02 + 2.1.0-preview3-26331-01 15.6.1 4.7.49 2.3.1 diff --git a/korebuild-lock.txt b/korebuild-lock.txt index 3a326c7d58..b3af0b8bce 100644 --- a/korebuild-lock.txt +++ b/korebuild-lock.txt @@ -1,2 +1,2 @@ -version:2.1.0-preview3-17001 -commithash:dda68c56abf0d3b911fe6a2315872c446b314585 +version:2.1.0-preview3-17002 +commithash:b8e4e6ab104adc94c0719bb74229870e9b584a7f From 6d7d1bd8a5cf56841a67eeb4b47c57cff5a2387d Mon Sep 17 00:00:00 2001 From: "ASP.NET CI" Date: Sun, 15 Apr 2018 13:59:14 -0700 Subject: [PATCH 278/296] Update dependencies.props [auto-updated: dependencies] --- build/dependencies.props | 26 +++++++++++++------------- korebuild-lock.txt | 4 ++-- 2 files changed, 15 insertions(+), 15 deletions(-) diff --git a/build/dependencies.props b/build/dependencies.props index 6af83a32c8..e8bb766c67 100644 --- a/build/dependencies.props +++ b/build/dependencies.props @@ -3,20 +3,20 @@ $(MSBuildAllProjects);$(MSBuildThisFileFullPath) - 2.1.0-preview3-17002 - 2.1.0-preview3-32110 - 2.1.0-preview3-32110 - 2.1.0-preview3-32110 - 2.1.0-preview3-32110 - 2.1.0-preview3-32110 - 2.1.0-preview3-32110 - 2.1.0-preview3-32110 - 2.1.0-preview3-32110 - 2.1.0-preview3-32110 - 2.1.0-preview3-32110 - 2.1.0-preview3-32110 + 2.1.0-preview3-17018 + 2.1.0-preview3-32233 + 2.1.0-preview3-32233 + 2.1.0-preview3-32233 + 2.1.0-preview3-32233 + 2.1.0-preview3-32233 + 2.1.0-preview3-32233 + 2.1.0-preview3-32233 + 2.1.0-preview3-32233 + 2.1.0-preview3-32233 + 2.1.0-preview3-32233 + 2.1.0-preview3-32233 2.0.0 - 2.1.0-preview3-26331-01 + 2.1.0-preview3-26413-05 15.6.1 4.7.49 2.3.1 diff --git a/korebuild-lock.txt b/korebuild-lock.txt index b3af0b8bce..b419d767b9 100644 --- a/korebuild-lock.txt +++ b/korebuild-lock.txt @@ -1,2 +1,2 @@ -version:2.1.0-preview3-17002 -commithash:b8e4e6ab104adc94c0719bb74229870e9b584a7f +version:2.1.0-preview3-17018 +commithash:af264ca131f212b5ba8aafbc5110fc0fc510a2be From e4e09975e3d1014758593da55969e776837469a6 Mon Sep 17 00:00:00 2001 From: Ryan Brandenburg Date: Mon, 16 Apr 2018 13:09:11 -0700 Subject: [PATCH 279/296] Branching for 2.1.0-rc1 --- build/repo.props | 4 ++-- korebuild.json | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/build/repo.props b/build/repo.props index ebbe645751..6522573ad6 100644 --- a/build/repo.props +++ b/build/repo.props @@ -1,8 +1,8 @@ - + - Internal.AspNetCore.Universe.Lineup + Internal.AspNetCore.Universe.Lineup`n 2.1.0-rc1-* https://dotnet.myget.org/F/aspnetcore-dev/api/v3/index.json diff --git a/korebuild.json b/korebuild.json index bd5d51a51b..678d8bb948 100644 --- a/korebuild.json +++ b/korebuild.json @@ -1,4 +1,4 @@ { - "$schema": "https://raw.githubusercontent.com/aspnet/BuildTools/dev/tools/korebuild.schema.json", - "channel": "dev" + "$schema": "https://raw.githubusercontent.com/aspnet/BuildTools/release/2.1/tools/korebuild.schema.json", + "channel": "release/2.1" } From b6a8c2a55c088d24d4e69f0161cb0e8220a2ba4f Mon Sep 17 00:00:00 2001 From: Ryan Brandenburg Date: Mon, 16 Apr 2018 13:09:16 -0700 Subject: [PATCH 280/296] Update version number to 2.2.0 --- version.props | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/version.props b/version.props index 24f2b00a0a..44985cedb3 100644 --- a/version.props +++ b/version.props @@ -1,7 +1,7 @@ - 2.1.0 - preview3 + 2.2.0 + preview1 $(VersionPrefix) $(VersionPrefix)-$(VersionSuffix)-final t000 From 07bfec916aaff1bb06592ce10cce2539c31f0c90 Mon Sep 17 00:00:00 2001 From: Ryan Brandenburg Date: Mon, 16 Apr 2018 13:14:56 -0700 Subject: [PATCH 281/296] Branching for 2.1.0-rc1 --- build/repo.props | 4 ++-- korebuild.json | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/build/repo.props b/build/repo.props index ebbe645751..6522573ad6 100644 --- a/build/repo.props +++ b/build/repo.props @@ -1,8 +1,8 @@ - + - Internal.AspNetCore.Universe.Lineup + Internal.AspNetCore.Universe.Lineup`n 2.1.0-rc1-* https://dotnet.myget.org/F/aspnetcore-dev/api/v3/index.json diff --git a/korebuild.json b/korebuild.json index bd5d51a51b..678d8bb948 100644 --- a/korebuild.json +++ b/korebuild.json @@ -1,4 +1,4 @@ { - "$schema": "https://raw.githubusercontent.com/aspnet/BuildTools/dev/tools/korebuild.schema.json", - "channel": "dev" + "$schema": "https://raw.githubusercontent.com/aspnet/BuildTools/release/2.1/tools/korebuild.schema.json", + "channel": "release/2.1" } From d8158719d95e0b9886728330236d875afc1948ce Mon Sep 17 00:00:00 2001 From: Ryan Brandenburg Date: Mon, 16 Apr 2018 16:23:10 -0700 Subject: [PATCH 282/296] Fix bad update --- build/repo.props | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/build/repo.props b/build/repo.props index 6522573ad6..6c9c88ab01 100644 --- a/build/repo.props +++ b/build/repo.props @@ -2,7 +2,8 @@ - Internal.AspNetCore.Universe.Lineup`n 2.1.0-rc1-* + Internal.AspNetCore.Universe.Lineup + 2.1.0-rc1-* https://dotnet.myget.org/F/aspnetcore-dev/api/v3/index.json From 2843f8cfc5bceafe6c17f7054b218bbdf255d210 Mon Sep 17 00:00:00 2001 From: Ryan Brandenburg Date: Mon, 16 Apr 2018 16:45:11 -0700 Subject: [PATCH 283/296] Bad merge from dev --- version.props | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/version.props b/version.props index 44985cedb3..e27532787e 100644 --- a/version.props +++ b/version.props @@ -1,7 +1,7 @@ - 2.2.0 - preview1 + 2.1.0 + rc1 $(VersionPrefix) $(VersionPrefix)-$(VersionSuffix)-final t000 From fd5533634f8c493ed211306d337f058a47575274 Mon Sep 17 00:00:00 2001 From: Nate McMaster Date: Thu, 19 Apr 2018 16:30:05 -0700 Subject: [PATCH 284/296] Set NETStandardImplicitPackageVersion via dependencies.props --- Directory.Build.targets | 1 + build/dependencies.props | 1 + 2 files changed, 2 insertions(+) diff --git a/Directory.Build.targets b/Directory.Build.targets index 894b1d0cf8..53b3f6e1da 100644 --- a/Directory.Build.targets +++ b/Directory.Build.targets @@ -2,5 +2,6 @@ $(MicrosoftNETCoreApp20PackageVersion) $(MicrosoftNETCoreApp21PackageVersion) + $(NETStandardLibrary20PackageVersion) diff --git a/build/dependencies.props b/build/dependencies.props index e8bb766c67..6d2ff44300 100644 --- a/build/dependencies.props +++ b/build/dependencies.props @@ -18,6 +18,7 @@ 2.0.0 2.1.0-preview3-26413-05 15.6.1 + 2.0.1 4.7.49 2.3.1 2.4.0-beta.1.build3945 From cca342e868a94ea8cd08efcd3159e38f1863b87d Mon Sep 17 00:00:00 2001 From: "ASP.NET CI" Date: Thu, 19 Apr 2018 22:12:58 -0700 Subject: [PATCH 285/296] Update dependencies.props [auto-updated: dependencies] --- build/dependencies.props | 28 ++++++++++++++-------------- korebuild-lock.txt | 4 ++-- 2 files changed, 16 insertions(+), 16 deletions(-) diff --git a/build/dependencies.props b/build/dependencies.props index 6d2ff44300..3468402ee7 100644 --- a/build/dependencies.props +++ b/build/dependencies.props @@ -3,23 +3,23 @@ $(MSBuildAllProjects);$(MSBuildThisFileFullPath) - 2.1.0-preview3-17018 - 2.1.0-preview3-32233 - 2.1.0-preview3-32233 - 2.1.0-preview3-32233 - 2.1.0-preview3-32233 - 2.1.0-preview3-32233 - 2.1.0-preview3-32233 - 2.1.0-preview3-32233 - 2.1.0-preview3-32233 - 2.1.0-preview3-32233 - 2.1.0-preview3-32233 - 2.1.0-preview3-32233 + 2.1.0-rc1-15774 + 2.1.0-rc1-30613 + 2.1.0-rc1-30613 + 2.1.0-rc1-30613 + 2.1.0-rc1-30613 + 2.1.0-rc1-30613 + 2.1.0-rc1-30613 + 2.1.0-rc1-30613 + 2.1.0-rc1-30613 + 2.1.0-rc1-30613 + 2.1.0-rc1-30613 + 2.1.0-rc1-30613 2.0.0 - 2.1.0-preview3-26413-05 + 2.1.0-rc1-26419-02 15.6.1 - 2.0.1 4.7.49 + 2.0.1 2.3.1 2.4.0-beta.1.build3945 diff --git a/korebuild-lock.txt b/korebuild-lock.txt index b419d767b9..9d4ef8c888 100644 --- a/korebuild-lock.txt +++ b/korebuild-lock.txt @@ -1,2 +1,2 @@ -version:2.1.0-preview3-17018 -commithash:af264ca131f212b5ba8aafbc5110fc0fc510a2be +version:2.1.0-rc1-15774 +commithash:ed5ca9de3c652347dbb0158a9a65eff3471d2114 From b019748d3ca586f234ac28a0620543a789d686e8 Mon Sep 17 00:00:00 2001 From: "Nate McMaster (automated)" Date: Mon, 30 Apr 2018 14:51:36 -0700 Subject: [PATCH 286/296] Bump version to 2.1.0-rtm --- version.props | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/version.props b/version.props index e27532787e..b9552451d8 100644 --- a/version.props +++ b/version.props @@ -1,7 +1,7 @@ 2.1.0 - rc1 + rtm $(VersionPrefix) $(VersionPrefix)-$(VersionSuffix)-final t000 From 60f7d1ecf536c0289175cea640f67779916cb867 Mon Sep 17 00:00:00 2001 From: "ASP.NET CI" Date: Fri, 4 May 2018 07:25:36 -0700 Subject: [PATCH 287/296] Update dependencies.props [auto-updated: dependencies] --- build/dependencies.props | 28 ++++++++++++++-------------- korebuild-lock.txt | 4 ++-- 2 files changed, 16 insertions(+), 16 deletions(-) diff --git a/build/dependencies.props b/build/dependencies.props index 3468402ee7..db908c9c35 100644 --- a/build/dependencies.props +++ b/build/dependencies.props @@ -3,23 +3,23 @@ $(MSBuildAllProjects);$(MSBuildThisFileFullPath) - 2.1.0-rc1-15774 - 2.1.0-rc1-30613 - 2.1.0-rc1-30613 - 2.1.0-rc1-30613 - 2.1.0-rc1-30613 - 2.1.0-rc1-30613 - 2.1.0-rc1-30613 - 2.1.0-rc1-30613 - 2.1.0-rc1-30613 - 2.1.0-rc1-30613 - 2.1.0-rc1-30613 - 2.1.0-rc1-30613 + 2.1.0-rtm-15783 + 2.1.0-rtm-30721 + 2.1.0-rtm-30721 + 2.1.0-rtm-30721 + 2.1.0-rtm-30721 + 2.1.0-rtm-30721 + 2.1.0-rtm-30721 + 2.1.0-rtm-30721 + 2.1.0-rtm-30721 + 2.1.0-rtm-30721 + 2.1.0-rtm-30721 + 2.1.0-rtm-30721 2.0.0 - 2.1.0-rc1-26419-02 + 2.1.0-rtm-26502-02 15.6.1 4.7.49 - 2.0.1 + 2.0.3 2.3.1 2.4.0-beta.1.build3945 diff --git a/korebuild-lock.txt b/korebuild-lock.txt index 9d4ef8c888..3673744db9 100644 --- a/korebuild-lock.txt +++ b/korebuild-lock.txt @@ -1,2 +1,2 @@ -version:2.1.0-rc1-15774 -commithash:ed5ca9de3c652347dbb0158a9a65eff3471d2114 +version:2.1.0-rtm-15783 +commithash:5fc2b2f607f542a2ffde11c19825e786fc1a3774 From c2e4c72a32741689f2636f5f2e53d1c81a27e0b6 Mon Sep 17 00:00:00 2001 From: "ASP.NET CI" Date: Tue, 29 May 2018 09:29:07 -0700 Subject: [PATCH 288/296] Update dependencies.props [auto-updated: dependencies] --- build/dependencies.props | 26 +++++++++++++------------- korebuild-lock.txt | 4 ++-- 2 files changed, 15 insertions(+), 15 deletions(-) diff --git a/build/dependencies.props b/build/dependencies.props index db908c9c35..79ae480e38 100644 --- a/build/dependencies.props +++ b/build/dependencies.props @@ -3,20 +3,20 @@ $(MSBuildAllProjects);$(MSBuildThisFileFullPath) - 2.1.0-rtm-15783 - 2.1.0-rtm-30721 - 2.1.0-rtm-30721 - 2.1.0-rtm-30721 - 2.1.0-rtm-30721 - 2.1.0-rtm-30721 - 2.1.0-rtm-30721 - 2.1.0-rtm-30721 - 2.1.0-rtm-30721 - 2.1.0-rtm-30721 - 2.1.0-rtm-30721 - 2.1.0-rtm-30721 + 2.1.1-rtm-15790 + 2.1.0 + 2.1.0 + 2.1.0 + 2.1.0 + 2.1.0 + 2.1.0 + 2.1.0 + 2.1.0 + 2.1.0 + 2.1.0 + 2.1.0 2.0.0 - 2.1.0-rtm-26502-02 + 2.1.0 15.6.1 4.7.49 2.0.3 diff --git a/korebuild-lock.txt b/korebuild-lock.txt index 3673744db9..cd5b409a1e 100644 --- a/korebuild-lock.txt +++ b/korebuild-lock.txt @@ -1,2 +1,2 @@ -version:2.1.0-rtm-15783 -commithash:5fc2b2f607f542a2ffde11c19825e786fc1a3774 +version:2.1.1-rtm-15790 +commithash:274c65868e735f29f4078c1884c61c4371ee1fc0 From 24cf5b1cc86e2c395f7622c1a9a91b209e5ff82b Mon Sep 17 00:00:00 2001 From: Nate McMaster Date: Tue, 5 Jun 2018 09:11:23 -0700 Subject: [PATCH 289/296] Bumping version from 2.1.0 to 2.1.1 --- version.props | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/version.props b/version.props index b9552451d8..669c874829 100644 --- a/version.props +++ b/version.props @@ -1,6 +1,6 @@ - + - 2.1.0 + 2.1.1 rtm $(VersionPrefix) $(VersionPrefix)-$(VersionSuffix)-final From 443fe51456f5b36166e0e34f44044392e99a1217 Mon Sep 17 00:00:00 2001 From: "ASP.NET CI" Date: Tue, 12 Jun 2018 19:10:40 +0000 Subject: [PATCH 290/296] Update dependencies.props [auto-updated: dependencies] --- build/dependencies.props | 24 ++++++++++++------------ korebuild-lock.txt | 4 ++-- 2 files changed, 14 insertions(+), 14 deletions(-) diff --git a/build/dependencies.props b/build/dependencies.props index 79ae480e38..0e34f68b3e 100644 --- a/build/dependencies.props +++ b/build/dependencies.props @@ -3,20 +3,20 @@ $(MSBuildAllProjects);$(MSBuildThisFileFullPath) - 2.1.1-rtm-15790 - 2.1.0 - 2.1.0 - 2.1.0 - 2.1.0 + 2.1.1-rtm-15793 + 2.1.1 + 2.1.1 + 2.1.1 + 2.1.1 2.1.0 - 2.1.0 - 2.1.0 - 2.1.0 - 2.1.0 - 2.1.0 - 2.1.0 + 2.1.1 + 2.1.1 + 2.1.1 + 2.1.1 + 2.1.1 + 2.1.1 2.0.0 - 2.1.0 + 2.1.1 15.6.1 4.7.49 2.0.3 diff --git a/korebuild-lock.txt b/korebuild-lock.txt index cd5b409a1e..bc84e0cd53 100644 --- a/korebuild-lock.txt +++ b/korebuild-lock.txt @@ -1,2 +1,2 @@ -version:2.1.1-rtm-15790 -commithash:274c65868e735f29f4078c1884c61c4371ee1fc0 +version:2.1.1-rtm-15793 +commithash:988313f4b064d6c69fc6f7b845b6384a6af3447a From 9215a8a3eed6b3f25b7e10197fba1164ade2afaa Mon Sep 17 00:00:00 2001 From: Ryan Brandenburg Date: Wed, 13 Jun 2018 10:51:21 -0700 Subject: [PATCH 291/296] Set 2.1 baselines --- .../baseline.netcore.json | 1551 +---------------- 1 file changed, 17 insertions(+), 1534 deletions(-) diff --git a/src/Microsoft.AspNetCore.Antiforgery/baseline.netcore.json b/src/Microsoft.AspNetCore.Antiforgery/baseline.netcore.json index c095a3501b..eaa03254ea 100644 --- a/src/Microsoft.AspNetCore.Antiforgery/baseline.netcore.json +++ b/src/Microsoft.AspNetCore.Antiforgery/baseline.netcore.json @@ -1,5 +1,5 @@ { - "AssemblyIdentity": "Microsoft.AspNetCore.Antiforgery, Version=2.0.2.0, Culture=neutral, PublicKeyToken=adb9793829ddae60", + "AssemblyIdentity": "Microsoft.AspNetCore.Antiforgery, Version=2.1.1.0, Culture=neutral, PublicKeyToken=adb9793829ddae60", "Types": [ { "Name": "Microsoft.Extensions.DependencyInjection.AntiforgeryServiceCollectionExtensions", @@ -324,6 +324,22 @@ ], "Visibility": "Public", "GenericParameter": [] + }, + { + "Kind": "Constructor", + "Name": ".ctor", + "Parameters": [ + { + "Name": "message", + "Type": "System.String" + }, + { + "Name": "innerException", + "Type": "System.Exception" + } + ], + "Visibility": "Public", + "GenericParameter": [] } ], "GenericParameters": [] @@ -435,1539 +451,6 @@ } ], "GenericParameters": [] - }, - { - "Name": "Microsoft.AspNetCore.Antiforgery.Internal.AntiforgeryFeature", - "Visibility": "Public", - "Kind": "Class", - "ImplementedInterfaces": [ - "Microsoft.AspNetCore.Antiforgery.Internal.IAntiforgeryFeature" - ], - "Members": [ - { - "Kind": "Method", - "Name": "get_HaveDeserializedCookieToken", - "Parameters": [], - "ReturnType": "System.Boolean", - "Sealed": true, - "Virtual": true, - "ImplementedInterface": "Microsoft.AspNetCore.Antiforgery.Internal.IAntiforgeryFeature", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "set_HaveDeserializedCookieToken", - "Parameters": [ - { - "Name": "value", - "Type": "System.Boolean" - } - ], - "ReturnType": "System.Void", - "Sealed": true, - "Virtual": true, - "ImplementedInterface": "Microsoft.AspNetCore.Antiforgery.Internal.IAntiforgeryFeature", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "get_CookieToken", - "Parameters": [], - "ReturnType": "Microsoft.AspNetCore.Antiforgery.Internal.AntiforgeryToken", - "Sealed": true, - "Virtual": true, - "ImplementedInterface": "Microsoft.AspNetCore.Antiforgery.Internal.IAntiforgeryFeature", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "set_CookieToken", - "Parameters": [ - { - "Name": "value", - "Type": "Microsoft.AspNetCore.Antiforgery.Internal.AntiforgeryToken" - } - ], - "ReturnType": "System.Void", - "Sealed": true, - "Virtual": true, - "ImplementedInterface": "Microsoft.AspNetCore.Antiforgery.Internal.IAntiforgeryFeature", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "get_HaveDeserializedRequestToken", - "Parameters": [], - "ReturnType": "System.Boolean", - "Sealed": true, - "Virtual": true, - "ImplementedInterface": "Microsoft.AspNetCore.Antiforgery.Internal.IAntiforgeryFeature", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "set_HaveDeserializedRequestToken", - "Parameters": [ - { - "Name": "value", - "Type": "System.Boolean" - } - ], - "ReturnType": "System.Void", - "Sealed": true, - "Virtual": true, - "ImplementedInterface": "Microsoft.AspNetCore.Antiforgery.Internal.IAntiforgeryFeature", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "get_RequestToken", - "Parameters": [], - "ReturnType": "Microsoft.AspNetCore.Antiforgery.Internal.AntiforgeryToken", - "Sealed": true, - "Virtual": true, - "ImplementedInterface": "Microsoft.AspNetCore.Antiforgery.Internal.IAntiforgeryFeature", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "set_RequestToken", - "Parameters": [ - { - "Name": "value", - "Type": "Microsoft.AspNetCore.Antiforgery.Internal.AntiforgeryToken" - } - ], - "ReturnType": "System.Void", - "Sealed": true, - "Virtual": true, - "ImplementedInterface": "Microsoft.AspNetCore.Antiforgery.Internal.IAntiforgeryFeature", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "get_HaveGeneratedNewCookieToken", - "Parameters": [], - "ReturnType": "System.Boolean", - "Sealed": true, - "Virtual": true, - "ImplementedInterface": "Microsoft.AspNetCore.Antiforgery.Internal.IAntiforgeryFeature", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "set_HaveGeneratedNewCookieToken", - "Parameters": [ - { - "Name": "value", - "Type": "System.Boolean" - } - ], - "ReturnType": "System.Void", - "Sealed": true, - "Virtual": true, - "ImplementedInterface": "Microsoft.AspNetCore.Antiforgery.Internal.IAntiforgeryFeature", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "get_NewCookieToken", - "Parameters": [], - "ReturnType": "Microsoft.AspNetCore.Antiforgery.Internal.AntiforgeryToken", - "Sealed": true, - "Virtual": true, - "ImplementedInterface": "Microsoft.AspNetCore.Antiforgery.Internal.IAntiforgeryFeature", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "set_NewCookieToken", - "Parameters": [ - { - "Name": "value", - "Type": "Microsoft.AspNetCore.Antiforgery.Internal.AntiforgeryToken" - } - ], - "ReturnType": "System.Void", - "Sealed": true, - "Virtual": true, - "ImplementedInterface": "Microsoft.AspNetCore.Antiforgery.Internal.IAntiforgeryFeature", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "get_NewCookieTokenString", - "Parameters": [], - "ReturnType": "System.String", - "Sealed": true, - "Virtual": true, - "ImplementedInterface": "Microsoft.AspNetCore.Antiforgery.Internal.IAntiforgeryFeature", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "set_NewCookieTokenString", - "Parameters": [ - { - "Name": "value", - "Type": "System.String" - } - ], - "ReturnType": "System.Void", - "Sealed": true, - "Virtual": true, - "ImplementedInterface": "Microsoft.AspNetCore.Antiforgery.Internal.IAntiforgeryFeature", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "get_NewRequestToken", - "Parameters": [], - "ReturnType": "Microsoft.AspNetCore.Antiforgery.Internal.AntiforgeryToken", - "Sealed": true, - "Virtual": true, - "ImplementedInterface": "Microsoft.AspNetCore.Antiforgery.Internal.IAntiforgeryFeature", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "set_NewRequestToken", - "Parameters": [ - { - "Name": "value", - "Type": "Microsoft.AspNetCore.Antiforgery.Internal.AntiforgeryToken" - } - ], - "ReturnType": "System.Void", - "Sealed": true, - "Virtual": true, - "ImplementedInterface": "Microsoft.AspNetCore.Antiforgery.Internal.IAntiforgeryFeature", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "get_NewRequestTokenString", - "Parameters": [], - "ReturnType": "System.String", - "Sealed": true, - "Virtual": true, - "ImplementedInterface": "Microsoft.AspNetCore.Antiforgery.Internal.IAntiforgeryFeature", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "set_NewRequestTokenString", - "Parameters": [ - { - "Name": "value", - "Type": "System.String" - } - ], - "ReturnType": "System.Void", - "Sealed": true, - "Virtual": true, - "ImplementedInterface": "Microsoft.AspNetCore.Antiforgery.Internal.IAntiforgeryFeature", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "get_HaveStoredNewCookieToken", - "Parameters": [], - "ReturnType": "System.Boolean", - "Sealed": true, - "Virtual": true, - "ImplementedInterface": "Microsoft.AspNetCore.Antiforgery.Internal.IAntiforgeryFeature", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "set_HaveStoredNewCookieToken", - "Parameters": [ - { - "Name": "value", - "Type": "System.Boolean" - } - ], - "ReturnType": "System.Void", - "Sealed": true, - "Virtual": true, - "ImplementedInterface": "Microsoft.AspNetCore.Antiforgery.Internal.IAntiforgeryFeature", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Constructor", - "Name": ".ctor", - "Parameters": [], - "Visibility": "Public", - "GenericParameter": [] - } - ], - "GenericParameters": [] - }, - { - "Name": "Microsoft.AspNetCore.Antiforgery.Internal.AntiforgeryOptionsSetup", - "Visibility": "Public", - "Kind": "Class", - "BaseType": "Microsoft.Extensions.Options.ConfigureOptions", - "ImplementedInterfaces": [], - "Members": [ - { - "Kind": "Method", - "Name": "ConfigureOptions", - "Parameters": [ - { - "Name": "options", - "Type": "Microsoft.AspNetCore.Antiforgery.AntiforgeryOptions" - }, - { - "Name": "dataProtectionOptions", - "Type": "Microsoft.AspNetCore.DataProtection.DataProtectionOptions" - } - ], - "ReturnType": "System.Void", - "Static": true, - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Constructor", - "Name": ".ctor", - "Parameters": [ - { - "Name": "dataProtectionOptionsAccessor", - "Type": "Microsoft.Extensions.Options.IOptions" - } - ], - "Visibility": "Public", - "GenericParameter": [] - } - ], - "GenericParameters": [] - }, - { - "Name": "Microsoft.AspNetCore.Antiforgery.Internal.AntiforgerySerializationContext", - "Visibility": "Public", - "Kind": "Class", - "ImplementedInterfaces": [], - "Members": [ - { - "Kind": "Method", - "Name": "get_Stream", - "Parameters": [], - "ReturnType": "System.IO.MemoryStream", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "get_Reader", - "Parameters": [], - "ReturnType": "System.IO.BinaryReader", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "get_Writer", - "Parameters": [], - "ReturnType": "System.IO.BinaryWriter", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "get_Sha256", - "Parameters": [], - "ReturnType": "System.Security.Cryptography.SHA256", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "GetChars", - "Parameters": [ - { - "Name": "count", - "Type": "System.Int32" - } - ], - "ReturnType": "System.Char[]", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "Reset", - "Parameters": [], - "ReturnType": "System.Void", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Constructor", - "Name": ".ctor", - "Parameters": [], - "Visibility": "Public", - "GenericParameter": [] - } - ], - "GenericParameters": [] - }, - { - "Name": "Microsoft.AspNetCore.Antiforgery.Internal.AntiforgerySerializationContextPooledObjectPolicy", - "Visibility": "Public", - "Kind": "Class", - "ImplementedInterfaces": [ - "Microsoft.Extensions.ObjectPool.IPooledObjectPolicy" - ], - "Members": [ - { - "Kind": "Method", - "Name": "Create", - "Parameters": [], - "ReturnType": "Microsoft.AspNetCore.Antiforgery.Internal.AntiforgerySerializationContext", - "Sealed": true, - "Virtual": true, - "ImplementedInterface": "Microsoft.Extensions.ObjectPool.IPooledObjectPolicy", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "Return", - "Parameters": [ - { - "Name": "obj", - "Type": "Microsoft.AspNetCore.Antiforgery.Internal.AntiforgerySerializationContext" - } - ], - "ReturnType": "System.Boolean", - "Sealed": true, - "Virtual": true, - "ImplementedInterface": "Microsoft.Extensions.ObjectPool.IPooledObjectPolicy", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Constructor", - "Name": ".ctor", - "Parameters": [], - "Visibility": "Public", - "GenericParameter": [] - } - ], - "GenericParameters": [] - }, - { - "Name": "Microsoft.AspNetCore.Antiforgery.Internal.AntiforgeryToken", - "Visibility": "Public", - "Kind": "Class", - "Sealed": true, - "ImplementedInterfaces": [], - "Members": [ - { - "Kind": "Method", - "Name": "get_AdditionalData", - "Parameters": [], - "ReturnType": "System.String", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "set_AdditionalData", - "Parameters": [ - { - "Name": "value", - "Type": "System.String" - } - ], - "ReturnType": "System.Void", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "get_ClaimUid", - "Parameters": [], - "ReturnType": "Microsoft.AspNetCore.Antiforgery.Internal.BinaryBlob", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "set_ClaimUid", - "Parameters": [ - { - "Name": "value", - "Type": "Microsoft.AspNetCore.Antiforgery.Internal.BinaryBlob" - } - ], - "ReturnType": "System.Void", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "get_IsCookieToken", - "Parameters": [], - "ReturnType": "System.Boolean", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "set_IsCookieToken", - "Parameters": [ - { - "Name": "value", - "Type": "System.Boolean" - } - ], - "ReturnType": "System.Void", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "get_SecurityToken", - "Parameters": [], - "ReturnType": "Microsoft.AspNetCore.Antiforgery.Internal.BinaryBlob", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "set_SecurityToken", - "Parameters": [ - { - "Name": "value", - "Type": "Microsoft.AspNetCore.Antiforgery.Internal.BinaryBlob" - } - ], - "ReturnType": "System.Void", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "get_Username", - "Parameters": [], - "ReturnType": "System.String", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "set_Username", - "Parameters": [ - { - "Name": "value", - "Type": "System.String" - } - ], - "ReturnType": "System.Void", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Constructor", - "Name": ".ctor", - "Parameters": [], - "Visibility": "Public", - "GenericParameter": [] - } - ], - "GenericParameters": [] - }, - { - "Name": "Microsoft.AspNetCore.Antiforgery.Internal.BinaryBlob", - "Visibility": "Public", - "Kind": "Class", - "Sealed": true, - "ImplementedInterfaces": [ - "System.IEquatable" - ], - "Members": [ - { - "Kind": "Method", - "Name": "get_BitLength", - "Parameters": [], - "ReturnType": "System.Int32", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "Equals", - "Parameters": [ - { - "Name": "obj", - "Type": "System.Object" - } - ], - "ReturnType": "System.Boolean", - "Virtual": true, - "Override": true, - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "Equals", - "Parameters": [ - { - "Name": "other", - "Type": "Microsoft.AspNetCore.Antiforgery.Internal.BinaryBlob" - } - ], - "ReturnType": "System.Boolean", - "Sealed": true, - "Virtual": true, - "ImplementedInterface": "System.IEquatable", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "GetData", - "Parameters": [], - "ReturnType": "System.Byte[]", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "GetHashCode", - "Parameters": [], - "ReturnType": "System.Int32", - "Virtual": true, - "Override": true, - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Constructor", - "Name": ".ctor", - "Parameters": [ - { - "Name": "bitLength", - "Type": "System.Int32" - } - ], - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Constructor", - "Name": ".ctor", - "Parameters": [ - { - "Name": "bitLength", - "Type": "System.Int32" - }, - { - "Name": "data", - "Type": "System.Byte[]" - } - ], - "Visibility": "Public", - "GenericParameter": [] - } - ], - "GenericParameters": [] - }, - { - "Name": "Microsoft.AspNetCore.Antiforgery.Internal.CryptographyAlgorithms", - "Visibility": "Public", - "Kind": "Class", - "Abstract": true, - "Static": true, - "Sealed": true, - "ImplementedInterfaces": [], - "Members": [ - { - "Kind": "Method", - "Name": "CreateSHA256", - "Parameters": [], - "ReturnType": "System.Security.Cryptography.SHA256", - "Static": true, - "Visibility": "Public", - "GenericParameter": [] - } - ], - "GenericParameters": [] - }, - { - "Name": "Microsoft.AspNetCore.Antiforgery.Internal.DefaultAntiforgery", - "Visibility": "Public", - "Kind": "Class", - "ImplementedInterfaces": [ - "Microsoft.AspNetCore.Antiforgery.IAntiforgery" - ], - "Members": [ - { - "Kind": "Method", - "Name": "GetAndStoreTokens", - "Parameters": [ - { - "Name": "httpContext", - "Type": "Microsoft.AspNetCore.Http.HttpContext" - } - ], - "ReturnType": "Microsoft.AspNetCore.Antiforgery.AntiforgeryTokenSet", - "Sealed": true, - "Virtual": true, - "ImplementedInterface": "Microsoft.AspNetCore.Antiforgery.IAntiforgery", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "GetTokens", - "Parameters": [ - { - "Name": "httpContext", - "Type": "Microsoft.AspNetCore.Http.HttpContext" - } - ], - "ReturnType": "Microsoft.AspNetCore.Antiforgery.AntiforgeryTokenSet", - "Sealed": true, - "Virtual": true, - "ImplementedInterface": "Microsoft.AspNetCore.Antiforgery.IAntiforgery", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "IsRequestValidAsync", - "Parameters": [ - { - "Name": "httpContext", - "Type": "Microsoft.AspNetCore.Http.HttpContext" - } - ], - "ReturnType": "System.Threading.Tasks.Task", - "Sealed": true, - "Virtual": true, - "ImplementedInterface": "Microsoft.AspNetCore.Antiforgery.IAntiforgery", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "ValidateRequestAsync", - "Parameters": [ - { - "Name": "httpContext", - "Type": "Microsoft.AspNetCore.Http.HttpContext" - } - ], - "ReturnType": "System.Threading.Tasks.Task", - "Sealed": true, - "Virtual": true, - "ImplementedInterface": "Microsoft.AspNetCore.Antiforgery.IAntiforgery", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "SetCookieTokenAndHeader", - "Parameters": [ - { - "Name": "httpContext", - "Type": "Microsoft.AspNetCore.Http.HttpContext" - } - ], - "ReturnType": "System.Void", - "Sealed": true, - "Virtual": true, - "ImplementedInterface": "Microsoft.AspNetCore.Antiforgery.IAntiforgery", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "SetDoNotCacheHeaders", - "Parameters": [ - { - "Name": "httpContext", - "Type": "Microsoft.AspNetCore.Http.HttpContext" - } - ], - "ReturnType": "System.Void", - "Virtual": true, - "Visibility": "Protected", - "GenericParameter": [] - }, - { - "Kind": "Constructor", - "Name": ".ctor", - "Parameters": [ - { - "Name": "antiforgeryOptionsAccessor", - "Type": "Microsoft.Extensions.Options.IOptions" - }, - { - "Name": "tokenGenerator", - "Type": "Microsoft.AspNetCore.Antiforgery.Internal.IAntiforgeryTokenGenerator" - }, - { - "Name": "tokenSerializer", - "Type": "Microsoft.AspNetCore.Antiforgery.Internal.IAntiforgeryTokenSerializer" - }, - { - "Name": "tokenStore", - "Type": "Microsoft.AspNetCore.Antiforgery.Internal.IAntiforgeryTokenStore" - }, - { - "Name": "loggerFactory", - "Type": "Microsoft.Extensions.Logging.ILoggerFactory" - } - ], - "Visibility": "Public", - "GenericParameter": [] - } - ], - "GenericParameters": [] - }, - { - "Name": "Microsoft.AspNetCore.Antiforgery.Internal.DefaultAntiforgeryAdditionalDataProvider", - "Visibility": "Public", - "Kind": "Class", - "ImplementedInterfaces": [ - "Microsoft.AspNetCore.Antiforgery.IAntiforgeryAdditionalDataProvider" - ], - "Members": [ - { - "Kind": "Method", - "Name": "GetAdditionalData", - "Parameters": [ - { - "Name": "context", - "Type": "Microsoft.AspNetCore.Http.HttpContext" - } - ], - "ReturnType": "System.String", - "Virtual": true, - "ImplementedInterface": "Microsoft.AspNetCore.Antiforgery.IAntiforgeryAdditionalDataProvider", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "ValidateAdditionalData", - "Parameters": [ - { - "Name": "context", - "Type": "Microsoft.AspNetCore.Http.HttpContext" - }, - { - "Name": "additionalData", - "Type": "System.String" - } - ], - "ReturnType": "System.Boolean", - "Virtual": true, - "ImplementedInterface": "Microsoft.AspNetCore.Antiforgery.IAntiforgeryAdditionalDataProvider", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Constructor", - "Name": ".ctor", - "Parameters": [], - "Visibility": "Public", - "GenericParameter": [] - } - ], - "GenericParameters": [] - }, - { - "Name": "Microsoft.AspNetCore.Antiforgery.Internal.DefaultAntiforgeryTokenGenerator", - "Visibility": "Public", - "Kind": "Class", - "ImplementedInterfaces": [ - "Microsoft.AspNetCore.Antiforgery.Internal.IAntiforgeryTokenGenerator" - ], - "Members": [ - { - "Kind": "Method", - "Name": "GenerateCookieToken", - "Parameters": [], - "ReturnType": "Microsoft.AspNetCore.Antiforgery.Internal.AntiforgeryToken", - "Sealed": true, - "Virtual": true, - "ImplementedInterface": "Microsoft.AspNetCore.Antiforgery.Internal.IAntiforgeryTokenGenerator", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "GenerateRequestToken", - "Parameters": [ - { - "Name": "httpContext", - "Type": "Microsoft.AspNetCore.Http.HttpContext" - }, - { - "Name": "cookieToken", - "Type": "Microsoft.AspNetCore.Antiforgery.Internal.AntiforgeryToken" - } - ], - "ReturnType": "Microsoft.AspNetCore.Antiforgery.Internal.AntiforgeryToken", - "Sealed": true, - "Virtual": true, - "ImplementedInterface": "Microsoft.AspNetCore.Antiforgery.Internal.IAntiforgeryTokenGenerator", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "IsCookieTokenValid", - "Parameters": [ - { - "Name": "cookieToken", - "Type": "Microsoft.AspNetCore.Antiforgery.Internal.AntiforgeryToken" - } - ], - "ReturnType": "System.Boolean", - "Sealed": true, - "Virtual": true, - "ImplementedInterface": "Microsoft.AspNetCore.Antiforgery.Internal.IAntiforgeryTokenGenerator", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "TryValidateTokenSet", - "Parameters": [ - { - "Name": "httpContext", - "Type": "Microsoft.AspNetCore.Http.HttpContext" - }, - { - "Name": "cookieToken", - "Type": "Microsoft.AspNetCore.Antiforgery.Internal.AntiforgeryToken" - }, - { - "Name": "requestToken", - "Type": "Microsoft.AspNetCore.Antiforgery.Internal.AntiforgeryToken" - }, - { - "Name": "message", - "Type": "System.String", - "Direction": "Out" - } - ], - "ReturnType": "System.Boolean", - "Sealed": true, - "Virtual": true, - "ImplementedInterface": "Microsoft.AspNetCore.Antiforgery.Internal.IAntiforgeryTokenGenerator", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Constructor", - "Name": ".ctor", - "Parameters": [ - { - "Name": "claimUidExtractor", - "Type": "Microsoft.AspNetCore.Antiforgery.Internal.IClaimUidExtractor" - }, - { - "Name": "additionalDataProvider", - "Type": "Microsoft.AspNetCore.Antiforgery.IAntiforgeryAdditionalDataProvider" - } - ], - "Visibility": "Public", - "GenericParameter": [] - } - ], - "GenericParameters": [] - }, - { - "Name": "Microsoft.AspNetCore.Antiforgery.Internal.DefaultAntiforgeryTokenSerializer", - "Visibility": "Public", - "Kind": "Class", - "ImplementedInterfaces": [ - "Microsoft.AspNetCore.Antiforgery.Internal.IAntiforgeryTokenSerializer" - ], - "Members": [ - { - "Kind": "Method", - "Name": "Deserialize", - "Parameters": [ - { - "Name": "serializedToken", - "Type": "System.String" - } - ], - "ReturnType": "Microsoft.AspNetCore.Antiforgery.Internal.AntiforgeryToken", - "Sealed": true, - "Virtual": true, - "ImplementedInterface": "Microsoft.AspNetCore.Antiforgery.Internal.IAntiforgeryTokenSerializer", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "Serialize", - "Parameters": [ - { - "Name": "token", - "Type": "Microsoft.AspNetCore.Antiforgery.Internal.AntiforgeryToken" - } - ], - "ReturnType": "System.String", - "Sealed": true, - "Virtual": true, - "ImplementedInterface": "Microsoft.AspNetCore.Antiforgery.Internal.IAntiforgeryTokenSerializer", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Constructor", - "Name": ".ctor", - "Parameters": [ - { - "Name": "provider", - "Type": "Microsoft.AspNetCore.DataProtection.IDataProtectionProvider" - }, - { - "Name": "pool", - "Type": "Microsoft.Extensions.ObjectPool.ObjectPool" - } - ], - "Visibility": "Public", - "GenericParameter": [] - } - ], - "GenericParameters": [] - }, - { - "Name": "Microsoft.AspNetCore.Antiforgery.Internal.DefaultAntiforgeryTokenStore", - "Visibility": "Public", - "Kind": "Class", - "ImplementedInterfaces": [ - "Microsoft.AspNetCore.Antiforgery.Internal.IAntiforgeryTokenStore" - ], - "Members": [ - { - "Kind": "Method", - "Name": "GetCookieToken", - "Parameters": [ - { - "Name": "httpContext", - "Type": "Microsoft.AspNetCore.Http.HttpContext" - } - ], - "ReturnType": "System.String", - "Sealed": true, - "Virtual": true, - "ImplementedInterface": "Microsoft.AspNetCore.Antiforgery.Internal.IAntiforgeryTokenStore", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "GetRequestTokensAsync", - "Parameters": [ - { - "Name": "httpContext", - "Type": "Microsoft.AspNetCore.Http.HttpContext" - } - ], - "ReturnType": "System.Threading.Tasks.Task", - "Sealed": true, - "Virtual": true, - "ImplementedInterface": "Microsoft.AspNetCore.Antiforgery.Internal.IAntiforgeryTokenStore", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "SaveCookieToken", - "Parameters": [ - { - "Name": "httpContext", - "Type": "Microsoft.AspNetCore.Http.HttpContext" - }, - { - "Name": "token", - "Type": "System.String" - } - ], - "ReturnType": "System.Void", - "Sealed": true, - "Virtual": true, - "ImplementedInterface": "Microsoft.AspNetCore.Antiforgery.Internal.IAntiforgeryTokenStore", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Constructor", - "Name": ".ctor", - "Parameters": [ - { - "Name": "optionsAccessor", - "Type": "Microsoft.Extensions.Options.IOptions" - } - ], - "Visibility": "Public", - "GenericParameter": [] - } - ], - "GenericParameters": [] - }, - { - "Name": "Microsoft.AspNetCore.Antiforgery.Internal.DefaultClaimUidExtractor", - "Visibility": "Public", - "Kind": "Class", - "ImplementedInterfaces": [ - "Microsoft.AspNetCore.Antiforgery.Internal.IClaimUidExtractor" - ], - "Members": [ - { - "Kind": "Method", - "Name": "ExtractClaimUid", - "Parameters": [ - { - "Name": "claimsPrincipal", - "Type": "System.Security.Claims.ClaimsPrincipal" - } - ], - "ReturnType": "System.String", - "Sealed": true, - "Virtual": true, - "ImplementedInterface": "Microsoft.AspNetCore.Antiforgery.Internal.IClaimUidExtractor", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "GetUniqueIdentifierParameters", - "Parameters": [ - { - "Name": "claimsIdentities", - "Type": "System.Collections.Generic.IEnumerable" - } - ], - "ReturnType": "System.Collections.Generic.IList", - "Static": true, - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Constructor", - "Name": ".ctor", - "Parameters": [ - { - "Name": "pool", - "Type": "Microsoft.Extensions.ObjectPool.ObjectPool" - } - ], - "Visibility": "Public", - "GenericParameter": [] - } - ], - "GenericParameters": [] - }, - { - "Name": "Microsoft.AspNetCore.Antiforgery.Internal.IAntiforgeryFeature", - "Visibility": "Public", - "Kind": "Interface", - "Abstract": true, - "ImplementedInterfaces": [], - "Members": [ - { - "Kind": "Method", - "Name": "get_CookieToken", - "Parameters": [], - "ReturnType": "Microsoft.AspNetCore.Antiforgery.Internal.AntiforgeryToken", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "set_CookieToken", - "Parameters": [ - { - "Name": "value", - "Type": "Microsoft.AspNetCore.Antiforgery.Internal.AntiforgeryToken" - } - ], - "ReturnType": "System.Void", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "get_HaveDeserializedCookieToken", - "Parameters": [], - "ReturnType": "System.Boolean", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "set_HaveDeserializedCookieToken", - "Parameters": [ - { - "Name": "value", - "Type": "System.Boolean" - } - ], - "ReturnType": "System.Void", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "get_HaveDeserializedRequestToken", - "Parameters": [], - "ReturnType": "System.Boolean", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "set_HaveDeserializedRequestToken", - "Parameters": [ - { - "Name": "value", - "Type": "System.Boolean" - } - ], - "ReturnType": "System.Void", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "get_HaveGeneratedNewCookieToken", - "Parameters": [], - "ReturnType": "System.Boolean", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "set_HaveGeneratedNewCookieToken", - "Parameters": [ - { - "Name": "value", - "Type": "System.Boolean" - } - ], - "ReturnType": "System.Void", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "get_HaveStoredNewCookieToken", - "Parameters": [], - "ReturnType": "System.Boolean", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "set_HaveStoredNewCookieToken", - "Parameters": [ - { - "Name": "value", - "Type": "System.Boolean" - } - ], - "ReturnType": "System.Void", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "get_NewCookieToken", - "Parameters": [], - "ReturnType": "Microsoft.AspNetCore.Antiforgery.Internal.AntiforgeryToken", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "set_NewCookieToken", - "Parameters": [ - { - "Name": "value", - "Type": "Microsoft.AspNetCore.Antiforgery.Internal.AntiforgeryToken" - } - ], - "ReturnType": "System.Void", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "get_NewCookieTokenString", - "Parameters": [], - "ReturnType": "System.String", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "set_NewCookieTokenString", - "Parameters": [ - { - "Name": "value", - "Type": "System.String" - } - ], - "ReturnType": "System.Void", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "get_NewRequestToken", - "Parameters": [], - "ReturnType": "Microsoft.AspNetCore.Antiforgery.Internal.AntiforgeryToken", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "set_NewRequestToken", - "Parameters": [ - { - "Name": "value", - "Type": "Microsoft.AspNetCore.Antiforgery.Internal.AntiforgeryToken" - } - ], - "ReturnType": "System.Void", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "get_NewRequestTokenString", - "Parameters": [], - "ReturnType": "System.String", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "set_NewRequestTokenString", - "Parameters": [ - { - "Name": "value", - "Type": "System.String" - } - ], - "ReturnType": "System.Void", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "get_RequestToken", - "Parameters": [], - "ReturnType": "Microsoft.AspNetCore.Antiforgery.Internal.AntiforgeryToken", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "set_RequestToken", - "Parameters": [ - { - "Name": "value", - "Type": "Microsoft.AspNetCore.Antiforgery.Internal.AntiforgeryToken" - } - ], - "ReturnType": "System.Void", - "GenericParameter": [] - } - ], - "GenericParameters": [] - }, - { - "Name": "Microsoft.AspNetCore.Antiforgery.Internal.IAntiforgeryTokenGenerator", - "Visibility": "Public", - "Kind": "Interface", - "Abstract": true, - "ImplementedInterfaces": [], - "Members": [ - { - "Kind": "Method", - "Name": "GenerateCookieToken", - "Parameters": [], - "ReturnType": "Microsoft.AspNetCore.Antiforgery.Internal.AntiforgeryToken", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "GenerateRequestToken", - "Parameters": [ - { - "Name": "httpContext", - "Type": "Microsoft.AspNetCore.Http.HttpContext" - }, - { - "Name": "cookieToken", - "Type": "Microsoft.AspNetCore.Antiforgery.Internal.AntiforgeryToken" - } - ], - "ReturnType": "Microsoft.AspNetCore.Antiforgery.Internal.AntiforgeryToken", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "IsCookieTokenValid", - "Parameters": [ - { - "Name": "cookieToken", - "Type": "Microsoft.AspNetCore.Antiforgery.Internal.AntiforgeryToken" - } - ], - "ReturnType": "System.Boolean", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "TryValidateTokenSet", - "Parameters": [ - { - "Name": "httpContext", - "Type": "Microsoft.AspNetCore.Http.HttpContext" - }, - { - "Name": "cookieToken", - "Type": "Microsoft.AspNetCore.Antiforgery.Internal.AntiforgeryToken" - }, - { - "Name": "requestToken", - "Type": "Microsoft.AspNetCore.Antiforgery.Internal.AntiforgeryToken" - }, - { - "Name": "message", - "Type": "System.String", - "Direction": "Out" - } - ], - "ReturnType": "System.Boolean", - "GenericParameter": [] - } - ], - "GenericParameters": [] - }, - { - "Name": "Microsoft.AspNetCore.Antiforgery.Internal.IAntiforgeryTokenSerializer", - "Visibility": "Public", - "Kind": "Interface", - "Abstract": true, - "ImplementedInterfaces": [], - "Members": [ - { - "Kind": "Method", - "Name": "Deserialize", - "Parameters": [ - { - "Name": "serializedToken", - "Type": "System.String" - } - ], - "ReturnType": "Microsoft.AspNetCore.Antiforgery.Internal.AntiforgeryToken", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "Serialize", - "Parameters": [ - { - "Name": "token", - "Type": "Microsoft.AspNetCore.Antiforgery.Internal.AntiforgeryToken" - } - ], - "ReturnType": "System.String", - "GenericParameter": [] - } - ], - "GenericParameters": [] - }, - { - "Name": "Microsoft.AspNetCore.Antiforgery.Internal.IAntiforgeryTokenStore", - "Visibility": "Public", - "Kind": "Interface", - "Abstract": true, - "ImplementedInterfaces": [], - "Members": [ - { - "Kind": "Method", - "Name": "GetCookieToken", - "Parameters": [ - { - "Name": "httpContext", - "Type": "Microsoft.AspNetCore.Http.HttpContext" - } - ], - "ReturnType": "System.String", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "GetRequestTokensAsync", - "Parameters": [ - { - "Name": "httpContext", - "Type": "Microsoft.AspNetCore.Http.HttpContext" - } - ], - "ReturnType": "System.Threading.Tasks.Task", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "SaveCookieToken", - "Parameters": [ - { - "Name": "httpContext", - "Type": "Microsoft.AspNetCore.Http.HttpContext" - }, - { - "Name": "token", - "Type": "System.String" - } - ], - "ReturnType": "System.Void", - "GenericParameter": [] - } - ], - "GenericParameters": [] - }, - { - "Name": "Microsoft.AspNetCore.Antiforgery.Internal.IClaimUidExtractor", - "Visibility": "Public", - "Kind": "Interface", - "Abstract": true, - "ImplementedInterfaces": [], - "Members": [ - { - "Kind": "Method", - "Name": "ExtractClaimUid", - "Parameters": [ - { - "Name": "claimsPrincipal", - "Type": "System.Security.Claims.ClaimsPrincipal" - } - ], - "ReturnType": "System.String", - "GenericParameter": [] - } - ], - "GenericParameters": [] } ] } \ No newline at end of file From c26db4bb8f276c6582c3beae561342c1126eee83 Mon Sep 17 00:00:00 2001 From: Nate McMaster Date: Wed, 27 Jun 2018 13:39:40 -0700 Subject: [PATCH 292/296] Bumping version from 2.1.1 to 2.1.2 --- version.props | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/version.props b/version.props index 669c874829..478dfd16ed 100644 --- a/version.props +++ b/version.props @@ -1,6 +1,6 @@  - 2.1.1 + 2.1.2 rtm $(VersionPrefix) $(VersionPrefix)-$(VersionSuffix)-final From 7d7fcbc0f83cfac2c6a9d17fffc852f45b8c3dd4 Mon Sep 17 00:00:00 2001 From: Nate McMaster Date: Wed, 11 Jul 2018 15:06:22 -0700 Subject: [PATCH 293/296] Reverting version from 2.1.2 back to 2.1.1 As a result of changing the way we apply servicing updates to aspnet core, this repo did not need the version bump because there are no planned product changes in this repo. --- version.props | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/version.props b/version.props index 478dfd16ed..669c874829 100644 --- a/version.props +++ b/version.props @@ -1,6 +1,6 @@  - 2.1.2 + 2.1.1 rtm $(VersionPrefix) $(VersionPrefix)-$(VersionSuffix)-final From 1608f269212fe43a4597617dfecdcb7031dc511a Mon Sep 17 00:00:00 2001 From: Nate McMaster Date: Wed, 11 Jul 2018 18:47:27 -0700 Subject: [PATCH 294/296] Updating dependencies to 2.1.2 and adding a section for pinned variable versions --- build/dependencies.props | 13 ++++++++++--- korebuild-lock.txt | 4 ++-- 2 files changed, 12 insertions(+), 5 deletions(-) diff --git a/build/dependencies.props b/build/dependencies.props index 0e34f68b3e..504ff91600 100644 --- a/build/dependencies.props +++ b/build/dependencies.props @@ -2,8 +2,10 @@ $(MSBuildAllProjects);$(MSBuildThisFileFullPath) - - 2.1.1-rtm-15793 + + + + 2.1.3-rtm-15802 2.1.1 2.1.1 2.1.1 @@ -16,12 +18,17 @@ 2.1.1 2.1.1 2.0.0 - 2.1.1 + 2.1.2 15.6.1 4.7.49 2.0.3 2.3.1 2.4.0-beta.1.build3945 + + + + + diff --git a/korebuild-lock.txt b/korebuild-lock.txt index bc84e0cd53..251c227c83 100644 --- a/korebuild-lock.txt +++ b/korebuild-lock.txt @@ -1,2 +1,2 @@ -version:2.1.1-rtm-15793 -commithash:988313f4b064d6c69fc6f7b845b6384a6af3447a +version:2.1.3-rtm-15802 +commithash:a7c08b45b440a7d2058a0aa1eaa3eb6ba811976a From 93b496090e65a66bba27b67b1e22ff6adec8effc Mon Sep 17 00:00:00 2001 From: Nate McMaster Date: Thu, 12 Jul 2018 11:43:02 -0700 Subject: [PATCH 295/296] Pin version variables to the ASP.NET Core 2.1.2 baseline This reverts our previous policy of cascading versions on all servicing updates. This moves variables into the 'pinned' section, and points them to the latest stable release (versions that were used at the time of the 2.1.2 release). --- build/dependencies.props | 29 +++++++++++++++-------------- 1 file changed, 15 insertions(+), 14 deletions(-) diff --git a/build/dependencies.props b/build/dependencies.props index 504ff91600..733502bfdc 100644 --- a/build/dependencies.props +++ b/build/dependencies.props @@ -4,19 +4,8 @@ - + 2.1.3-rtm-15802 - 2.1.1 - 2.1.1 - 2.1.1 - 2.1.1 - 2.1.0 - 2.1.1 - 2.1.1 - 2.1.1 - 2.1.1 - 2.1.1 - 2.1.1 2.0.0 2.1.2 15.6.1 @@ -30,5 +19,17 @@ - - + + 2.1.1 + 2.1.1 + 2.1.1 + 2.1.1 + 2.1.0 + 2.1.1 + 2.1.1 + 2.1.1 + 2.1.1 + 2.1.1 + 2.1.1 + + \ No newline at end of file From 42a93c8153ac988cff4b32789b592a0f4cba9ef8 Mon Sep 17 00:00:00 2001 From: Ryan Brandenburg Date: Wed, 21 Nov 2018 15:01:46 -0800 Subject: [PATCH 296/296] Reorganize source code in preparation to move into aspnet/AspNetCore Prior to reorganization, this source code was found in https://github.com/aspnet/Antiforgery/tree/93b496090e65a66bba27b67b1e22ff6adec8effc --- .appveyor.yml | 17 -- .gitattributes | 51 ---- .github/ISSUE_TEMPLATE.md | 3 - .travis.yml | 27 -- CONTRIBUTING.md | 4 - LICENSE.txt | 14 -- NuGet.config | 7 - build.cmd | 2 - build.sh | 8 - korebuild-lock.txt | 2 - korebuild.json | 4 - run.cmd | 2 - run.ps1 | 196 --------------- run.sh | 231 ------------------ .gitignore => src/Antiforgery/.gitignore | 0 .../Antiforgery/Antiforgery.sln | 0 .../Antiforgery/Directory.Build.props | 0 .../Antiforgery/Directory.Build.targets | 0 .../Antiforgery/NuGetPackageVerifier.json | 0 README.md => src/Antiforgery/README.md | 0 {build => src/Antiforgery/build}/Key.snk | Bin .../Antiforgery/build}/dependencies.props | 0 {build => src/Antiforgery/build}/repo.props | 0 .../Antiforgery/build}/sources.props | 0 .../AntiforgeryOptions.cs | 0 .../AntiforgeryServiceCollectionExtensions.cs | 0 .../AntiforgeryTokenSet.cs | 0 .../AntiforgeryValidationException.cs | 0 .../IAntiforgery.cs | 0 .../IAntiforgeryAdditionalDataProvider.cs | 0 .../Internal/AntiforgeryFeature.cs | 0 .../Internal/AntiforgeryLoggerExtensions.cs | 0 .../Internal/AntiforgeryOptionsSetup.cs | 0 .../AntiforgerySerializationContext.cs | 0 ...ySerializationContextPooledObjectPolicy.cs | 0 .../Internal/AntiforgeryToken.cs | 0 .../Internal/BinaryBlob.cs | 0 .../Internal/CryptographyAlgorithms.cs | 0 .../Internal/DefaultAntiforgery.cs | 0 ...efaultAntiforgeryAdditionalDataProvider.cs | 0 .../DefaultAntiforgeryTokenGenerator.cs | 0 .../DefaultAntiforgeryTokenSerializer.cs | 0 .../Internal/DefaultAntiforgeryTokenStore.cs | 0 .../Internal/DefaultClaimUidExtractor.cs | 0 .../Internal/IAntiforgeryFeature.cs | 0 .../Internal/IAntiforgeryTokenGenerator.cs | 0 .../Internal/IAntiforgeryTokenSerializer.cs | 0 .../Internal/IAntiforgeryTokenStore.cs | 0 .../Internal/IClaimUidExtractor.cs | 0 .../Microsoft.AspNetCore.Antiforgery.csproj | 0 .../Properties/AssemblyInfo.cs | 0 .../Properties/Resources.Designer.cs | 0 .../Resources.resx | 0 .../baseline.netcore.json | 0 .../Antiforgery/test}/Directory.Build.props | 0 .../Internal/AntiforgeryOptionsSetupTest.cs | 0 .../Internal/AntiforgeryTokenTest.cs | 0 .../Internal/BinaryBlobTest.cs | 0 .../Internal/DefaultAntiforgeryTest.cs | 0 .../DefaultAntiforgeryTokenGeneratorTest.cs | 0 .../DefaultAntiforgeryTokenSerializerTest.cs | 0 .../DefaultAntiforgeryTokenStoreTest.cs | 0 .../Internal/DefaultClaimUidExtractorTest.cs | 0 ...crosoft.AspNetCore.Antiforgery.Test.csproj | 0 .../TestOptionsManager.cs | 0 .../Antiforgery/version.props | 0 66 files changed, 568 deletions(-) delete mode 100644 .appveyor.yml delete mode 100644 .gitattributes delete mode 100644 .github/ISSUE_TEMPLATE.md delete mode 100644 .travis.yml delete mode 100644 CONTRIBUTING.md delete mode 100644 LICENSE.txt delete mode 100644 NuGet.config delete mode 100644 build.cmd delete mode 100755 build.sh delete mode 100644 korebuild-lock.txt delete mode 100644 korebuild.json delete mode 100644 run.cmd delete mode 100644 run.ps1 delete mode 100755 run.sh rename .gitignore => src/Antiforgery/.gitignore (100%) rename Antiforgery.sln => src/Antiforgery/Antiforgery.sln (100%) rename Directory.Build.props => src/Antiforgery/Directory.Build.props (100%) rename Directory.Build.targets => src/Antiforgery/Directory.Build.targets (100%) rename NuGetPackageVerifier.json => src/Antiforgery/NuGetPackageVerifier.json (100%) rename README.md => src/Antiforgery/README.md (100%) rename {build => src/Antiforgery/build}/Key.snk (100%) rename {build => src/Antiforgery/build}/dependencies.props (100%) rename {build => src/Antiforgery/build}/repo.props (100%) rename {build => src/Antiforgery/build}/sources.props (100%) rename src/{ => Antiforgery/src}/Microsoft.AspNetCore.Antiforgery/AntiforgeryOptions.cs (100%) rename src/{ => Antiforgery/src}/Microsoft.AspNetCore.Antiforgery/AntiforgeryServiceCollectionExtensions.cs (100%) rename src/{ => Antiforgery/src}/Microsoft.AspNetCore.Antiforgery/AntiforgeryTokenSet.cs (100%) rename src/{ => Antiforgery/src}/Microsoft.AspNetCore.Antiforgery/AntiforgeryValidationException.cs (100%) rename src/{ => Antiforgery/src}/Microsoft.AspNetCore.Antiforgery/IAntiforgery.cs (100%) rename src/{ => Antiforgery/src}/Microsoft.AspNetCore.Antiforgery/IAntiforgeryAdditionalDataProvider.cs (100%) rename src/{ => Antiforgery/src}/Microsoft.AspNetCore.Antiforgery/Internal/AntiforgeryFeature.cs (100%) rename src/{ => Antiforgery/src}/Microsoft.AspNetCore.Antiforgery/Internal/AntiforgeryLoggerExtensions.cs (100%) rename src/{ => Antiforgery/src}/Microsoft.AspNetCore.Antiforgery/Internal/AntiforgeryOptionsSetup.cs (100%) rename src/{ => Antiforgery/src}/Microsoft.AspNetCore.Antiforgery/Internal/AntiforgerySerializationContext.cs (100%) rename src/{ => Antiforgery/src}/Microsoft.AspNetCore.Antiforgery/Internal/AntiforgerySerializationContextPooledObjectPolicy.cs (100%) rename src/{ => Antiforgery/src}/Microsoft.AspNetCore.Antiforgery/Internal/AntiforgeryToken.cs (100%) rename src/{ => Antiforgery/src}/Microsoft.AspNetCore.Antiforgery/Internal/BinaryBlob.cs (100%) rename src/{ => Antiforgery/src}/Microsoft.AspNetCore.Antiforgery/Internal/CryptographyAlgorithms.cs (100%) rename src/{ => Antiforgery/src}/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgery.cs (100%) rename src/{ => Antiforgery/src}/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgeryAdditionalDataProvider.cs (100%) rename src/{ => Antiforgery/src}/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgeryTokenGenerator.cs (100%) rename src/{ => Antiforgery/src}/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgeryTokenSerializer.cs (100%) rename src/{ => Antiforgery/src}/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgeryTokenStore.cs (100%) rename src/{ => Antiforgery/src}/Microsoft.AspNetCore.Antiforgery/Internal/DefaultClaimUidExtractor.cs (100%) rename src/{ => Antiforgery/src}/Microsoft.AspNetCore.Antiforgery/Internal/IAntiforgeryFeature.cs (100%) rename src/{ => Antiforgery/src}/Microsoft.AspNetCore.Antiforgery/Internal/IAntiforgeryTokenGenerator.cs (100%) rename src/{ => Antiforgery/src}/Microsoft.AspNetCore.Antiforgery/Internal/IAntiforgeryTokenSerializer.cs (100%) rename src/{ => Antiforgery/src}/Microsoft.AspNetCore.Antiforgery/Internal/IAntiforgeryTokenStore.cs (100%) rename src/{ => Antiforgery/src}/Microsoft.AspNetCore.Antiforgery/Internal/IClaimUidExtractor.cs (100%) rename src/{ => Antiforgery/src}/Microsoft.AspNetCore.Antiforgery/Microsoft.AspNetCore.Antiforgery.csproj (100%) rename src/{ => Antiforgery/src}/Microsoft.AspNetCore.Antiforgery/Properties/AssemblyInfo.cs (100%) rename src/{ => Antiforgery/src}/Microsoft.AspNetCore.Antiforgery/Properties/Resources.Designer.cs (100%) rename src/{ => Antiforgery/src}/Microsoft.AspNetCore.Antiforgery/Resources.resx (100%) rename src/{ => Antiforgery/src}/Microsoft.AspNetCore.Antiforgery/baseline.netcore.json (100%) rename {test => src/Antiforgery/test}/Directory.Build.props (100%) rename {test => src/Antiforgery/test}/Microsoft.AspNetCore.Antiforgery.Test/Internal/AntiforgeryOptionsSetupTest.cs (100%) rename {test => src/Antiforgery/test}/Microsoft.AspNetCore.Antiforgery.Test/Internal/AntiforgeryTokenTest.cs (100%) rename {test => src/Antiforgery/test}/Microsoft.AspNetCore.Antiforgery.Test/Internal/BinaryBlobTest.cs (100%) rename {test => src/Antiforgery/test}/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTest.cs (100%) rename {test => src/Antiforgery/test}/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTokenGeneratorTest.cs (100%) rename {test => src/Antiforgery/test}/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTokenSerializerTest.cs (100%) rename {test => src/Antiforgery/test}/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTokenStoreTest.cs (100%) rename {test => src/Antiforgery/test}/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultClaimUidExtractorTest.cs (100%) rename {test => src/Antiforgery/test}/Microsoft.AspNetCore.Antiforgery.Test/Microsoft.AspNetCore.Antiforgery.Test.csproj (100%) rename {test => src/Antiforgery/test}/Microsoft.AspNetCore.Antiforgery.Test/TestOptionsManager.cs (100%) rename version.props => src/Antiforgery/version.props (100%) diff --git a/.appveyor.yml b/.appveyor.yml deleted file mode 100644 index 4eea96ab69..0000000000 --- a/.appveyor.yml +++ /dev/null @@ -1,17 +0,0 @@ -init: -- git config --global core.autocrlf true -branches: - only: - - dev - - /^release\/.*$/ - - /^(.*\/)?ci-.*$/ -build_script: -- ps: .\run.ps1 default-build -clone_depth: 1 -environment: - global: - DOTNET_SKIP_FIRST_TIME_EXPERIENCE: true - DOTNET_CLI_TELEMETRY_OPTOUT: 1 -test: 'off' -deploy: 'off' -os: Visual Studio 2017 diff --git a/.gitattributes b/.gitattributes deleted file mode 100644 index 97b827b758..0000000000 --- a/.gitattributes +++ /dev/null @@ -1,51 +0,0 @@ -*.doc diff=astextplain -*.DOC diff=astextplain -*.docx diff=astextplain -*.DOCX diff=astextplain -*.dot diff=astextplain -*.DOT diff=astextplain -*.pdf diff=astextplain -*.PDF diff=astextplain -*.rtf diff=astextplain -*.RTF diff=astextplain - -*.jpg binary -*.png binary -*.gif binary - -*.cs text=auto diff=csharp -*.vb text=auto -*.resx text=auto -*.c text=auto -*.cpp text=auto -*.cxx text=auto -*.h text=auto -*.hxx text=auto -*.py text=auto -*.rb text=auto -*.java text=auto -*.html text=auto -*.htm text=auto -*.css text=auto -*.scss text=auto -*.sass text=auto -*.less text=auto -*.js text=auto -*.lisp text=auto -*.clj text=auto -*.sql text=auto -*.php text=auto -*.lua text=auto -*.m text=auto -*.asm text=auto -*.erl text=auto -*.fs text=auto -*.fsx text=auto -*.hs text=auto - -*.csproj text=auto -*.vbproj text=auto -*.fsproj text=auto -*.dbproj text=auto -*.sln text=auto eol=crlf -*.sh eol=lf diff --git a/.github/ISSUE_TEMPLATE.md b/.github/ISSUE_TEMPLATE.md deleted file mode 100644 index 101a084f0a..0000000000 --- a/.github/ISSUE_TEMPLATE.md +++ /dev/null @@ -1,3 +0,0 @@ -THIS ISSUE TRACKER IS CLOSED - please log new issues here: https://github.com/aspnet/Home/issues - -For information about this change, see https://github.com/aspnet/Announcements/issues/283 diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index 64bdbb4441..0000000000 --- a/.travis.yml +++ /dev/null @@ -1,27 +0,0 @@ -language: csharp -sudo: false -dist: trusty -env: - global: - - DOTNET_SKIP_FIRST_TIME_EXPERIENCE: true - - DOTNET_CLI_TELEMETRY_OPTOUT: 1 -mono: none -os: -- linux -- osx -osx_image: xcode8.2 -addons: - apt: - packages: - - libunwind8 -branches: - only: - - dev - - /^release\/.*$/ - - /^(.*\/)?ci-.*$/ -before_install: -- if test "$TRAVIS_OS_NAME" == "osx"; then brew update; brew install openssl; ln -s - /usr/local/opt/openssl/lib/libcrypto.1.0.0.dylib /usr/local/lib/; ln -s /usr/local/opt/openssl/lib/libssl.1.0.0.dylib - /usr/local/lib/; fi -script: -- ./build.sh diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md deleted file mode 100644 index 64ff041d5c..0000000000 --- a/CONTRIBUTING.md +++ /dev/null @@ -1,4 +0,0 @@ -Contributing -====== - -Information on contributing to this repo is in the [Contributing Guide](https://github.com/aspnet/Home/blob/dev/CONTRIBUTING.md) in the Home repo. diff --git a/LICENSE.txt b/LICENSE.txt deleted file mode 100644 index 7b2956ecee..0000000000 --- a/LICENSE.txt +++ /dev/null @@ -1,14 +0,0 @@ -Copyright (c) .NET Foundation and Contributors - -All rights reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); you may not use -this file except in compliance with the License. You may obtain a copy of the -License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software distributed -under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR -CONDITIONS OF ANY KIND, either express or implied. See the License for the -specific language governing permissions and limitations under the License. diff --git a/NuGet.config b/NuGet.config deleted file mode 100644 index e32bddfd51..0000000000 --- a/NuGet.config +++ /dev/null @@ -1,7 +0,0 @@ - - - - - - - diff --git a/build.cmd b/build.cmd deleted file mode 100644 index c0050bda12..0000000000 --- a/build.cmd +++ /dev/null @@ -1,2 +0,0 @@ -@ECHO OFF -PowerShell -NoProfile -NoLogo -ExecutionPolicy unrestricted -Command "[System.Threading.Thread]::CurrentThread.CurrentCulture = ''; [System.Threading.Thread]::CurrentThread.CurrentUICulture = '';& '%~dp0run.ps1' default-build %*; exit $LASTEXITCODE" diff --git a/build.sh b/build.sh deleted file mode 100755 index 98a4b22765..0000000000 --- a/build.sh +++ /dev/null @@ -1,8 +0,0 @@ -#!/usr/bin/env bash - -set -euo pipefail -DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" - -# Call "sync" between "chmod" and execution to prevent "text file busy" error in Docker (aufs) -chmod +x "$DIR/run.sh"; sync -"$DIR/run.sh" default-build "$@" diff --git a/korebuild-lock.txt b/korebuild-lock.txt deleted file mode 100644 index 251c227c83..0000000000 --- a/korebuild-lock.txt +++ /dev/null @@ -1,2 +0,0 @@ -version:2.1.3-rtm-15802 -commithash:a7c08b45b440a7d2058a0aa1eaa3eb6ba811976a diff --git a/korebuild.json b/korebuild.json deleted file mode 100644 index 678d8bb948..0000000000 --- a/korebuild.json +++ /dev/null @@ -1,4 +0,0 @@ -{ - "$schema": "https://raw.githubusercontent.com/aspnet/BuildTools/release/2.1/tools/korebuild.schema.json", - "channel": "release/2.1" -} diff --git a/run.cmd b/run.cmd deleted file mode 100644 index d52d5c7e68..0000000000 --- a/run.cmd +++ /dev/null @@ -1,2 +0,0 @@ -@ECHO OFF -PowerShell -NoProfile -NoLogo -ExecutionPolicy unrestricted -Command "[System.Threading.Thread]::CurrentThread.CurrentCulture = ''; [System.Threading.Thread]::CurrentThread.CurrentUICulture = '';& '%~dp0run.ps1' %*; exit $LASTEXITCODE" diff --git a/run.ps1 b/run.ps1 deleted file mode 100644 index 27dcf848f8..0000000000 --- a/run.ps1 +++ /dev/null @@ -1,196 +0,0 @@ -#!/usr/bin/env powershell -#requires -version 4 - -<# -.SYNOPSIS -Executes KoreBuild commands. - -.DESCRIPTION -Downloads korebuild if required. Then executes the KoreBuild command. To see available commands, execute with `-Command help`. - -.PARAMETER Command -The KoreBuild command to run. - -.PARAMETER Path -The folder to build. Defaults to the folder containing this script. - -.PARAMETER Channel -The channel of KoreBuild to download. Overrides the value from the config file. - -.PARAMETER DotNetHome -The directory where .NET Core tools will be stored. - -.PARAMETER ToolsSource -The base url where build tools can be downloaded. Overrides the value from the config file. - -.PARAMETER Update -Updates KoreBuild to the latest version even if a lock file is present. - -.PARAMETER ConfigFile -The path to the configuration file that stores values. Defaults to korebuild.json. - -.PARAMETER ToolsSourceSuffix -The Suffix to append to the end of the ToolsSource. Useful for query strings in blob stores. - -.PARAMETER Arguments -Arguments to be passed to the command - -.NOTES -This function will create a file $PSScriptRoot/korebuild-lock.txt. This lock file can be committed to source, but does not have to be. -When the lockfile is not present, KoreBuild will create one using latest available version from $Channel. - -The $ConfigFile is expected to be an JSON file. It is optional, and the configuration values in it are optional as well. Any options set -in the file are overridden by command line parameters. - -.EXAMPLE -Example config file: -```json -{ - "$schema": "https://raw.githubusercontent.com/aspnet/BuildTools/dev/tools/korebuild.schema.json", - "channel": "dev", - "toolsSource": "https://aspnetcore.blob.core.windows.net/buildtools" -} -``` -#> -[CmdletBinding(PositionalBinding = $false)] -param( - [Parameter(Mandatory = $true, Position = 0)] - [string]$Command, - [string]$Path = $PSScriptRoot, - [Alias('c')] - [string]$Channel, - [Alias('d')] - [string]$DotNetHome, - [Alias('s')] - [string]$ToolsSource, - [Alias('u')] - [switch]$Update, - [string]$ConfigFile, - [string]$ToolsSourceSuffix, - [Parameter(ValueFromRemainingArguments = $true)] - [string[]]$Arguments -) - -Set-StrictMode -Version 2 -$ErrorActionPreference = 'Stop' - -# -# Functions -# - -function Get-KoreBuild { - - $lockFile = Join-Path $Path 'korebuild-lock.txt' - - if (!(Test-Path $lockFile) -or $Update) { - Get-RemoteFile "$ToolsSource/korebuild/channels/$Channel/latest.txt" $lockFile $ToolsSourceSuffix - } - - $version = Get-Content $lockFile | Where-Object { $_ -like 'version:*' } | Select-Object -first 1 - if (!$version) { - Write-Error "Failed to parse version from $lockFile. Expected a line that begins with 'version:'" - } - $version = $version.TrimStart('version:').Trim() - $korebuildPath = Join-Paths $DotNetHome ('buildtools', 'korebuild', $version) - - if (!(Test-Path $korebuildPath)) { - Write-Host -ForegroundColor Magenta "Downloading KoreBuild $version" - New-Item -ItemType Directory -Path $korebuildPath | Out-Null - $remotePath = "$ToolsSource/korebuild/artifacts/$version/korebuild.$version.zip" - - try { - $tmpfile = Join-Path ([IO.Path]::GetTempPath()) "KoreBuild-$([guid]::NewGuid()).zip" - Get-RemoteFile $remotePath $tmpfile $ToolsSourceSuffix - if (Get-Command -Name 'Expand-Archive' -ErrorAction Ignore) { - # Use built-in commands where possible as they are cross-plat compatible - Expand-Archive -Path $tmpfile -DestinationPath $korebuildPath - } - else { - # Fallback to old approach for old installations of PowerShell - Add-Type -AssemblyName System.IO.Compression.FileSystem - [System.IO.Compression.ZipFile]::ExtractToDirectory($tmpfile, $korebuildPath) - } - } - catch { - Remove-Item -Recurse -Force $korebuildPath -ErrorAction Ignore - throw - } - finally { - Remove-Item $tmpfile -ErrorAction Ignore - } - } - - return $korebuildPath -} - -function Join-Paths([string]$path, [string[]]$childPaths) { - $childPaths | ForEach-Object { $path = Join-Path $path $_ } - return $path -} - -function Get-RemoteFile([string]$RemotePath, [string]$LocalPath, [string]$RemoteSuffix) { - if ($RemotePath -notlike 'http*') { - Copy-Item $RemotePath $LocalPath - return - } - - $retries = 10 - while ($retries -gt 0) { - $retries -= 1 - try { - Invoke-WebRequest -UseBasicParsing -Uri $($RemotePath + $RemoteSuffix) -OutFile $LocalPath - return - } - catch { - Write-Verbose "Request failed. $retries retries remaining" - } - } - - Write-Error "Download failed: '$RemotePath'." -} - -# -# Main -# - -# Load configuration or set defaults - -$Path = Resolve-Path $Path -if (!$ConfigFile) { $ConfigFile = Join-Path $Path 'korebuild.json' } - -if (Test-Path $ConfigFile) { - try { - $config = Get-Content -Raw -Encoding UTF8 -Path $ConfigFile | ConvertFrom-Json - if ($config) { - if (!($Channel) -and (Get-Member -Name 'channel' -InputObject $config)) { [string] $Channel = $config.channel } - if (!($ToolsSource) -and (Get-Member -Name 'toolsSource' -InputObject $config)) { [string] $ToolsSource = $config.toolsSource} - } - } - catch { - Write-Warning "$ConfigFile could not be read. Its settings will be ignored." - Write-Warning $Error[0] - } -} - -if (!$DotNetHome) { - $DotNetHome = if ($env:DOTNET_HOME) { $env:DOTNET_HOME } ` - elseif ($env:USERPROFILE) { Join-Path $env:USERPROFILE '.dotnet'} ` - elseif ($env:HOME) {Join-Path $env:HOME '.dotnet'}` - else { Join-Path $PSScriptRoot '.dotnet'} -} - -if (!$Channel) { $Channel = 'dev' } -if (!$ToolsSource) { $ToolsSource = 'https://aspnetcore.blob.core.windows.net/buildtools' } - -# Execute - -$korebuildPath = Get-KoreBuild -Import-Module -Force -Scope Local (Join-Path $korebuildPath 'KoreBuild.psd1') - -try { - Set-KoreBuildSettings -ToolsSource $ToolsSource -DotNetHome $DotNetHome -RepoPath $Path -ConfigFile $ConfigFile - Invoke-KoreBuildCommand $Command @Arguments -} -finally { - Remove-Module 'KoreBuild' -ErrorAction Ignore -} diff --git a/run.sh b/run.sh deleted file mode 100755 index 834961fc3a..0000000000 --- a/run.sh +++ /dev/null @@ -1,231 +0,0 @@ -#!/usr/bin/env bash - -set -euo pipefail - -# -# variables -# - -RESET="\033[0m" -RED="\033[0;31m" -YELLOW="\033[0;33m" -MAGENTA="\033[0;95m" -DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" -[ -z "${DOTNET_HOME:-}" ] && DOTNET_HOME="$HOME/.dotnet" -verbose=false -update=false -repo_path="$DIR" -channel='' -tools_source='' -tools_source_suffix='' - -# -# Functions -# -__usage() { - echo "Usage: $(basename "${BASH_SOURCE[0]}") command [options] [[--] ...]" - echo "" - echo "Arguments:" - echo " command The command to be run." - echo " ... Arguments passed to the command. Variable number of arguments allowed." - echo "" - echo "Options:" - echo " --verbose Show verbose output." - echo " -c|--channel The channel of KoreBuild to download. Overrides the value from the config file.." - echo " --config-file The path to the configuration file that stores values. Defaults to korebuild.json." - echo " -d|--dotnet-home The directory where .NET Core tools will be stored. Defaults to '\$DOTNET_HOME' or '\$HOME/.dotnet." - echo " --path The directory to build. Defaults to the directory containing the script." - echo " -s|--tools-source|-ToolsSource The base url where build tools can be downloaded. Overrides the value from the config file." - echo " --tools-source-suffix|-ToolsSourceSuffix The suffix to append to tools-source. Useful for query strings." - echo " -u|--update Update to the latest KoreBuild even if the lock file is present." - echo "" - echo "Description:" - echo " This function will create a file \$DIR/korebuild-lock.txt. This lock file can be committed to source, but does not have to be." - echo " When the lockfile is not present, KoreBuild will create one using latest available version from \$channel." - - if [[ "${1:-}" != '--no-exit' ]]; then - exit 2 - fi -} - -get_korebuild() { - local version - local lock_file="$repo_path/korebuild-lock.txt" - if [ ! -f "$lock_file" ] || [ "$update" = true ]; then - __get_remote_file "$tools_source/korebuild/channels/$channel/latest.txt" "$lock_file" "$tools_source_suffix" - fi - version="$(grep 'version:*' -m 1 "$lock_file")" - if [[ "$version" == '' ]]; then - __error "Failed to parse version from $lock_file. Expected a line that begins with 'version:'" - return 1 - fi - version="$(echo "${version#version:}" | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//')" - local korebuild_path="$DOTNET_HOME/buildtools/korebuild/$version" - - { - if [ ! -d "$korebuild_path" ]; then - mkdir -p "$korebuild_path" - local remote_path="$tools_source/korebuild/artifacts/$version/korebuild.$version.zip" - tmpfile="$(mktemp)" - echo -e "${MAGENTA}Downloading KoreBuild ${version}${RESET}" - if __get_remote_file "$remote_path" "$tmpfile" "$tools_source_suffix"; then - unzip -q -d "$korebuild_path" "$tmpfile" - fi - rm "$tmpfile" || true - fi - - source "$korebuild_path/KoreBuild.sh" - } || { - if [ -d "$korebuild_path" ]; then - echo "Cleaning up after failed installation" - rm -rf "$korebuild_path" || true - fi - return 1 - } -} - -__error() { - echo -e "${RED}error: $*${RESET}" 1>&2 -} - -__warn() { - echo -e "${YELLOW}warning: $*${RESET}" -} - -__machine_has() { - hash "$1" > /dev/null 2>&1 - return $? -} - -__get_remote_file() { - local remote_path=$1 - local local_path=$2 - local remote_path_suffix=$3 - - if [[ "$remote_path" != 'http'* ]]; then - cp "$remote_path" "$local_path" - return 0 - fi - - local failed=false - if __machine_has wget; then - wget --tries 10 --quiet -O "$local_path" "${remote_path}${remote_path_suffix}" || failed=true - else - failed=true - fi - - if [ "$failed" = true ] && __machine_has curl; then - failed=false - curl --retry 10 -sSL -f --create-dirs -o "$local_path" "${remote_path}${remote_path_suffix}" || failed=true - fi - - if [ "$failed" = true ]; then - __error "Download failed: $remote_path" 1>&2 - return 1 - fi -} - -# -# main -# - -command="${1:-}" -shift - -while [[ $# -gt 0 ]]; do - case $1 in - -\?|-h|--help) - __usage --no-exit - exit 0 - ;; - -c|--channel|-Channel) - shift - channel="${1:-}" - [ -z "$channel" ] && __usage - ;; - --config-file|-ConfigFile) - shift - config_file="${1:-}" - [ -z "$config_file" ] && __usage - if [ ! -f "$config_file" ]; then - __error "Invalid value for --config-file. $config_file does not exist." - exit 1 - fi - ;; - -d|--dotnet-home|-DotNetHome) - shift - DOTNET_HOME="${1:-}" - [ -z "$DOTNET_HOME" ] && __usage - ;; - --path|-Path) - shift - repo_path="${1:-}" - [ -z "$repo_path" ] && __usage - ;; - -s|--tools-source|-ToolsSource) - shift - tools_source="${1:-}" - [ -z "$tools_source" ] && __usage - ;; - --tools-source-suffix|-ToolsSourceSuffix) - shift - tools_source_suffix="${1:-}" - [ -z "$tools_source_suffix" ] && __usage - ;; - -u|--update|-Update) - update=true - ;; - --verbose|-Verbose) - verbose=true - ;; - --) - shift - break - ;; - *) - break - ;; - esac - shift -done - -if ! __machine_has unzip; then - __error 'Missing required command: unzip' - exit 1 -fi - -if ! __machine_has curl && ! __machine_has wget; then - __error 'Missing required command. Either wget or curl is required.' - exit 1 -fi - -[ -z "${config_file:-}" ] && config_file="$repo_path/korebuild.json" -if [ -f "$config_file" ]; then - if __machine_has jq ; then - if jq '.' "$config_file" >/dev/null ; then - config_channel="$(jq -r 'select(.channel!=null) | .channel' "$config_file")" - config_tools_source="$(jq -r 'select(.toolsSource!=null) | .toolsSource' "$config_file")" - else - __warn "$config_file is invalid JSON. Its settings will be ignored." - fi - elif __machine_has python ; then - if python -c "import json,codecs;obj=json.load(codecs.open('$config_file', 'r', 'utf-8-sig'))" >/dev/null ; then - config_channel="$(python -c "import json,codecs;obj=json.load(codecs.open('$config_file', 'r', 'utf-8-sig'));print(obj['channel'] if 'channel' in obj else '')")" - config_tools_source="$(python -c "import json,codecs;obj=json.load(codecs.open('$config_file', 'r', 'utf-8-sig'));print(obj['toolsSource'] if 'toolsSource' in obj else '')")" - else - __warn "$config_file is invalid JSON. Its settings will be ignored." - fi - else - __warn 'Missing required command: jq or pyton. Could not parse the JSON file. Its settings will be ignored.' - fi - - [ ! -z "${config_channel:-}" ] && channel="$config_channel" - [ ! -z "${config_tools_source:-}" ] && tools_source="$config_tools_source" -fi - -[ -z "$channel" ] && channel='dev' -[ -z "$tools_source" ] && tools_source='https://aspnetcore.blob.core.windows.net/buildtools' - -get_korebuild -set_korebuildsettings "$tools_source" "$DOTNET_HOME" "$repo_path" "$config_file" -invoke_korebuild_command "$command" "$@" diff --git a/.gitignore b/src/Antiforgery/.gitignore similarity index 100% rename from .gitignore rename to src/Antiforgery/.gitignore diff --git a/Antiforgery.sln b/src/Antiforgery/Antiforgery.sln similarity index 100% rename from Antiforgery.sln rename to src/Antiforgery/Antiforgery.sln diff --git a/Directory.Build.props b/src/Antiforgery/Directory.Build.props similarity index 100% rename from Directory.Build.props rename to src/Antiforgery/Directory.Build.props diff --git a/Directory.Build.targets b/src/Antiforgery/Directory.Build.targets similarity index 100% rename from Directory.Build.targets rename to src/Antiforgery/Directory.Build.targets diff --git a/NuGetPackageVerifier.json b/src/Antiforgery/NuGetPackageVerifier.json similarity index 100% rename from NuGetPackageVerifier.json rename to src/Antiforgery/NuGetPackageVerifier.json diff --git a/README.md b/src/Antiforgery/README.md similarity index 100% rename from README.md rename to src/Antiforgery/README.md diff --git a/build/Key.snk b/src/Antiforgery/build/Key.snk similarity index 100% rename from build/Key.snk rename to src/Antiforgery/build/Key.snk diff --git a/build/dependencies.props b/src/Antiforgery/build/dependencies.props similarity index 100% rename from build/dependencies.props rename to src/Antiforgery/build/dependencies.props diff --git a/build/repo.props b/src/Antiforgery/build/repo.props similarity index 100% rename from build/repo.props rename to src/Antiforgery/build/repo.props diff --git a/build/sources.props b/src/Antiforgery/build/sources.props similarity index 100% rename from build/sources.props rename to src/Antiforgery/build/sources.props diff --git a/src/Microsoft.AspNetCore.Antiforgery/AntiforgeryOptions.cs b/src/Antiforgery/src/Microsoft.AspNetCore.Antiforgery/AntiforgeryOptions.cs similarity index 100% rename from src/Microsoft.AspNetCore.Antiforgery/AntiforgeryOptions.cs rename to src/Antiforgery/src/Microsoft.AspNetCore.Antiforgery/AntiforgeryOptions.cs diff --git a/src/Microsoft.AspNetCore.Antiforgery/AntiforgeryServiceCollectionExtensions.cs b/src/Antiforgery/src/Microsoft.AspNetCore.Antiforgery/AntiforgeryServiceCollectionExtensions.cs similarity index 100% rename from src/Microsoft.AspNetCore.Antiforgery/AntiforgeryServiceCollectionExtensions.cs rename to src/Antiforgery/src/Microsoft.AspNetCore.Antiforgery/AntiforgeryServiceCollectionExtensions.cs diff --git a/src/Microsoft.AspNetCore.Antiforgery/AntiforgeryTokenSet.cs b/src/Antiforgery/src/Microsoft.AspNetCore.Antiforgery/AntiforgeryTokenSet.cs similarity index 100% rename from src/Microsoft.AspNetCore.Antiforgery/AntiforgeryTokenSet.cs rename to src/Antiforgery/src/Microsoft.AspNetCore.Antiforgery/AntiforgeryTokenSet.cs diff --git a/src/Microsoft.AspNetCore.Antiforgery/AntiforgeryValidationException.cs b/src/Antiforgery/src/Microsoft.AspNetCore.Antiforgery/AntiforgeryValidationException.cs similarity index 100% rename from src/Microsoft.AspNetCore.Antiforgery/AntiforgeryValidationException.cs rename to src/Antiforgery/src/Microsoft.AspNetCore.Antiforgery/AntiforgeryValidationException.cs diff --git a/src/Microsoft.AspNetCore.Antiforgery/IAntiforgery.cs b/src/Antiforgery/src/Microsoft.AspNetCore.Antiforgery/IAntiforgery.cs similarity index 100% rename from src/Microsoft.AspNetCore.Antiforgery/IAntiforgery.cs rename to src/Antiforgery/src/Microsoft.AspNetCore.Antiforgery/IAntiforgery.cs diff --git a/src/Microsoft.AspNetCore.Antiforgery/IAntiforgeryAdditionalDataProvider.cs b/src/Antiforgery/src/Microsoft.AspNetCore.Antiforgery/IAntiforgeryAdditionalDataProvider.cs similarity index 100% rename from src/Microsoft.AspNetCore.Antiforgery/IAntiforgeryAdditionalDataProvider.cs rename to src/Antiforgery/src/Microsoft.AspNetCore.Antiforgery/IAntiforgeryAdditionalDataProvider.cs diff --git a/src/Microsoft.AspNetCore.Antiforgery/Internal/AntiforgeryFeature.cs b/src/Antiforgery/src/Microsoft.AspNetCore.Antiforgery/Internal/AntiforgeryFeature.cs similarity index 100% rename from src/Microsoft.AspNetCore.Antiforgery/Internal/AntiforgeryFeature.cs rename to src/Antiforgery/src/Microsoft.AspNetCore.Antiforgery/Internal/AntiforgeryFeature.cs diff --git a/src/Microsoft.AspNetCore.Antiforgery/Internal/AntiforgeryLoggerExtensions.cs b/src/Antiforgery/src/Microsoft.AspNetCore.Antiforgery/Internal/AntiforgeryLoggerExtensions.cs similarity index 100% rename from src/Microsoft.AspNetCore.Antiforgery/Internal/AntiforgeryLoggerExtensions.cs rename to src/Antiforgery/src/Microsoft.AspNetCore.Antiforgery/Internal/AntiforgeryLoggerExtensions.cs diff --git a/src/Microsoft.AspNetCore.Antiforgery/Internal/AntiforgeryOptionsSetup.cs b/src/Antiforgery/src/Microsoft.AspNetCore.Antiforgery/Internal/AntiforgeryOptionsSetup.cs similarity index 100% rename from src/Microsoft.AspNetCore.Antiforgery/Internal/AntiforgeryOptionsSetup.cs rename to src/Antiforgery/src/Microsoft.AspNetCore.Antiforgery/Internal/AntiforgeryOptionsSetup.cs diff --git a/src/Microsoft.AspNetCore.Antiforgery/Internal/AntiforgerySerializationContext.cs b/src/Antiforgery/src/Microsoft.AspNetCore.Antiforgery/Internal/AntiforgerySerializationContext.cs similarity index 100% rename from src/Microsoft.AspNetCore.Antiforgery/Internal/AntiforgerySerializationContext.cs rename to src/Antiforgery/src/Microsoft.AspNetCore.Antiforgery/Internal/AntiforgerySerializationContext.cs diff --git a/src/Microsoft.AspNetCore.Antiforgery/Internal/AntiforgerySerializationContextPooledObjectPolicy.cs b/src/Antiforgery/src/Microsoft.AspNetCore.Antiforgery/Internal/AntiforgerySerializationContextPooledObjectPolicy.cs similarity index 100% rename from src/Microsoft.AspNetCore.Antiforgery/Internal/AntiforgerySerializationContextPooledObjectPolicy.cs rename to src/Antiforgery/src/Microsoft.AspNetCore.Antiforgery/Internal/AntiforgerySerializationContextPooledObjectPolicy.cs diff --git a/src/Microsoft.AspNetCore.Antiforgery/Internal/AntiforgeryToken.cs b/src/Antiforgery/src/Microsoft.AspNetCore.Antiforgery/Internal/AntiforgeryToken.cs similarity index 100% rename from src/Microsoft.AspNetCore.Antiforgery/Internal/AntiforgeryToken.cs rename to src/Antiforgery/src/Microsoft.AspNetCore.Antiforgery/Internal/AntiforgeryToken.cs diff --git a/src/Microsoft.AspNetCore.Antiforgery/Internal/BinaryBlob.cs b/src/Antiforgery/src/Microsoft.AspNetCore.Antiforgery/Internal/BinaryBlob.cs similarity index 100% rename from src/Microsoft.AspNetCore.Antiforgery/Internal/BinaryBlob.cs rename to src/Antiforgery/src/Microsoft.AspNetCore.Antiforgery/Internal/BinaryBlob.cs diff --git a/src/Microsoft.AspNetCore.Antiforgery/Internal/CryptographyAlgorithms.cs b/src/Antiforgery/src/Microsoft.AspNetCore.Antiforgery/Internal/CryptographyAlgorithms.cs similarity index 100% rename from src/Microsoft.AspNetCore.Antiforgery/Internal/CryptographyAlgorithms.cs rename to src/Antiforgery/src/Microsoft.AspNetCore.Antiforgery/Internal/CryptographyAlgorithms.cs diff --git a/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgery.cs b/src/Antiforgery/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgery.cs similarity index 100% rename from src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgery.cs rename to src/Antiforgery/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgery.cs diff --git a/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgeryAdditionalDataProvider.cs b/src/Antiforgery/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgeryAdditionalDataProvider.cs similarity index 100% rename from src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgeryAdditionalDataProvider.cs rename to src/Antiforgery/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgeryAdditionalDataProvider.cs diff --git a/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgeryTokenGenerator.cs b/src/Antiforgery/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgeryTokenGenerator.cs similarity index 100% rename from src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgeryTokenGenerator.cs rename to src/Antiforgery/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgeryTokenGenerator.cs diff --git a/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgeryTokenSerializer.cs b/src/Antiforgery/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgeryTokenSerializer.cs similarity index 100% rename from src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgeryTokenSerializer.cs rename to src/Antiforgery/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgeryTokenSerializer.cs diff --git a/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgeryTokenStore.cs b/src/Antiforgery/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgeryTokenStore.cs similarity index 100% rename from src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgeryTokenStore.cs rename to src/Antiforgery/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultAntiforgeryTokenStore.cs diff --git a/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultClaimUidExtractor.cs b/src/Antiforgery/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultClaimUidExtractor.cs similarity index 100% rename from src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultClaimUidExtractor.cs rename to src/Antiforgery/src/Microsoft.AspNetCore.Antiforgery/Internal/DefaultClaimUidExtractor.cs diff --git a/src/Microsoft.AspNetCore.Antiforgery/Internal/IAntiforgeryFeature.cs b/src/Antiforgery/src/Microsoft.AspNetCore.Antiforgery/Internal/IAntiforgeryFeature.cs similarity index 100% rename from src/Microsoft.AspNetCore.Antiforgery/Internal/IAntiforgeryFeature.cs rename to src/Antiforgery/src/Microsoft.AspNetCore.Antiforgery/Internal/IAntiforgeryFeature.cs diff --git a/src/Microsoft.AspNetCore.Antiforgery/Internal/IAntiforgeryTokenGenerator.cs b/src/Antiforgery/src/Microsoft.AspNetCore.Antiforgery/Internal/IAntiforgeryTokenGenerator.cs similarity index 100% rename from src/Microsoft.AspNetCore.Antiforgery/Internal/IAntiforgeryTokenGenerator.cs rename to src/Antiforgery/src/Microsoft.AspNetCore.Antiforgery/Internal/IAntiforgeryTokenGenerator.cs diff --git a/src/Microsoft.AspNetCore.Antiforgery/Internal/IAntiforgeryTokenSerializer.cs b/src/Antiforgery/src/Microsoft.AspNetCore.Antiforgery/Internal/IAntiforgeryTokenSerializer.cs similarity index 100% rename from src/Microsoft.AspNetCore.Antiforgery/Internal/IAntiforgeryTokenSerializer.cs rename to src/Antiforgery/src/Microsoft.AspNetCore.Antiforgery/Internal/IAntiforgeryTokenSerializer.cs diff --git a/src/Microsoft.AspNetCore.Antiforgery/Internal/IAntiforgeryTokenStore.cs b/src/Antiforgery/src/Microsoft.AspNetCore.Antiforgery/Internal/IAntiforgeryTokenStore.cs similarity index 100% rename from src/Microsoft.AspNetCore.Antiforgery/Internal/IAntiforgeryTokenStore.cs rename to src/Antiforgery/src/Microsoft.AspNetCore.Antiforgery/Internal/IAntiforgeryTokenStore.cs diff --git a/src/Microsoft.AspNetCore.Antiforgery/Internal/IClaimUidExtractor.cs b/src/Antiforgery/src/Microsoft.AspNetCore.Antiforgery/Internal/IClaimUidExtractor.cs similarity index 100% rename from src/Microsoft.AspNetCore.Antiforgery/Internal/IClaimUidExtractor.cs rename to src/Antiforgery/src/Microsoft.AspNetCore.Antiforgery/Internal/IClaimUidExtractor.cs diff --git a/src/Microsoft.AspNetCore.Antiforgery/Microsoft.AspNetCore.Antiforgery.csproj b/src/Antiforgery/src/Microsoft.AspNetCore.Antiforgery/Microsoft.AspNetCore.Antiforgery.csproj similarity index 100% rename from src/Microsoft.AspNetCore.Antiforgery/Microsoft.AspNetCore.Antiforgery.csproj rename to src/Antiforgery/src/Microsoft.AspNetCore.Antiforgery/Microsoft.AspNetCore.Antiforgery.csproj diff --git a/src/Microsoft.AspNetCore.Antiforgery/Properties/AssemblyInfo.cs b/src/Antiforgery/src/Microsoft.AspNetCore.Antiforgery/Properties/AssemblyInfo.cs similarity index 100% rename from src/Microsoft.AspNetCore.Antiforgery/Properties/AssemblyInfo.cs rename to src/Antiforgery/src/Microsoft.AspNetCore.Antiforgery/Properties/AssemblyInfo.cs diff --git a/src/Microsoft.AspNetCore.Antiforgery/Properties/Resources.Designer.cs b/src/Antiforgery/src/Microsoft.AspNetCore.Antiforgery/Properties/Resources.Designer.cs similarity index 100% rename from src/Microsoft.AspNetCore.Antiforgery/Properties/Resources.Designer.cs rename to src/Antiforgery/src/Microsoft.AspNetCore.Antiforgery/Properties/Resources.Designer.cs diff --git a/src/Microsoft.AspNetCore.Antiforgery/Resources.resx b/src/Antiforgery/src/Microsoft.AspNetCore.Antiforgery/Resources.resx similarity index 100% rename from src/Microsoft.AspNetCore.Antiforgery/Resources.resx rename to src/Antiforgery/src/Microsoft.AspNetCore.Antiforgery/Resources.resx diff --git a/src/Microsoft.AspNetCore.Antiforgery/baseline.netcore.json b/src/Antiforgery/src/Microsoft.AspNetCore.Antiforgery/baseline.netcore.json similarity index 100% rename from src/Microsoft.AspNetCore.Antiforgery/baseline.netcore.json rename to src/Antiforgery/src/Microsoft.AspNetCore.Antiforgery/baseline.netcore.json diff --git a/test/Directory.Build.props b/src/Antiforgery/test/Directory.Build.props similarity index 100% rename from test/Directory.Build.props rename to src/Antiforgery/test/Directory.Build.props diff --git a/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/AntiforgeryOptionsSetupTest.cs b/src/Antiforgery/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/AntiforgeryOptionsSetupTest.cs similarity index 100% rename from test/Microsoft.AspNetCore.Antiforgery.Test/Internal/AntiforgeryOptionsSetupTest.cs rename to src/Antiforgery/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/AntiforgeryOptionsSetupTest.cs diff --git a/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/AntiforgeryTokenTest.cs b/src/Antiforgery/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/AntiforgeryTokenTest.cs similarity index 100% rename from test/Microsoft.AspNetCore.Antiforgery.Test/Internal/AntiforgeryTokenTest.cs rename to src/Antiforgery/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/AntiforgeryTokenTest.cs diff --git a/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/BinaryBlobTest.cs b/src/Antiforgery/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/BinaryBlobTest.cs similarity index 100% rename from test/Microsoft.AspNetCore.Antiforgery.Test/Internal/BinaryBlobTest.cs rename to src/Antiforgery/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/BinaryBlobTest.cs diff --git a/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTest.cs b/src/Antiforgery/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTest.cs similarity index 100% rename from test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTest.cs rename to src/Antiforgery/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTest.cs diff --git a/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTokenGeneratorTest.cs b/src/Antiforgery/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTokenGeneratorTest.cs similarity index 100% rename from test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTokenGeneratorTest.cs rename to src/Antiforgery/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTokenGeneratorTest.cs diff --git a/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTokenSerializerTest.cs b/src/Antiforgery/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTokenSerializerTest.cs similarity index 100% rename from test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTokenSerializerTest.cs rename to src/Antiforgery/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTokenSerializerTest.cs diff --git a/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTokenStoreTest.cs b/src/Antiforgery/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTokenStoreTest.cs similarity index 100% rename from test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTokenStoreTest.cs rename to src/Antiforgery/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultAntiforgeryTokenStoreTest.cs diff --git a/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultClaimUidExtractorTest.cs b/src/Antiforgery/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultClaimUidExtractorTest.cs similarity index 100% rename from test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultClaimUidExtractorTest.cs rename to src/Antiforgery/test/Microsoft.AspNetCore.Antiforgery.Test/Internal/DefaultClaimUidExtractorTest.cs diff --git a/test/Microsoft.AspNetCore.Antiforgery.Test/Microsoft.AspNetCore.Antiforgery.Test.csproj b/src/Antiforgery/test/Microsoft.AspNetCore.Antiforgery.Test/Microsoft.AspNetCore.Antiforgery.Test.csproj similarity index 100% rename from test/Microsoft.AspNetCore.Antiforgery.Test/Microsoft.AspNetCore.Antiforgery.Test.csproj rename to src/Antiforgery/test/Microsoft.AspNetCore.Antiforgery.Test/Microsoft.AspNetCore.Antiforgery.Test.csproj diff --git a/test/Microsoft.AspNetCore.Antiforgery.Test/TestOptionsManager.cs b/src/Antiforgery/test/Microsoft.AspNetCore.Antiforgery.Test/TestOptionsManager.cs similarity index 100% rename from test/Microsoft.AspNetCore.Antiforgery.Test/TestOptionsManager.cs rename to src/Antiforgery/test/Microsoft.AspNetCore.Antiforgery.Test/TestOptionsManager.cs diff --git a/version.props b/src/Antiforgery/version.props similarity index 100% rename from version.props rename to src/Antiforgery/version.props