Browse Source

Migrate to ASP.NET Core/.NET CLI

pull/60/head
Kévin Chalet 10 years ago
parent
commit
8f5295b4bd
  1. 1
      .gitignore
  2. 23
      .travis.yml
  3. 10
      NuGet.config
  4. 66
      build.cmd
  5. 40
      build.sh
  6. 2
      external/NWebsec/ApplicationBuilderExtensions.cs
  7. 2
      external/NWebsec/Extensions/HttpContextExtensions.cs
  8. 2
      external/NWebsec/Helpers/CspUpgradeHelper.cs
  9. 2
      external/NWebsec/Helpers/HeaderResultHandler.cs
  10. 2
      external/NWebsec/Helpers/IHeaderResultHandler.cs
  11. 4
      external/NWebsec/Middleware/CspMiddleware.cs
  12. 4
      external/NWebsec/Middleware/HpkpMiddleware.cs
  13. 4
      external/NWebsec/Middleware/HstsMiddleware.cs
  14. 4
      external/NWebsec/Middleware/MiddleWareBase.cs
  15. 4
      external/NWebsec/Middleware/RedirectValidationMiddleware.cs
  16. 4
      external/NWebsec/Middleware/XContentTypeOptionsMiddleware.cs
  17. 4
      external/NWebsec/Middleware/XDownloadOptionsMiddleware.cs
  18. 4
      external/NWebsec/Middleware/XRobotsTagMiddleware.cs
  19. 4
      external/NWebsec/Middleware/XXssMiddleware.cs
  20. 4
      external/NWebsec/Middleware/XfoMiddleware.cs
  21. 50
      external/NWebsec/project.json
  22. 4
      global.json
  23. 8
      samples/Mvc.Client/Controllers/AuthenticationController.cs
  24. 4
      samples/Mvc.Client/Controllers/HomeController.cs
  25. 4
      samples/Mvc.Client/Properties/launchSettings.json
  26. 60
      samples/Mvc.Client/Startup.cs
  27. 2
      samples/Mvc.Client/hosting.json
  28. 38
      samples/Mvc.Client/project.json
  29. 15
      samples/Mvc.Server/Controllers/AccountController.cs
  30. 2
      samples/Mvc.Server/Controllers/HomeController.cs
  31. 84
      samples/Mvc.Server/Controllers/ManageController.cs
  32. 4
      samples/Mvc.Server/Controllers/ResourceController.cs
  33. 2
      samples/Mvc.Server/Models/ApplicationDbContext.cs
  34. 5
      samples/Mvc.Server/Models/ApplicationUser.cs
  35. 4
      samples/Mvc.Server/Properties/launchSettings.json
  36. 39
      samples/Mvc.Server/Startup.cs
  37. 2
      samples/Mvc.Server/ViewModels/Account/SendCodeViewModel.cs
  38. 2
      samples/Mvc.Server/ViewModels/Manage/ConfigureTwoFactorViewModel.cs
  39. 2
      samples/Mvc.Server/ViewModels/Manage/IndexViewModel.cs
  40. 4
      samples/Mvc.Server/ViewModels/Manage/ManageLoginsViewModel.cs
  41. 6
      samples/Mvc.Server/ViewModels/Manage/RemoveLoginViewModel.cs
  42. 4
      samples/Mvc.Server/Views/Account/Login.cshtml
  43. 2
      samples/Mvc.Server/Views/Manage/ManageLogins.cshtml
  44. 2
      samples/Mvc.Server/Views/Manage/RemoveLogin.cshtml
  45. 20
      samples/Mvc.Server/Views/Shared/_LoginPartial.cshtml
  46. 4
      samples/Mvc.Server/Views/_ViewImports.cshtml
  47. 2
      samples/Mvc.Server/hosting.json
  48. 48
      samples/Mvc.Server/project.json
  49. 14
      src/OpenIddict.Assets/OpenIddictExtensions.cs
  50. 19
      src/OpenIddict.Assets/project.json
  51. 2
      src/OpenIddict.Core/IOpenIddictStore.cs
  52. 2
      src/OpenIddict.Core/OpenIddictBuilder.cs
  53. 38
      src/OpenIddict.Core/OpenIddictExtensions.cs
  54. 53
      src/OpenIddict.Core/OpenIddictManager.cs
  55. 2
      src/OpenIddict.Core/OpenIddictModule.cs
  56. 2
      src/OpenIddict.Core/OpenIddictOptions.cs
  57. 12
      src/OpenIddict.Core/OpenIddictProvider.Authentication.cs
  58. 18
      src/OpenIddict.Core/OpenIddictProvider.Exchange.cs
  59. 11
      src/OpenIddict.Core/OpenIddictProvider.Introspection.cs
  60. 4
      src/OpenIddict.Core/OpenIddictProvider.Session.cs
  61. 15
      src/OpenIddict.Core/OpenIddictProvider.cs
  62. 2
      src/OpenIddict.Core/OpenIddictServices.cs
  63. 27
      src/OpenIddict.Core/project.json
  64. 6
      src/OpenIddict.EF/OpenIddictContext.cs
  65. 16
      src/OpenIddict.EF/OpenIddictExtensions.cs
  66. 4
      src/OpenIddict.EF/OpenIddictStore.cs
  67. 16
      src/OpenIddict.EF/project.json
  68. 2
      src/OpenIddict.Models/Application.cs
  69. 11
      src/OpenIddict.Models/project.json
  70. 18
      src/OpenIddict.Mvc/OpenIddictController.cs
  71. 34
      src/OpenIddict.Mvc/OpenIddictExtensions.cs
  72. 2
      src/OpenIddict.Mvc/Views/Shared/SignIn.cshtml
  73. 23
      src/OpenIddict.Mvc/project.json
  74. 21
      src/OpenIddict.Security/OpenIddictExtensions.cs
  75. 17
      src/OpenIddict.Security/project.json
  76. 24
      src/OpenIddict/OpenIddictExtensions.cs
  77. 15
      src/OpenIddict/project.json

1
.gitignore

@ -6,6 +6,7 @@
target/ target/
.nuget/ .nuget/
.vs/ .vs/
.build/
# User-specific files # User-specific files
*.suo *.suo

23
.travis.yml

@ -1,7 +1,20 @@
language: csharp language: csharp
sudo: false sudo: required
script: dist: trusty
- ./build.sh verify addons:
apt:
packages:
- gettext
- libcurl4-openssl-dev
- libicu-dev
- libssl-dev
- libunwind8
- zlib1g
mono: mono:
- alpha - 4.0.5
- latest os:
- linux
- osx
osx_image: xcode7.1
script:
- ./build.sh verify

10
NuGet.config

@ -1,10 +1,8 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<configuration> <configuration>
<packageSources> <packageSources>
<add key="aspnet-contrib" value="https://www.myget.org/F/aspnet-contrib/api/v2" /> <add key="AspNetCiDev" value="https://www.myget.org/F/aspnetcidev/api/v3/index.json" />
<add key="AspNetVNext" value="https://www.myget.org/F/aspnetvnext/api/v2" />
<add key="WebStack Nightly" value="http://www.myget.org/f/aspnetwebstacknightly/" />
<add key="AzureAd Nightly" value="http://www.myget.org/F/azureadwebstacknightly/" />
<add key="NuGet" value="https://api.nuget.org/v3/index.json" /> <add key="NuGet" value="https://api.nuget.org/v3/index.json" />
<add key="aspnet-contrib" value="https://www.myget.org/F/aspnet-contrib/api/v3/index.json" />
</packageSources> </packageSources>
</configuration> </configuration>

66
build.cmd

@ -1,40 +1,40 @@
@echo off @ECHO off
cd %~dp0
SETLOCAL 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 NUGET_VERSION=latest
SET CACHED_NUGET="%LocalAppData%\NuGet\nuget.%NUGET_VERSION%.exe" SET CACHED_NUGET=%LocalAppData%\NuGet\nuget.%NUGET_VERSION%.exe
SET BUILDCMD_KOREBUILD_VERSION=
SET BUILDCMD_DNX_VERSION= IF NOT EXIST "%BUILD_FOLDER%" (
md "%BUILD_FOLDER%"
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 NOT EXIST "%NUGET_PATH%" (
IF "%BUILDCMD_DNX_VERSION%"=="" ( IF NOT EXIST "%CACHED_NUGET%" (
SET BUILDCMD_DNX_VERSION=latest 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 "%SKIP_DNX_INSTALL%"=="" (
CALL packages\KoreBuild\build\dnvm install %BUILDCMD_DNX_VERSION% -runtime CoreCLR -arch x86 -alias default IF NOT EXIST "%KOREBUILD_FOLDER%" (
CALL packages\KoreBuild\build\dnvm install default -runtime CLR -arch x86 -alias default SET KOREBUILD_DOWNLOAD_ARGS=
) ELSE ( IF NOT "%KOREBUILD_VERSION%"=="" (
CALL packages\KoreBuild\build\dnvm use default -runtime CLR -arch x86 SET KOREBUILD_DOWNLOAD_ARGS=-version %KOREBUILD_VERSION%
)
"%BUILD_FOLDER%\nuget.exe" install KoreBuild-dotnet -ExcludeVersion -o "%BUILD_FOLDER%" -nocache -pre %KOREBUILD_DOWNLOAD_ARGS%
) )
packages\Sake\tools\Sake.exe -I packages\KoreBuild\build -f makefile.shade %* "%KOREBUILD_FOLDER%\build\KoreBuild.cmd" %*

40
build.sh

@ -1,5 +1,10 @@
#!/usr/bin/env bash #!/usr/bin/env bash
buildFolder=.build
koreBuildFolder=$buildFolder/KoreBuild-dotnet
nugetPath=$buildFolder/nuget.exe
if test `uname` = Darwin; then if test `uname` = Darwin; then
cachedir=~/Library/Caches/KBuild cachedir=~/Library/Caches/KBuild
else else
@ -11,33 +16,30 @@ else
fi fi
mkdir -p $cachedir mkdir -p $cachedir
nugetVersion=latest 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 if test ! -d $buildFolder; then
wget -O $cachePath $url 2>/dev/null || curl -o $cachePath --location $url /dev/null mkdir $buildFolder
fi fi
if test ! -e .nuget; then if test ! -f $nugetPath; then
mkdir .nuget if test ! -f $cacheNuget; then
cp $cachePath .nuget/nuget.exe wget -O $cacheNuget $nugetUrl 2>/dev/null || curl -o $cacheNuget --location $nugetUrl /dev/null
fi fi
if test ! -d packages/Sake; then cp $cacheNuget $nugetPath
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
fi fi
if ! type dnvm > /dev/null 2>&1; then if test ! -d $koreBuildFolder; then
source packages/KoreBuild/build/dnvm.sh mono $nugetPath install KoreBuild-dotnet -ExcludeVersion -o $buildFolder -nocache -pre
chmod +x $koreBuildFolder/build/KoreBuild.sh
fi fi
if ! type dnx > /dev/null 2>&1 || [ -z "$SKIP_DNX_INSTALL" ]; then makeFile=makefile.shade
dnvm install latest -runtime coreclr -alias default if [ ! -e $makeFile ]; then
dnvm install default -runtime mono -alias default makeFile=$koreBuildFolder/build/makefile.shade
else
dnvm use default -runtime mono
fi fi
mono packages/Sake/tools/Sake.exe -I packages/KoreBuild/build -f makefile.shade "$@" ./$koreBuildFolder/build/KoreBuild.sh -n $nugetPath -m $makeFile "$@"

2
external/NWebsec/ApplicationBuilderExtensions.cs

@ -6,7 +6,7 @@ using NWebsec.Middleware;
using NWebsec.Middleware.Middleware; using NWebsec.Middleware.Middleware;
// ReSharper disable once CheckNamespace // ReSharper disable once CheckNamespace
namespace Microsoft.AspNet.Builder namespace Microsoft.AspNetCore.Builder
{ {
public static class ApplicationBuilderExtensions public static class ApplicationBuilderExtensions
{ {

2
external/NWebsec/Extensions/HttpContextExtensions.cs

@ -1,6 +1,6 @@
// Copyright (c) André N. Klingsheim. See License.txt in the project root for license information. // Copyright (c) André N. Klingsheim. See License.txt in the project root for license information.
using Microsoft.AspNet.Http; using Microsoft.AspNetCore.Http;
namespace NWebsec.Core.Extensions namespace NWebsec.Core.Extensions
{ {

2
external/NWebsec/Helpers/CspUpgradeHelper.cs

@ -4,7 +4,7 @@
using System; using System;
using System.Linq; using System.Linq;
using Microsoft.AspNet.Http; using Microsoft.AspNetCore.Http;
namespace NWebsec.Middleware.Helpers namespace NWebsec.Middleware.Helpers
{ {

2
external/NWebsec/Helpers/HeaderResultHandler.cs

@ -1,6 +1,6 @@
// Copyright (c) André N. Klingsheim. See License.txt in the project root for license information. // Copyright (c) André N. Klingsheim. See License.txt in the project root for license information.
using Microsoft.AspNet.Http; using Microsoft.AspNetCore.Http;
using NWebsec.Core.HttpHeaders; using NWebsec.Core.HttpHeaders;
namespace NWebsec.Core.Helpers namespace NWebsec.Core.Helpers

2
external/NWebsec/Helpers/IHeaderResultHandler.cs

@ -1,6 +1,6 @@
// Copyright (c) André N. Klingsheim. See License.txt in the project root for license information. // Copyright (c) André N. Klingsheim. See License.txt in the project root for license information.
using Microsoft.AspNet.Http; using Microsoft.AspNetCore.Http;
using NWebsec.Core.HttpHeaders; using NWebsec.Core.HttpHeaders;
namespace NWebsec.Core.Helpers namespace NWebsec.Core.Helpers

4
external/NWebsec/Middleware/CspMiddleware.cs

@ -2,8 +2,8 @@
using System; using System;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.AspNet.Builder; using Microsoft.AspNetCore.Builder;
using Microsoft.AspNet.Http; using Microsoft.AspNetCore.Http;
using NWebsec.Core.Extensions; using NWebsec.Core.Extensions;
using NWebsec.Core.HttpHeaders; using NWebsec.Core.HttpHeaders;
using NWebsec.Core.HttpHeaders.Configuration; using NWebsec.Core.HttpHeaders.Configuration;

4
external/NWebsec/Middleware/HpkpMiddleware.cs

@ -1,7 +1,7 @@
// Copyright (c) André N. Klingsheim. See License.txt in the project root for license information. // Copyright (c) André N. Klingsheim. See License.txt in the project root for license information.
using Microsoft.AspNet.Builder; using Microsoft.AspNetCore.Builder;
using Microsoft.AspNet.Http; using Microsoft.AspNetCore.Http;
using NWebsec.Core.HttpHeaders; using NWebsec.Core.HttpHeaders;
using NWebsec.Core.HttpHeaders.Configuration; using NWebsec.Core.HttpHeaders.Configuration;

4
external/NWebsec/Middleware/HstsMiddleware.cs

@ -1,7 +1,7 @@
// Copyright (c) André N. Klingsheim. See License.txt in the project root for license information. // Copyright (c) André N. Klingsheim. See License.txt in the project root for license information.
using Microsoft.AspNet.Builder; using Microsoft.AspNetCore.Builder;
using Microsoft.AspNet.Http; using Microsoft.AspNetCore.Http;
using NWebsec.Core.HttpHeaders; using NWebsec.Core.HttpHeaders;
using NWebsec.Core.HttpHeaders.Configuration; using NWebsec.Core.HttpHeaders.Configuration;
using NWebsec.Middleware.Helpers; using NWebsec.Middleware.Helpers;

4
external/NWebsec/Middleware/MiddleWareBase.cs

@ -1,8 +1,8 @@
// Copyright (c) André N. Klingsheim. See License.txt in the project root for license information. // Copyright (c) André N. Klingsheim. See License.txt in the project root for license information.
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.AspNet.Builder; using Microsoft.AspNetCore.Builder;
using Microsoft.AspNet.Http; using Microsoft.AspNetCore.Http;
namespace NWebsec.Middleware.Middleware namespace NWebsec.Middleware.Middleware
{ {

4
external/NWebsec/Middleware/RedirectValidationMiddleware.cs

@ -1,8 +1,8 @@
// Copyright (c) André N. Klingsheim. See License.txt in the project root for license information. // Copyright (c) André N. Klingsheim. See License.txt in the project root for license information.
using System; using System;
using Microsoft.AspNet.Builder; using Microsoft.AspNetCore.Builder;
using Microsoft.AspNet.Http; using Microsoft.AspNetCore.Http;
using NWebsec.Core; using NWebsec.Core;
namespace NWebsec.Middleware.Middleware namespace NWebsec.Middleware.Middleware

4
external/NWebsec/Middleware/XContentTypeOptionsMiddleware.cs

@ -1,7 +1,7 @@
// Copyright (c) André N. Klingsheim. See License.txt in the project root for license information. // Copyright (c) André N. Klingsheim. See License.txt in the project root for license information.
using Microsoft.AspNet.Builder; using Microsoft.AspNetCore.Builder;
using Microsoft.AspNet.Http; using Microsoft.AspNetCore.Http;
using NWebsec.Core.Extensions; using NWebsec.Core.Extensions;
using NWebsec.Core.HttpHeaders; using NWebsec.Core.HttpHeaders;
using NWebsec.Core.HttpHeaders.Configuration; using NWebsec.Core.HttpHeaders.Configuration;

4
external/NWebsec/Middleware/XDownloadOptionsMiddleware.cs

@ -1,7 +1,7 @@
// Copyright (c) André N. Klingsheim. See License.txt in the project root for license information. // Copyright (c) André N. Klingsheim. See License.txt in the project root for license information.
using Microsoft.AspNet.Builder; using Microsoft.AspNetCore.Builder;
using Microsoft.AspNet.Http; using Microsoft.AspNetCore.Http;
using NWebsec.Core.Extensions; using NWebsec.Core.Extensions;
using NWebsec.Core.HttpHeaders; using NWebsec.Core.HttpHeaders;
using NWebsec.Core.HttpHeaders.Configuration; using NWebsec.Core.HttpHeaders.Configuration;

4
external/NWebsec/Middleware/XRobotsTagMiddleware.cs

@ -1,7 +1,7 @@
// Copyright (c) André N. Klingsheim. See License.txt in the project root for license information. // Copyright (c) André N. Klingsheim. See License.txt in the project root for license information.
using Microsoft.AspNet.Builder; using Microsoft.AspNetCore.Builder;
using Microsoft.AspNet.Http; using Microsoft.AspNetCore.Http;
using NWebsec.Core.Extensions; using NWebsec.Core.Extensions;
using NWebsec.Core.HttpHeaders; using NWebsec.Core.HttpHeaders;
using NWebsec.Core.HttpHeaders.Configuration; using NWebsec.Core.HttpHeaders.Configuration;

4
external/NWebsec/Middleware/XXssMiddleware.cs

@ -1,7 +1,7 @@
// Copyright (c) André N. Klingsheim. See License.txt in the project root for license information. // Copyright (c) André N. Klingsheim. See License.txt in the project root for license information.
using Microsoft.AspNet.Builder; using Microsoft.AspNetCore.Builder;
using Microsoft.AspNet.Http; using Microsoft.AspNetCore.Http;
using NWebsec.Core.Extensions; using NWebsec.Core.Extensions;
using NWebsec.Core.HttpHeaders; using NWebsec.Core.HttpHeaders;
using NWebsec.Core.HttpHeaders.Configuration; using NWebsec.Core.HttpHeaders.Configuration;

4
external/NWebsec/Middleware/XfoMiddleware.cs

@ -1,7 +1,7 @@
// Copyright (c) André N. Klingsheim. See License.txt in the project root for license information. // Copyright (c) André N. Klingsheim. See License.txt in the project root for license information.
using Microsoft.AspNet.Builder; using Microsoft.AspNetCore.Builder;
using Microsoft.AspNet.Http; using Microsoft.AspNetCore.Http;
using NWebsec.Core.Extensions; using NWebsec.Core.Extensions;
using NWebsec.Core.HttpHeaders; using NWebsec.Core.HttpHeaders;
using NWebsec.Core.HttpHeaders.Configuration; using NWebsec.Core.HttpHeaders.Configuration;

50
external/NWebsec/project.json

@ -1,30 +1,30 @@
{ {
"version": "1.0.0-internal-*", "version": "1.0.0-internal-*",
"title": "NWebsec.Middleware (ASP.NET 5)", "title": "NWebsec.Middleware (ASP.NET 5)",
"description": "NWebsec middleware for ASP.NET 5 applications. NWebsec helps you set important security headers and detect potentially dangerous redirects. See project website for documentation.", "description": "NWebsec middleware for ASP.NET 5 applications. NWebsec helps you set important security headers and detect potentially dangerous redirects. See project website for documentation.",
"releaseNotes": "This release includes core functions for the NWebsec security libaries.", "releaseNotes": "This release includes core functions for the NWebsec security libaries.",
"authors": [ "André N. Klingsheim" ], "authors": [ "André N. Klingsheim" ],
"owners": [ "André N. Klingsheim" ], "owners": [ "André N. Klingsheim" ],
"copyright": "Copyright © 2014 - 2015", "copyright": "Copyright © 2014 - 2015",
"tags": [ "NWebsec Security AspNet AppSec" ], "tags": [ "NWebsec Security AspNet AppSec" ],
"projectUrl": "https://docs.nwebsec.com/en/latest/", "projectUrl": "https://docs.nwebsec.com/en/latest/",
"licenseUrl": "https://github.com/NWebsec/NWebsec/blob/master/LICENSE", "licenseUrl": "https://github.com/NWebsec/NWebsec/blob/master/LICENSE",
"iconUrl": "https://klings.blob.core.windows.net/nwebsecicon/nwebsec_nuget.png", "iconUrl": "https://klings.blob.core.windows.net/nwebsecicon/nwebsec_nuget.png",
"shared": "**/**.cs", "shared": "**/**.cs",
"frameworks": { "frameworks": {
"dnx451": { }, "net451": { },
"net451": { }, "dotnet5.4": {
"dotnet5.4": { "dependencies": {
"dependencies": { "Microsoft.CSharp": "4.0.1-*",
"Microsoft.CSharp": "4.0.1-*", "System.Runtime": "4.1.0-*"
"System.Runtime": "4.0.21-*" }
} }
}
},
}, "dependencies": {
"dependencies": { "Microsoft.AspNetCore.Http.Abstractions": "1.0.0-*"
"Microsoft.AspNet.Http.Abstractions": "1.0.0-rc2-*" }
}
} }

4
global.json

@ -1 +1,3 @@
{ "sources": [ "src", "external" ] } {
"projects": [ "src", "external" ]
}

8
samples/Mvc.Client/Controllers/AuthenticationController.cs

@ -1,8 +1,8 @@
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.AspNet.Authentication.Cookies; using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNet.Authentication.OpenIdConnect; using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using Microsoft.AspNet.Http.Authentication; using Microsoft.AspNetCore.Http.Authentication;
using Microsoft.AspNet.Mvc; using Microsoft.AspNetCore.Mvc;
namespace Mvc.Client.Controllers { namespace Mvc.Client.Controllers {
public class AuthenticationController : Controller { public class AuthenticationController : Controller {

4
samples/Mvc.Client/Controllers/HomeController.cs

@ -3,8 +3,8 @@ using System.Net.Http;
using System.Net.Http.Headers; using System.Net.Http.Headers;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.AspNet.Authorization; using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNet.Mvc; using Microsoft.AspNetCore.Mvc;
namespace Mvc.Client.Controllers { namespace Mvc.Client.Controllers {
public class HomeController : Controller { public class HomeController : Controller {

4
samples/Mvc.Client/Properties/launchSettings.json

@ -12,12 +12,14 @@
"commandName": "IISExpress", "commandName": "IISExpress",
"launchBrowser": true, "launchBrowser": true,
"environmentVariables": { "environmentVariables": {
"ASPNET_ENVIRONMENT": "Development" "ASPNET_ENV": "Development",
"Hosting:Environment": "Development"
} }
}, },
"web": { "web": {
"commandName": "web", "commandName": "web",
"environmentVariables": { "environmentVariables": {
"ASPNET_ENV": "Development",
"Hosting:Environment": "Development" "Hosting:Environment": "Development"
} }
} }

60
samples/Mvc.Client/Startup.cs

@ -1,9 +1,8 @@
using Microsoft.AspNet.Authentication; using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNet.Authentication.Cookies; using Microsoft.AspNetCore.Builder;
using Microsoft.AspNet.Builder; using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNet.Hosting; using Microsoft.AspNetCore.Http;
using Microsoft.AspNet.Http; using Microsoft.AspNetCore.HttpOverrides;
using Microsoft.AspNet.HttpOverrides;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using Microsoft.IdentityModel.Protocols.OpenIdConnect; using Microsoft.IdentityModel.Protocols.OpenIdConnect;
@ -11,8 +10,11 @@ using Microsoft.IdentityModel.Protocols.OpenIdConnect;
namespace Mvc.Client { namespace Mvc.Client {
public class Startup { public class Startup {
public static void Main(string[] args) { public static void Main(string[] args) {
var application = new WebApplicationBuilder() var application = new WebHostBuilder()
.UseConfiguration(WebApplicationConfiguration.GetDefault(args)) .UseCaptureStartupErrors(captureStartupError: true)
.UseDefaultConfiguration(args)
.UseIISPlatformHandlerUrl()
.UseServer("Microsoft.AspNetCore.Server.Kestrel")
.UseStartup<Startup>() .UseStartup<Startup>()
.Build(); .Build();
@ -20,11 +22,10 @@ namespace Mvc.Client {
} }
public void ConfigureServices(IServiceCollection services) { public void ConfigureServices(IServiceCollection services) {
services.Configure<SharedAuthenticationOptions>(options => { services.AddAuthentication(options => {
options.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme; options.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
}); });
services.AddAuthentication();
services.AddMvc(); services.AddMvc();
} }
@ -33,45 +34,44 @@ namespace Mvc.Client {
factory.AddConsole(); factory.AddConsole();
factory.AddDebug(); factory.AddDebug();
app.UseIISPlatformHandler(options => { app.UseIISPlatformHandler();
options.FlowWindowsAuthentication = false;
});
app.UseOverrideHeaders(options => { app.UseForwardedHeaders(new ForwardedHeadersOptions {
options.ForwardedOptions = ForwardedHeaders.All; ForwardedHeaders = ForwardedHeaders.All
}); });
app.UseDeveloperExceptionPage();
app.UseStaticFiles(); app.UseStaticFiles();
// Insert a new cookies middleware in the pipeline to store the user // Insert a new cookies middleware in the pipeline to store the user
// identity after he has been redirected from the identity provider. // identity after he has been redirected from the identity provider.
app.UseCookieAuthentication(options => { app.UseCookieAuthentication(new CookieAuthenticationOptions {
options.AutomaticAuthenticate = true; AutomaticAuthenticate = true,
options.AutomaticChallenge = true; AutomaticChallenge = true,
options.LoginPath = new PathString("/signin"); LoginPath = new PathString("/signin")
}); });
app.UseOpenIdConnectAuthentication(options => { app.UseOpenIdConnectAuthentication(new OpenIdConnectOptions {
// Note: these settings must match the application details // Note: these settings must match the application details
// inserted in the database at the server level. // inserted in the database at the server level.
options.ClientId = "myClient"; ClientId = "myClient",
options.ClientSecret = "secret_secret_secret"; ClientSecret = "secret_secret_secret",
options.PostLogoutRedirectUri = "http://localhost:53507/"; PostLogoutRedirectUri = "http://localhost:53507/",
options.RequireHttpsMetadata = false; RequireHttpsMetadata = false,
options.GetClaimsFromUserInfoEndpoint = true; GetClaimsFromUserInfoEndpoint = true,
options.SaveTokensAsClaims = true; SaveTokensAsClaims = true,
// Use the authorization code flow. // Use the authorization code flow.
options.ResponseType = OpenIdConnectResponseTypes.Code; ResponseType = OpenIdConnectResponseTypes.Code,
// Note: setting the Authority allows the OIDC client middleware to automatically // Note: setting the Authority allows the OIDC client middleware to automatically
// retrieve the identity provider's configuration and spare you from setting // retrieve the identity provider's configuration and spare you from setting
// the different endpoints URIs or the token validation parameters explicitly. // the different endpoints URIs or the token validation parameters explicitly.
options.Authority = "http://localhost:54540/"; Authority = "http://localhost:54540/",
options.Scope.Add("email"); Scope = { "email", "roles" }
options.Scope.Add("roles");
}); });

2
samples/Mvc.Client/hosting.json

@ -1,3 +1,3 @@
{ {
"server": "Microsoft.AspNet.Server.Kestrel" "server": "Microsoft.AspNetCore.Server.Kestrel"
} }

38
samples/Mvc.Client/project.json

@ -1,32 +1,40 @@
{ {
"dependencies": { "dependencies": {
"Microsoft.AspNet.Mvc": "6.0.0-*", "Microsoft.AspNetCore.Mvc": "1.0.0-*",
"Microsoft.AspNet.Authentication.Cookies": "1.0.0-*", "Microsoft.AspNetCore.Authentication.Cookies": "1.0.0-*",
"Microsoft.AspNet.Authentication.OpenIdConnect": "1.0.0-*", "Microsoft.AspNetCore.Authentication.OpenIdConnect": "0.1.0-*",
"Microsoft.AspNet.IISPlatformHandler": "1.0.0-*", "Microsoft.AspNetCore.Diagnostics": "1.0.0-*",
"Microsoft.AspNet.HttpOverrides": "1.0.0-*", "Microsoft.AspNetCore.IISPlatformHandler": "1.0.0-*",
"Microsoft.AspNet.Hosting": "1.0.0-*", "Microsoft.AspNetCore.HttpOverrides": "1.0.0-*",
"Microsoft.AspNet.Server.Kestrel": "1.0.0-*", "Microsoft.AspNetCore.Hosting": "1.0.0-*",
"Microsoft.AspNet.StaticFiles": "1.0.0-*", "Microsoft.AspNetCore.Server.Kestrel": "1.0.0-*",
"Microsoft.AspNetCore.StaticFiles": "1.0.0-*",
"Microsoft.Extensions.Logging.Console": "1.0.0-*", "Microsoft.Extensions.Logging.Console": "1.0.0-*",
"Microsoft.Extensions.Logging.Debug": "1.0.0-*", "Microsoft.Extensions.Logging.Debug": "1.0.0-*",
"Microsoft.NETCore.Platforms": "1.0.1-*"
},
"frameworks": {
"dnx451": { },
"Newtonsoft.Json": "7.0.1" "dnxcore50": {
"imports": "portable-net45+win8"
}
}, },
"compilationOptions": { "compilationOptions": {
"emitEntryPoint": true "emitEntryPoint": true,
"preserveCompilationContext": true
}, },
"commands": { "commands": {
"web": "Mvc.Client" "web": "Mvc.Client"
}, },
"frameworks": { "content": [
"dnx451": { }, "wwwroot",
"dnxcore50": { } "Views"
}, ],
"exclude": [ "exclude": [
"wwwroot", "wwwroot",

15
samples/Mvc.Server/Controllers/AccountController.cs

@ -1,11 +1,10 @@
using System.Linq; using System.Linq;
using System.Security.Claims; using System.Security.Claims;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.AspNet.Authorization; using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNet.Identity; using Microsoft.AspNetCore.Identity;
using Microsoft.AspNet.Mvc; using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNet.Mvc.Rendering; using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.Data.Entity;
using Mvc.Server.Models; using Mvc.Server.Models;
using Mvc.Server.Services; using Mvc.Server.Services;
using Mvc.Server.ViewModels.Account; using Mvc.Server.ViewModels.Account;
@ -168,10 +167,6 @@ namespace Mvc.Server.Controllers {
[AllowAnonymous] [AllowAnonymous]
[ValidateAntiForgeryToken] [ValidateAntiForgeryToken]
public async Task<IActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl = null) { public async Task<IActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl = null) {
if (User.IsSignedIn()) {
return RedirectToAction(nameof(ManageController.Index), "Manage");
}
if (ModelState.IsValid) { if (ModelState.IsValid) {
// Get the information about the user from the external login provider // Get the information about the user from the external login provider
var info = await _signInManager.GetExternalLoginInfoAsync(); var info = await _signInManager.GetExternalLoginInfoAsync();
@ -395,7 +390,7 @@ namespace Mvc.Server.Controllers {
} }
private async Task<ApplicationUser> GetCurrentUserAsync() { private async Task<ApplicationUser> GetCurrentUserAsync() {
return await _userManager.FindByIdAsync(User.GetUserId()); return await _userManager.GetUserAsync(User);
} }
private IActionResult RedirectToLocal(string returnUrl) { private IActionResult RedirectToLocal(string returnUrl) {

2
samples/Mvc.Server/Controllers/HomeController.cs

@ -1,4 +1,4 @@
using Microsoft.AspNet.Mvc; using Microsoft.AspNetCore.Mvc;
namespace Mvc.Server.Controllers { namespace Mvc.Server.Controllers {
public class HomeController : Controller { public class HomeController : Controller {

84
samples/Mvc.Server/Controllers/ManageController.cs

@ -1,9 +1,9 @@
using System.Linq; using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.AspNet.Authorization; using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNet.Identity; using Microsoft.AspNetCore.Identity;
using Microsoft.AspNet.Mvc; using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Mvc.Server.Models; using Mvc.Server.Models;
using Mvc.Server.Services; using Mvc.Server.Services;
using Mvc.Server.ViewModels.Manage; using Mvc.Server.ViewModels.Manage;
@ -15,20 +15,23 @@ namespace Mvc.Server.Controllers {
private readonly SignInManager<ApplicationUser> _signInManager; private readonly SignInManager<ApplicationUser> _signInManager;
private readonly IEmailSender _emailSender; private readonly IEmailSender _emailSender;
private readonly ISmsSender _smsSender; private readonly ISmsSender _smsSender;
private readonly ILogger _logger;
public ManageController( public ManageController(
UserManager<ApplicationUser> userManager, UserManager<ApplicationUser> userManager,
SignInManager<ApplicationUser> signInManager, SignInManager<ApplicationUser> signInManager,
IEmailSender emailSender, IEmailSender emailSender,
ISmsSender smsSender) { ISmsSender smsSender,
ILoggerFactory loggerFactory) {
_userManager = userManager; _userManager = userManager;
_signInManager = signInManager; _signInManager = signInManager;
_emailSender = emailSender; _emailSender = emailSender;
_smsSender = smsSender; _smsSender = smsSender;
_logger = loggerFactory.CreateLogger<ManageController>();
} }
// //
// GET: /Account/Index // GET: /Manage/Index
[HttpGet] [HttpGet]
public async Task<IActionResult> Index(ManageMessageId? message = null) { public async Task<IActionResult> Index(ManageMessageId? message = null) {
ViewData["StatusMessage"] = ViewData["StatusMessage"] =
@ -51,25 +54,15 @@ namespace Mvc.Server.Controllers {
return View(model); return View(model);
} }
//
// GET: /Account/RemoveLogin
[HttpGet]
public async Task<IActionResult> RemoveLogin() {
var user = await GetCurrentUserAsync();
var linkedAccounts = await _userManager.GetLoginsAsync(user);
ViewData["ShowRemoveButton"] = await _userManager.HasPasswordAsync(user) || linkedAccounts.Count > 1;
return View(linkedAccounts);
}
// //
// POST: /Manage/RemoveLogin // POST: /Manage/RemoveLogin
[HttpPost] [HttpPost]
[ValidateAntiForgeryToken] [ValidateAntiForgeryToken]
public async Task<IActionResult> RemoveLogin(string loginProvider, string providerKey) { public async Task<IActionResult> RemoveLogin(RemoveLoginViewModel account) {
ManageMessageId? message = ManageMessageId.Error; ManageMessageId? message = ManageMessageId.Error;
var user = await GetCurrentUserAsync(); var user = await GetCurrentUserAsync();
if (user != null) { if (user != null) {
var result = await _userManager.RemoveLoginAsync(user, loginProvider, providerKey); var result = await _userManager.RemoveLoginAsync(user, account.LoginProvider, account.ProviderKey);
if (result.Succeeded) { if (result.Succeeded) {
await _signInManager.SignInAsync(user, isPersistent: false); await _signInManager.SignInAsync(user, isPersistent: false);
message = ManageMessageId.RemoveLoginSuccess; message = ManageMessageId.RemoveLoginSuccess;
@ -79,13 +72,13 @@ namespace Mvc.Server.Controllers {
} }
// //
// GET: /Account/AddPhoneNumber // GET: /Manage/AddPhoneNumber
public IActionResult AddPhoneNumber() { public IActionResult AddPhoneNumber() {
return View(); return View();
} }
// //
// POST: /Account/AddPhoneNumber // POST: /Manage/AddPhoneNumber
[HttpPost] [HttpPost]
[ValidateAntiForgeryToken] [ValidateAntiForgeryToken]
public async Task<IActionResult> AddPhoneNumber(AddPhoneNumberViewModel model) { public async Task<IActionResult> AddPhoneNumber(AddPhoneNumberViewModel model) {
@ -108,6 +101,7 @@ namespace Mvc.Server.Controllers {
if (user != null) { if (user != null) {
await _userManager.SetTwoFactorEnabledAsync(user, true); await _userManager.SetTwoFactorEnabledAsync(user, true);
await _signInManager.SignInAsync(user, isPersistent: false); await _signInManager.SignInAsync(user, isPersistent: false);
_logger.LogInformation(1, "User enabled two-factor authentication.");
} }
return RedirectToAction(nameof(Index), "Manage"); return RedirectToAction(nameof(Index), "Manage");
} }
@ -121,12 +115,13 @@ namespace Mvc.Server.Controllers {
if (user != null) { if (user != null) {
await _userManager.SetTwoFactorEnabledAsync(user, false); await _userManager.SetTwoFactorEnabledAsync(user, false);
await _signInManager.SignInAsync(user, isPersistent: false); await _signInManager.SignInAsync(user, isPersistent: false);
_logger.LogInformation(2, "User disabled two-factor authentication.");
} }
return RedirectToAction(nameof(Index), "Manage"); return RedirectToAction(nameof(Index), "Manage");
} }
// //
// GET: /Account/VerifyPhoneNumber // GET: /Manage/VerifyPhoneNumber
[HttpGet] [HttpGet]
public async Task<IActionResult> VerifyPhoneNumber(string phoneNumber) { public async Task<IActionResult> VerifyPhoneNumber(string phoneNumber) {
var code = await _userManager.GenerateChangePhoneNumberTokenAsync(await GetCurrentUserAsync(), phoneNumber); var code = await _userManager.GenerateChangePhoneNumberTokenAsync(await GetCurrentUserAsync(), phoneNumber);
@ -135,7 +130,7 @@ namespace Mvc.Server.Controllers {
} }
// //
// POST: /Account/VerifyPhoneNumber // POST: /Manage/VerifyPhoneNumber
[HttpPost] [HttpPost]
[ValidateAntiForgeryToken] [ValidateAntiForgeryToken]
public async Task<IActionResult> VerifyPhoneNumber(VerifyPhoneNumberViewModel model) { public async Task<IActionResult> VerifyPhoneNumber(VerifyPhoneNumberViewModel model) {
@ -156,8 +151,9 @@ namespace Mvc.Server.Controllers {
} }
// //
// GET: /Account/RemovePhoneNumber // GET: /Manage/RemovePhoneNumber
[HttpGet] [HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> RemovePhoneNumber() { public async Task<IActionResult> RemovePhoneNumber() {
var user = await GetCurrentUserAsync(); var user = await GetCurrentUserAsync();
if (user != null) { if (user != null) {
@ -178,7 +174,7 @@ namespace Mvc.Server.Controllers {
} }
// //
// POST: /Account/Manage // POST: /Manage/ChangePassword
[HttpPost] [HttpPost]
[ValidateAntiForgeryToken] [ValidateAntiForgeryToken]
public async Task<IActionResult> ChangePassword(ChangePasswordViewModel model) { public async Task<IActionResult> ChangePassword(ChangePasswordViewModel model) {
@ -190,6 +186,7 @@ namespace Mvc.Server.Controllers {
var result = await _userManager.ChangePasswordAsync(user, model.OldPassword, model.NewPassword); var result = await _userManager.ChangePasswordAsync(user, model.OldPassword, model.NewPassword);
if (result.Succeeded) { if (result.Succeeded) {
await _signInManager.SignInAsync(user, isPersistent: false); await _signInManager.SignInAsync(user, isPersistent: false);
_logger.LogInformation(3, "User changed their password successfully.");
return RedirectToAction(nameof(Index), new { Message = ManageMessageId.ChangePasswordSuccess }); return RedirectToAction(nameof(Index), new { Message = ManageMessageId.ChangePasswordSuccess });
} }
AddErrors(result); AddErrors(result);
@ -227,7 +224,7 @@ namespace Mvc.Server.Controllers {
return RedirectToAction(nameof(Index), new { Message = ManageMessageId.Error }); return RedirectToAction(nameof(Index), new { Message = ManageMessageId.Error });
} }
//GET: /Account/Manage //GET: /Manage/ManageLogins
[HttpGet] [HttpGet]
public async Task<IActionResult> ManageLogins(ManageMessageId? message = null) { public async Task<IActionResult> ManageLogins(ManageMessageId? message = null) {
ViewData["StatusMessage"] = ViewData["StatusMessage"] =
@ -255,8 +252,8 @@ namespace Mvc.Server.Controllers {
public IActionResult LinkLogin(string provider) { public IActionResult LinkLogin(string provider) {
// Request a redirect to the external login provider to link a login for the current user // Request a redirect to the external login provider to link a login for the current user
var redirectUrl = Url.Action("LinkLoginCallback", "Manage"); var redirectUrl = Url.Action("LinkLoginCallback", "Manage");
var properties = _signInManager.ConfigureExternalAuthenticationProperties(provider, redirectUrl, User.GetUserId()); var properties = _signInManager.ConfigureExternalAuthenticationProperties(provider, redirectUrl, _userManager.GetUserId(User));
return new ChallengeResult(provider, properties); return Challenge(provider, properties);
} }
// //
@ -267,7 +264,7 @@ namespace Mvc.Server.Controllers {
if (user == null) { if (user == null) {
return View("Error"); return View("Error");
} }
var info = await _signInManager.GetExternalLoginInfoAsync(User.GetUserId()); var info = await _signInManager.GetExternalLoginInfoAsync(await _userManager.GetUserIdAsync(user));
if (info == null) { if (info == null) {
return RedirectToAction(nameof(ManageLogins), new { Message = ManageMessageId.Error }); return RedirectToAction(nameof(ManageLogins), new { Message = ManageMessageId.Error });
} }
@ -284,14 +281,6 @@ namespace Mvc.Server.Controllers {
} }
} }
private async Task<bool> HasPhoneNumber() {
var user = await _userManager.FindByIdAsync(User.GetUserId());
if (user != null) {
return user.PhoneNumber != null;
}
return false;
}
public enum ManageMessageId { public enum ManageMessageId {
AddPhoneSuccess, AddPhoneSuccess,
AddLoginSuccess, AddLoginSuccess,
@ -303,19 +292,10 @@ namespace Mvc.Server.Controllers {
Error Error
} }
private async Task<ApplicationUser> GetCurrentUserAsync() { private Task<ApplicationUser> GetCurrentUserAsync() {
return await _userManager.FindByIdAsync(User.GetUserId()); return _userManager.GetUserAsync(User);
}
private IActionResult RedirectToLocal(string returnUrl) {
if (Url.IsLocalUrl(returnUrl)) {
return Redirect(returnUrl);
}
else {
return RedirectToAction(nameof(HomeController.Index), nameof(HomeController));
}
} }
#endregion #endregion
} }
} }

4
samples/Mvc.Server/Controllers/ResourceController.cs

@ -1,7 +1,7 @@
using System.Security.Claims; using System.Security.Claims;
using AspNet.Security.OAuth.Validation; using AspNet.Security.OAuth.Validation;
using Microsoft.AspNet.Authorization; using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNet.Mvc; using Microsoft.AspNetCore.Mvc;
namespace Mvc.Server.Controllers { namespace Mvc.Server.Controllers {
[Route("api")] [Route("api")]

2
samples/Mvc.Server/Models/ApplicationDbContext.cs

@ -1,4 +1,4 @@
using Microsoft.Data.Entity; using Microsoft.EntityFrameworkCore;
using OpenIddict; using OpenIddict;
namespace Mvc.Server.Models { namespace Mvc.Server.Models {

5
samples/Mvc.Server/Models/ApplicationUser.cs

@ -1,7 +1,6 @@
using Microsoft.AspNet.Identity.EntityFramework; using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
namespace Mvc.Server.Models { namespace Mvc.Server.Models {
// Add profile data for application users by adding properties to the ApplicationUser class // Add profile data for application users by adding properties to the ApplicationUser class
public class ApplicationUser : IdentityUser { public class ApplicationUser : IdentityUser { }
}
} }

4
samples/Mvc.Server/Properties/launchSettings.json

@ -12,12 +12,14 @@
"commandName": "IISExpress", "commandName": "IISExpress",
"launchBrowser": true, "launchBrowser": true,
"environmentVariables": { "environmentVariables": {
"ASPNET_ENVIRONMENT": "Development" "ASPNET_ENV": "Development",
"Hosting:Environment": "Development"
} }
}, },
"web": { "web": {
"commandName": "web", "commandName": "web",
"environmentVariables": { "environmentVariables": {
"ASPNET_ENV": "Development",
"Hosting:Environment": "Development" "Hosting:Environment": "Development"
} }
} }

39
samples/Mvc.Server/Startup.cs

@ -1,10 +1,10 @@
using System.Linq; using System.Linq;
using CryptoHelper; using CryptoHelper;
using Microsoft.AspNet.Builder; using Microsoft.AspNetCore.Builder;
using Microsoft.AspNet.Hosting; using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNet.HttpOverrides; using Microsoft.AspNetCore.HttpOverrides;
using Microsoft.AspNet.Identity.EntityFramework; using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.Data.Entity; using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
@ -17,8 +17,11 @@ using OpenIddict.Models;
namespace Mvc.Server { namespace Mvc.Server {
public class Startup { public class Startup {
public static void Main(string[] args) { public static void Main(string[] args) {
var application = new WebApplicationBuilder() var application = new WebHostBuilder()
.UseConfiguration(WebApplicationConfiguration.GetDefault(args)) .UseCaptureStartupErrors(captureStartupError: true)
.UseDefaultConfiguration(args)
.UseIISPlatformHandlerUrl()
.UseServer("Microsoft.AspNetCore.Server.Kestrel")
.UseStartup<Startup>() .UseStartup<Startup>()
.Build(); .Build();
@ -52,14 +55,14 @@ namespace Mvc.Server {
factory.AddConsole(); factory.AddConsole();
factory.AddDebug(); factory.AddDebug();
app.UseIISPlatformHandler(options => { app.UseIISPlatformHandler();
options.FlowWindowsAuthentication = false;
});
app.UseOverrideHeaders(options => { app.UseForwardedHeaders(new ForwardedHeadersOptions {
options.ForwardedOptions = ForwardedHeaders.All; ForwardedHeaders = ForwardedHeaders.All
}); });
app.UseDeveloperExceptionPage();
app.UseStaticFiles(); app.UseStaticFiles();
// Add a middleware used to validate access // Add a middleware used to validate access
@ -81,14 +84,14 @@ namespace Mvc.Server {
app.UseIdentity(); app.UseIdentity();
app.UseGoogleAuthentication(options => { app.UseGoogleAuthentication(new GoogleOptions {
options.ClientId = "560027070069-37ldt4kfuohhu3m495hk2j4pjp92d382.apps.googleusercontent.com"; ClientId = "560027070069-37ldt4kfuohhu3m495hk2j4pjp92d382.apps.googleusercontent.com",
options.ClientSecret = "n2Q-GEw9RQjzcRbU3qhfTj8f"; ClientSecret = "n2Q-GEw9RQjzcRbU3qhfTj8f"
}); });
app.UseTwitterAuthentication(options => { app.UseTwitterAuthentication(new TwitterOptions {
options.ConsumerKey = "6XaCTaLbMqfj6ww3zvZ5g"; ConsumerKey = "6XaCTaLbMqfj6ww3zvZ5g",
options.ConsumerSecret = "Il2eFzGIrYhz6BWjYhVXBPQSfZuS4xoHpSSyD9PI"; ConsumerSecret = "Il2eFzGIrYhz6BWjYhVXBPQSfZuS4xoHpSSyD9PI"
}); });
// Note: OpenIddict must be added after // Note: OpenIddict must be added after

2
samples/Mvc.Server/ViewModels/Account/SendCodeViewModel.cs

@ -1,5 +1,5 @@
using System.Collections.Generic; using System.Collections.Generic;
using Microsoft.AspNet.Mvc.Rendering; using Microsoft.AspNetCore.Mvc.Rendering;
namespace Mvc.Server.ViewModels.Account { namespace Mvc.Server.ViewModels.Account {
public class SendCodeViewModel { public class SendCodeViewModel {

2
samples/Mvc.Server/ViewModels/Manage/ConfigureTwoFactorViewModel.cs

@ -1,5 +1,5 @@
using System.Collections.Generic; using System.Collections.Generic;
using Microsoft.AspNet.Mvc.Rendering; using Microsoft.AspNetCore.Mvc.Rendering;
namespace Mvc.Server.ViewModels.Manage { namespace Mvc.Server.ViewModels.Manage {
public class ConfigureTwoFactorViewModel { public class ConfigureTwoFactorViewModel {

2
samples/Mvc.Server/ViewModels/Manage/IndexViewModel.cs

@ -1,5 +1,5 @@
using System.Collections.Generic; using System.Collections.Generic;
using Microsoft.AspNet.Identity; using Microsoft.AspNetCore.Identity;
namespace Mvc.Server.ViewModels.Manage { namespace Mvc.Server.ViewModels.Manage {
public class IndexViewModel { public class IndexViewModel {

4
samples/Mvc.Server/ViewModels/Manage/ManageLoginsViewModel.cs

@ -1,6 +1,6 @@
using System.Collections.Generic; using System.Collections.Generic;
using Microsoft.AspNet.Http.Authentication; using Microsoft.AspNetCore.Http.Authentication;
using Microsoft.AspNet.Identity; using Microsoft.AspNetCore.Identity;
namespace Mvc.Server.ViewModels.Manage { namespace Mvc.Server.ViewModels.Manage {
public class ManageLoginsViewModel public class ManageLoginsViewModel

6
samples/Mvc.Server/ViewModels/Manage/RemoveLoginViewModel.cs

@ -0,0 +1,6 @@
namespace Mvc.Server.ViewModels.Manage {
public class RemoveLoginViewModel {
public string LoginProvider { get; set; }
public string ProviderKey { get; set; }
}
}

4
samples/Mvc.Server/Views/Account/Login.cshtml

@ -1,6 +1,6 @@
@using System.Collections.Generic @using System.Collections.Generic
@using Microsoft.AspNet.Http @using Microsoft.AspNetCore.Http
@using Microsoft.AspNet.Http.Authentication @using Microsoft.AspNetCore.Http.Authentication
@model LoginViewModel @model LoginViewModel
@inject SignInManager<ApplicationUser> SignInManager @inject SignInManager<ApplicationUser> SignInManager

2
samples/Mvc.Server/Views/Manage/ManageLogins.cshtml

@ -1,5 +1,5 @@
@model ManageLoginsViewModel @model ManageLoginsViewModel
@using Microsoft.AspNet.Http.Authentication @using Microsoft.AspNetCore.Http.Authentication
@{ @{
ViewData["Title"] = "Manage your external logins"; ViewData["Title"] = "Manage your external logins";
} }

2
samples/Mvc.Server/Views/Manage/RemoveLogin.cshtml

@ -1,4 +1,4 @@
@model ICollection<Microsoft.AspNet.Identity.UserLoginInfo> @model ICollection<Microsoft.AspNetCore.Identity.UserLoginInfo>
@{ @{
ViewData["Title"] = "Remove Login"; ViewData["Title"] = "Remove Login";
} }

20
samples/Mvc.Server/Views/Shared/_LoginPartial.cshtml

@ -1,20 +1,24 @@
@using System.Security.Claims @using Microsoft.AspNetCore.Identity
@using Mvc.Server.Models
@if (User.Identity.IsAuthenticated) @inject SignInManager<ApplicationUser> SignInManager
{ @inject UserManager<ApplicationUser> UserManager
@if (SignInManager.IsSignedIn(User)) {
<form asp-controller="Account" asp-action="LogOff" method="post" id="logoutForm" class="navbar-right"> <form asp-controller="Account" asp-action="LogOff" method="post" id="logoutForm" class="navbar-right">
<ul class="nav navbar-nav navbar-right"> <ul class="nav navbar-nav navbar-right">
<li> <li>
<a asp-controller="Manage" asp-action="Index" title="Manage">Hello @User.GetUserName()!</a> <a asp-controller="Manage" asp-action="Index" title="Manage">Hello @UserManager.GetUserName(User)!</a>
</li>
<li>
<button type="submit" class="btn btn-link navbar-btn navbar-link">Log off</button>
</li> </li>
<li><a href="javascript:document.getElementById('logoutForm').submit()">Log off</a></li>
</ul> </ul>
</form> </form>
} }
else else {
{
<ul class="nav navbar-nav navbar-right"> <ul class="nav navbar-nav navbar-right">
<li><a asp-controller="Account" asp-action="Register">Register</a></li> <li><a asp-controller="Account" asp-action="Register">Register</a></li>
<li><a asp-controller="Account" asp-action="Login">Log in</a></li> <li><a asp-controller="Account" asp-action="Login">Log in</a></li>
</ul> </ul>
} }

4
samples/Mvc.Server/Views/_ViewImports.cshtml

@ -2,5 +2,5 @@
@using Mvc.Server.Models @using Mvc.Server.Models
@using Mvc.Server.ViewModels.Account @using Mvc.Server.ViewModels.Account
@using Mvc.Server.ViewModels.Manage @using Mvc.Server.ViewModels.Manage
@using Microsoft.AspNet.Identity @using Microsoft.AspNetCore.Identity
@addTagHelper *, Microsoft.AspNet.Mvc.TagHelpers @addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers

2
samples/Mvc.Server/hosting.json

@ -1,3 +1,3 @@
{ {
"server": "Microsoft.AspNet.Server.Kestrel" "server": "Microsoft.AspNetCore.Server.Kestrel"
} }

48
samples/Mvc.Server/project.json

@ -2,36 +2,42 @@
"dependencies": { "dependencies": {
"AspNet.Security.OAuth.Introspection": "1.0.0-*", "AspNet.Security.OAuth.Introspection": "1.0.0-*",
"AspNet.Security.OAuth.Validation": "1.0.0-*", "AspNet.Security.OAuth.Validation": "1.0.0-*",
"Microsoft.AspNetCore.Authentication.Google": "1.0.0-*",
"EntityFramework.MicrosoftSqlServer": "7.0.0-*", "Microsoft.AspNetCore.Authentication.Twitter": "1.0.0-*",
"Microsoft.AspNetCore.Diagnostics": "1.0.0-*",
"Microsoft.AspNet.Authentication.Google": "1.0.0-*", "Microsoft.AspNetCore.IISPlatformHandler": "1.0.0-*",
"Microsoft.AspNet.Authentication.Twitter": "1.0.0-*", "Microsoft.AspNetCore.HttpOverrides": "1.0.0-*",
"Microsoft.AspNet.Diagnostics": "1.0.0-*", "Microsoft.AspNetCore.Mvc.TagHelpers": "1.0.0-*",
"Microsoft.AspNet.IISPlatformHandler": "1.0.0-*", "Microsoft.AspNetCore.Server.Kestrel": "1.0.0-*",
"Microsoft.AspNet.HttpOverrides": "1.0.0-*", "Microsoft.AspNetCore.StaticFiles": "1.0.0-*",
"Microsoft.AspNet.Mvc.TagHelpers": "6.0.0-*", "Microsoft.EntityFrameworkCore.SqlServer": "1.0.0-*",
"Microsoft.AspNet.Server.Kestrel": "1.0.0-*",
"Microsoft.AspNet.StaticFiles": "1.0.0-*",
"Microsoft.Extensions.Logging.Console": "1.0.0-*", "Microsoft.Extensions.Logging.Console": "1.0.0-*",
"Microsoft.Extensions.Logging.Debug": "1.0.0-*", "Microsoft.Extensions.Logging.Debug": "1.0.0-*",
"Microsoft.NETCore.Platforms": "1.0.1-*",
"OpenIddict": "1.0.0-*" "OpenIddict": "1.0.0-*"
}, },
"frameworks": {
"dnx451": { },
"dnxcore50": {
"imports": "portable-net45+win8"
}
},
"compilationOptions": { "compilationOptions": {
"emitEntryPoint": true "emitEntryPoint": true,
"preserveCompilationContext": true
}, },
"commands": { "commands": {
"web": "Mvc.Server" "web": "Mvc.Server"
}, },
"frameworks": { "content": [
"dnx451": { }, "wwwroot",
"dnxcore50": { } "Views"
}, ],
"exclude": [ "exclude": [
"wwwroot", "wwwroot",
@ -45,9 +51,5 @@
"**.xproj", "**.xproj",
"**.user", "**.user",
"**.vspscc" "**.vspscc"
], ]
"scripts": {
"prepublish": [ "npm install", "bower install", "gulp clean", "gulp min" ]
}
} }

14
src/OpenIddict.Assets/OpenIddictExtensions.cs

@ -1,17 +1,21 @@
/* /*
* Licensed under the Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0) * Licensed under the Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
* See https://github.com/openiddict/core for more information concerning * See https://github.com/openiddict/openiddict-core for more information concerning
* the license and the contributors participating to this project. * the license and the contributors participating to this project.
*/ */
using System;
using System.Reflection; using System.Reflection;
using Microsoft.AspNet.FileProviders; using JetBrains.Annotations;
using Microsoft.AspNet.StaticFiles; using Microsoft.Extensions.FileProviders;
using Microsoft.Extensions.Internal;
namespace Microsoft.AspNet.Builder { namespace Microsoft.AspNetCore.Builder {
public static class OpenIddictExtensions { public static class OpenIddictExtensions {
public static OpenIddictBuilder UseAssets([NotNull] this OpenIddictBuilder builder) { public static OpenIddictBuilder UseAssets([NotNull] this OpenIddictBuilder builder) {
if (builder == null) {
throw new ArgumentNullException(nameof(builder));
}
return builder.AddModule("Assets", -20, app => app.UseStaticFiles(new StaticFileOptions { return builder.AddModule("Assets", -20, app => app.UseStaticFiles(new StaticFileOptions {
FileProvider = new EmbeddedFileProvider( FileProvider = new EmbeddedFileProvider(
assembly: Assembly.Load(new AssemblyName("OpenIddict.Assets")), assembly: Assembly.Load(new AssemblyName("OpenIddict.Assets")),

19
src/OpenIddict.Assets/project.json

@ -6,24 +6,17 @@
"resource": [ "fonts/*", "scripts/*", "stylesheets/*" ], "resource": [ "fonts/*", "scripts/*", "stylesheets/*" ],
"dependencies": { "dependencies": {
"Microsoft.AspNet.FileProviders.Embedded": "1.0.0-*", "JetBrains.Annotations": "10.1.2-eap",
"Microsoft.AspNet.StaticFiles": "1.0.0-*", "Microsoft.AspNetCore.StaticFiles": "1.0.0-*",
"Microsoft.Extensions.FileProviders.Embedded": "1.0.0-*",
"Microsoft.Extensions.NotNullAttribute.Sources": {
"type": "build",
"version": "1.0.0-*"
},
"OpenIddict.Core": "1.0.0-*" "OpenIddict.Core": "1.0.0-*"
}, },
"frameworks": { "frameworks": {
"dnx451": { }, "net451": { },
"dnxcore50": { "dotnet5.4": {
"dependencies": { "imports": "portable-net451+win8"
"System.Runtime": "4.0.21-*"
}
} }
} }
} }

2
src/OpenIddict.Core/IOpenIddictStore.cs

@ -1,6 +1,6 @@
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.AspNet.Identity; using Microsoft.AspNetCore.Identity;
namespace OpenIddict { namespace OpenIddict {
public interface IOpenIddictStore<TUser, TApplication> : IUserStore<TUser> where TUser : class where TApplication : class { public interface IOpenIddictStore<TUser, TApplication> : IUserStore<TUser> where TUser : class where TApplication : class {

2
src/OpenIddict.Core/OpenIddictBuilder.cs

@ -1,7 +1,7 @@
using System.Collections.Generic; using System.Collections.Generic;
using OpenIddict; using OpenIddict;
namespace Microsoft.AspNet.Builder { namespace Microsoft.AspNetCore.Builder {
/// <summary> /// <summary>
/// Holds various properties allowing to configure OpenIddict. /// Holds various properties allowing to configure OpenIddict.
/// </summary> /// </summary>

38
src/OpenIddict.Core/OpenIddictExtensions.cs

@ -1,25 +1,33 @@
/* /*
* Licensed under the Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0) * Licensed under the Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
* See https://github.com/openiddict/core for more information concerning * See https://github.com/openiddict/openiddict-core for more information concerning
* the license and the contributors participating to this project. * the license and the contributors participating to this project.
*/ */
using System; using System;
using System.Linq; using System.Linq;
using AspNet.Security.OpenIdConnect.Server; using AspNet.Security.OpenIdConnect.Server;
using Microsoft.AspNet.Hosting; using JetBrains.Annotations;
using Microsoft.AspNet.Identity; using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions; using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Internal;
using OpenIddict; using OpenIddict;
namespace Microsoft.AspNet.Builder { namespace Microsoft.AspNetCore.Builder {
public static class OpenIddictExtensions { public static class OpenIddictExtensions {
public static IdentityBuilder AddOpenIddictCore<TApplication>( public static IdentityBuilder AddOpenIddictCore<TApplication>(
[NotNull] this IdentityBuilder builder, [NotNull] this IdentityBuilder builder,
[NotNull] Action<OpenIddictServices> configuration) [NotNull] Action<OpenIddictServices> configuration)
where TApplication : class { where TApplication : class {
if (builder == null) {
throw new ArgumentNullException(nameof(builder));
}
if (configuration == null) {
throw new ArgumentNullException(nameof(configuration));
}
builder.Services.AddAuthentication(); builder.Services.AddAuthentication();
builder.Services.AddCaching(); builder.Services.AddCaching();
@ -49,6 +57,18 @@ namespace Microsoft.AspNet.Builder {
[NotNull] this OpenIddictBuilder builder, [NotNull] this OpenIddictBuilder builder,
[NotNull] string name, int position, [NotNull] string name, int position,
[NotNull] Action<IApplicationBuilder> registration) { [NotNull] Action<IApplicationBuilder> registration) {
if (builder == null) {
throw new ArgumentNullException(nameof(builder));
}
if (string.IsNullOrEmpty(name)) {
throw new ArgumentNullException(nameof(name));
}
if (registration == null) {
throw new ArgumentNullException(nameof(registration));
}
// Note: always call ToArray to make sure the foreach // Note: always call ToArray to make sure the foreach
// block doesn't iterate on the modified collection. // block doesn't iterate on the modified collection.
foreach (var module in builder.Modules.Where(module => string.Equals(module.Name, name)).ToArray()) { foreach (var module in builder.Modules.Where(module => string.Equals(module.Name, name)).ToArray()) {
@ -71,6 +91,14 @@ namespace Microsoft.AspNet.Builder {
public static IApplicationBuilder UseOpenIddictCore( public static IApplicationBuilder UseOpenIddictCore(
[NotNull] this IApplicationBuilder app, [NotNull] this IApplicationBuilder app,
[NotNull] Action<OpenIddictBuilder> configuration) { [NotNull] Action<OpenIddictBuilder> configuration) {
if (app == null) {
throw new ArgumentNullException(nameof(app));
}
if (configuration == null) {
throw new ArgumentNullException(nameof(configuration));
}
var builder = new OpenIddictBuilder(); var builder = new OpenIddictBuilder();
// Resolve the OpenIddict provider from the services container. // Resolve the OpenIddict provider from the services container.

53
src/OpenIddict.Core/OpenIddictManager.cs

@ -2,32 +2,36 @@
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Security.Claims; using System.Security.Claims;
using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using AspNet.Security.OpenIdConnect.Extensions; using AspNet.Security.OpenIdConnect.Extensions;
using AspNet.Security.OpenIdConnect.Server; using AspNet.Security.OpenIdConnect.Server;
using CryptoHelper; using CryptoHelper;
using Microsoft.AspNet.Http; using Microsoft.AspNetCore.Builder;
using Microsoft.AspNet.Identity; using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Internal;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options; using Microsoft.Extensions.Options;
namespace OpenIddict { namespace OpenIddict {
public class OpenIddictManager<TUser, TApplication> : UserManager<TUser> where TUser : class where TApplication : class { public class OpenIddictManager<TUser, TApplication> : UserManager<TUser> where TUser : class where TApplication : class {
public OpenIddictManager([NotNull] IServiceProvider services) public OpenIddictManager(
: base(services: services, IOpenIddictStore<TUser, TApplication> store,
store: services.GetService<IOpenIddictStore<TUser, TApplication>>(), IOptions<IdentityOptions> optionsAccessor,
optionsAccessor: services.GetService<IOptions<IdentityOptions>>(), IPasswordHasher<TUser> passwordHasher,
passwordHasher: services.GetService<IPasswordHasher<TUser>>(), IEnumerable<IUserValidator<TUser>> userValidators,
userValidators: services.GetServices<IUserValidator<TUser>>(), IEnumerable<IPasswordValidator<TUser>> passwordValidators,
passwordValidators: services.GetServices<IPasswordValidator<TUser>>(), ILookupNormalizer keyNormalizer,
keyNormalizer: services.GetService<ILookupNormalizer>(), IdentityErrorDescriber errors,
errors: services.GetService<IdentityErrorDescriber>(), IServiceProvider services,
logger: services.GetService<ILogger<UserManager<TUser>>>(), ILogger<UserManager<TUser>> logger)
contextAccessor: services.GetService<IHttpContextAccessor>()) { : base(store, optionsAccessor,
Context = services.GetRequiredService<IHttpContextAccessor>().HttpContext; passwordHasher, userValidators,
Options = services.GetRequiredService<IOptions<IdentityOptions>>().Value; passwordValidators, keyNormalizer,
errors, services, logger) {
Context = services.GetService<IHttpContextAccessor>()?.HttpContext;
Options = optionsAccessor.Value;
} }
/// <summary> /// <summary>
@ -35,6 +39,11 @@ namespace OpenIddict {
/// </summary> /// </summary>
public virtual HttpContext Context { get; } public virtual HttpContext Context { get; }
/// <summary>
/// Gets the cancellation token used to abort async operations.
/// </summary>
public virtual CancellationToken CancellationToken => Context?.RequestAborted ?? CancellationToken.None;
/// <summary> /// <summary>
/// Gets the Identity options associated with the current manager. /// Gets the Identity options associated with the current manager.
/// </summary> /// </summary>
@ -112,11 +121,11 @@ namespace OpenIddict {
} }
public virtual Task<TApplication> FindApplicationByIdAsync(string identifier) { public virtual Task<TApplication> FindApplicationByIdAsync(string identifier) {
return Store.FindApplicationByIdAsync(identifier, Context.RequestAborted); return Store.FindApplicationByIdAsync(identifier, CancellationToken);
} }
public virtual Task<TApplication> FindApplicationByLogoutRedirectUri(string url) { public virtual Task<TApplication> FindApplicationByLogoutRedirectUri(string url) {
return Store.FindApplicationByLogoutRedirectUri(url, Context.RequestAborted); return Store.FindApplicationByLogoutRedirectUri(url, CancellationToken);
} }
public virtual async Task<string> FindClaimAsync(TUser user, string type) { public virtual async Task<string> FindClaimAsync(TUser user, string type) {
@ -141,7 +150,7 @@ namespace OpenIddict {
throw new ArgumentNullException(nameof(application)); throw new ArgumentNullException(nameof(application));
} }
var type = await Store.GetApplicationTypeAsync(application, Context.RequestAborted); var type = await Store.GetApplicationTypeAsync(application, CancellationToken);
// Ensure the application type returned by the store is supported by the manager. // Ensure the application type returned by the store is supported by the manager.
if (!string.Equals(type, OpenIddictConstants.ApplicationTypes.Confidential, StringComparison.OrdinalIgnoreCase) && if (!string.Equals(type, OpenIddictConstants.ApplicationTypes.Confidential, StringComparison.OrdinalIgnoreCase) &&
@ -158,7 +167,7 @@ namespace OpenIddict {
throw new ArgumentNullException(nameof(application)); throw new ArgumentNullException(nameof(application));
} }
return Store.GetDisplayNameAsync(application, Context.RequestAborted); return Store.GetDisplayNameAsync(application, CancellationToken);
} }
public virtual async Task<bool> ValidateRedirectUriAsync(TApplication application, string address) { public virtual async Task<bool> ValidateRedirectUriAsync(TApplication application, string address) {
@ -166,7 +175,7 @@ namespace OpenIddict {
throw new ArgumentNullException(nameof(application)); throw new ArgumentNullException(nameof(application));
} }
if (!string.Equals(address, await Store.GetRedirectUriAsync(application, Context.RequestAborted), StringComparison.Ordinal)) { if (!string.Equals(address, await Store.GetRedirectUriAsync(application, CancellationToken), StringComparison.Ordinal)) {
Logger.LogWarning("Client validation failed because {RedirectUri} was not a valid redirect_uri " + Logger.LogWarning("Client validation failed because {RedirectUri} was not a valid redirect_uri " +
"for {Client}", address, await GetDisplayNameAsync(application)); "for {Client}", address, await GetDisplayNameAsync(application));
@ -187,7 +196,7 @@ namespace OpenIddict {
return false; return false;
} }
var hash = await Store.GetHashedSecretAsync(application, Context.RequestAborted); var hash = await Store.GetHashedSecretAsync(application, CancellationToken);
if (string.IsNullOrEmpty(hash)) { if (string.IsNullOrEmpty(hash)) {
Logger.LogError("Client authentication failed for {Client} because " + Logger.LogError("Client authentication failed for {Client} because " +
"no client secret was associated with the application."); "no client secret was associated with the application.");

2
src/OpenIddict.Core/OpenIddictModule.cs

@ -1,5 +1,5 @@
using System; using System;
using Microsoft.AspNet.Builder; using Microsoft.AspNetCore.Builder;
namespace OpenIddict { namespace OpenIddict {
/// <summary> /// <summary>

2
src/OpenIddict.Core/OpenIddictOptions.cs

@ -1,6 +1,6 @@
/* /*
* Licensed under the Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0) * Licensed under the Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
* See https://github.com/openiddict/core for more information concerning * See https://github.com/openiddict/openiddict-core for more information concerning
* the license and the contributors participating to this project. * the license and the contributors participating to this project.
*/ */

12
src/OpenIddict.Core/OpenIddictProvider.Authentication.cs

@ -1,6 +1,6 @@
/* /*
* Licensed under the Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0) * Licensed under the Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
* See https://github.com/openiddict/core for more information concerning * See https://github.com/openiddict/openiddict-core for more information concerning
* the license and the contributors participating to this project. * the license and the contributors participating to this project.
*/ */
@ -12,10 +12,10 @@ using System.Security.Claims;
using System.Threading.Tasks; using System.Threading.Tasks;
using AspNet.Security.OpenIdConnect.Extensions; using AspNet.Security.OpenIdConnect.Extensions;
using AspNet.Security.OpenIdConnect.Server; using AspNet.Security.OpenIdConnect.Server;
using Microsoft.AspNet.Authentication; using JetBrains.Annotations;
using Microsoft.AspNet.Http.Authentication; using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Http.Authentication;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Internal;
namespace OpenIddict { namespace OpenIddict {
public partial class OpenIddictProvider<TUser, TApplication> : OpenIdConnectServerProvider where TUser : class where TApplication : class { public partial class OpenIddictProvider<TUser, TApplication> : OpenIdConnectServerProvider where TUser : class where TApplication : class {
@ -68,7 +68,7 @@ namespace OpenIddict {
// the appropriate set of scopes is requested to prevent personal data leakage. // the appropriate set of scopes is requested to prevent personal data leakage.
if (context.HttpContext.User.Identities.Any(identity => identity.IsAuthenticated)) { if (context.HttpContext.User.Identities.Any(identity => identity.IsAuthenticated)) {
// Ensure the user profile still exists in the database. // Ensure the user profile still exists in the database.
var user = await manager.FindByIdAsync(context.HttpContext.User.GetUserId()); var user = await manager.GetUserAsync(context.HttpContext.User);
if (user == null) { if (user == null) {
context.Reject( context.Reject(
error: OpenIdConnectConstants.Errors.ServerError, error: OpenIdConnectConstants.Errors.ServerError,
@ -147,7 +147,7 @@ namespace OpenIddict {
// the initial check made by ValidateAuthorizationRequest. // the initial check made by ValidateAuthorizationRequest.
// In this case, ignore the prompt=none request and // In this case, ignore the prompt=none request and
// continue to the next middleware in the pipeline. // continue to the next middleware in the pipeline.
var user = await manager.FindByIdAsync(principal.GetUserId()); var user = await manager.GetUserAsync(principal);
if (user == null) { if (user == null) {
return; return;
} }

18
src/OpenIddict.Core/OpenIddictProvider.Exchange.cs

@ -1,6 +1,6 @@
/* /*
* Licensed under the Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0) * Licensed under the Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
* See https://github.com/openiddict/core for more information concerning * See https://github.com/openiddict/openiddict-core for more information concerning
* the license and the contributors participating to this project. * the license and the contributors participating to this project.
*/ */
@ -10,11 +10,11 @@ using System.Security.Claims;
using System.Threading.Tasks; using System.Threading.Tasks;
using AspNet.Security.OpenIdConnect.Extensions; using AspNet.Security.OpenIdConnect.Extensions;
using AspNet.Security.OpenIdConnect.Server; using AspNet.Security.OpenIdConnect.Server;
using Microsoft.AspNet.Authentication; using JetBrains.Annotations;
using Microsoft.AspNet.Http.Authentication; using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNet.Identity; using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http.Authentication;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Internal;
using Microsoft.Extensions.Options; using Microsoft.Extensions.Options;
namespace OpenIddict { namespace OpenIddict {
@ -128,10 +128,10 @@ namespace OpenIddict {
var manager = context.HttpContext.RequestServices.GetRequiredService<OpenIddictManager<TUser, TApplication>>(); var manager = context.HttpContext.RequestServices.GetRequiredService<OpenIddictManager<TUser, TApplication>>();
var options = context.HttpContext.RequestServices.GetRequiredService<IOptions<IdentityOptions>>(); var options = context.HttpContext.RequestServices.GetRequiredService<IOptions<IdentityOptions>>();
var principal = context.AuthenticationTicket?.Principal; var principal = context.Ticket?.Principal;
Debug.Assert(principal != null); Debug.Assert(principal != null);
var user = await manager.FindByIdAsync(principal.GetUserId()); var user = await manager.GetUserAsync(principal);
if (user == null) { if (user == null) {
context.Reject( context.Reject(
error: OpenIdConnectConstants.Errors.InvalidGrant, error: OpenIdConnectConstants.Errors.InvalidGrant,
@ -156,14 +156,14 @@ namespace OpenIddict {
// Note: the "scopes" property stored in context.AuthenticationTicket is automatically // Note: the "scopes" property stored in context.AuthenticationTicket is automatically
// updated by ASOS when the client application requests a restricted scopes collection. // updated by ASOS when the client application requests a restricted scopes collection.
var identity = await manager.CreateIdentityAsync(user, context.AuthenticationTicket.GetScopes()); var identity = await manager.CreateIdentityAsync(user, context.Ticket.GetScopes());
Debug.Assert(identity != null); Debug.Assert(identity != null);
// Create a new authentication ticket holding the user identity but // Create a new authentication ticket holding the user identity but
// reuse the authentication properties stored in the refresh token. // reuse the authentication properties stored in the refresh token.
var ticket = new AuthenticationTicket( var ticket = new AuthenticationTicket(
new ClaimsPrincipal(identity), new ClaimsPrincipal(identity),
context.AuthenticationTicket.Properties, context.Ticket.Properties,
context.Options.AuthenticationScheme); context.Options.AuthenticationScheme);
context.Validate(ticket); context.Validate(ticket);

11
src/OpenIddict.Core/OpenIddictProvider.Introspection.cs

@ -1,18 +1,17 @@
/* /*
* Licensed under the Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0) * Licensed under the Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
* See https://github.com/openiddict/core for more information concerning * See https://github.com/openiddict/openiddict-core for more information concerning
* the license and the contributors participating to this project. * the license and the contributors participating to this project.
*/ */
using System; using System;
using System.Diagnostics; using System.Diagnostics;
using System.Security.Claims;
using System.Threading.Tasks; using System.Threading.Tasks;
using AspNet.Security.OpenIdConnect.Extensions; using AspNet.Security.OpenIdConnect.Extensions;
using AspNet.Security.OpenIdConnect.Server; using AspNet.Security.OpenIdConnect.Server;
using Microsoft.AspNet.Identity; using JetBrains.Annotations;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Internal;
using Microsoft.Extensions.Options; using Microsoft.Extensions.Options;
namespace OpenIddict { namespace OpenIddict {
@ -82,10 +81,10 @@ namespace OpenIddict {
return; return;
} }
var principal = context.AuthenticationTicket?.Principal; var principal = context.Ticket?.Principal;
Debug.Assert(principal != null); Debug.Assert(principal != null);
var user = await manager.FindByIdAsync(principal.GetUserId()); var user = await manager.GetUserAsync(principal);
if (user == null) { if (user == null) {
context.Active = false; context.Active = false;

4
src/OpenIddict.Core/OpenIddictProvider.Session.cs

@ -1,14 +1,14 @@
/* /*
* Licensed under the Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0) * Licensed under the Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
* See https://github.com/openiddict/core for more information concerning * See https://github.com/openiddict/openiddict-core for more information concerning
* the license and the contributors participating to this project. * the license and the contributors participating to this project.
*/ */
using System.Threading.Tasks; using System.Threading.Tasks;
using AspNet.Security.OpenIdConnect.Extensions; using AspNet.Security.OpenIdConnect.Extensions;
using AspNet.Security.OpenIdConnect.Server; using AspNet.Security.OpenIdConnect.Server;
using JetBrains.Annotations;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Internal;
namespace OpenIddict { namespace OpenIddict {
public partial class OpenIddictProvider<TUser, TApplication> : OpenIdConnectServerProvider where TUser : class where TApplication : class { public partial class OpenIddictProvider<TUser, TApplication> : OpenIdConnectServerProvider where TUser : class where TApplication : class {

15
src/OpenIddict.Core/OpenIddictProvider.cs

@ -1,6 +1,6 @@
/* /*
* Licensed under the Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0) * Licensed under the Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
* See https://github.com/openiddict/core for more information concerning * See https://github.com/openiddict/openiddict-core for more information concerning
* the license and the contributors participating to this project. * the license and the contributors participating to this project.
*/ */
@ -9,6 +9,7 @@ using System.Security.Claims;
using System.Threading.Tasks; using System.Threading.Tasks;
using AspNet.Security.OpenIdConnect.Extensions; using AspNet.Security.OpenIdConnect.Extensions;
using AspNet.Security.OpenIdConnect.Server; using AspNet.Security.OpenIdConnect.Server;
using JetBrains.Annotations;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Internal; using Microsoft.Extensions.Internal;
using Newtonsoft.Json.Linq; using Newtonsoft.Json.Linq;
@ -30,12 +31,12 @@ namespace OpenIddict {
public override async Task ProfileEndpoint([NotNull] ProfileEndpointContext context) { public override async Task ProfileEndpoint([NotNull] ProfileEndpointContext context) {
var manager = context.HttpContext.RequestServices.GetRequiredService<OpenIddictManager<TUser, TApplication>>(); var manager = context.HttpContext.RequestServices.GetRequiredService<OpenIddictManager<TUser, TApplication>>();
var principal = context.AuthenticationTicket?.Principal; var principal = context.Ticket?.Principal;
Debug.Assert(principal != null); Debug.Assert(principal != null);
// Note: user may be null if the user has been removed. // Note: user may be null if the user has been removed.
// In this case, return a 400 response. // In this case, return a 400 response.
var user = await manager.FindByIdAsync(principal.GetUserId()); var user = await manager.GetUserAsync(principal);
if (user == null) { if (user == null) {
context.Response.StatusCode = 400; context.Response.StatusCode = 400;
context.HandleResponse(); context.HandleResponse();
@ -51,7 +52,7 @@ namespace OpenIddict {
// Note: filtering the username is not needed at this stage as OpenIddictController.Accept // Note: filtering the username is not needed at this stage as OpenIddictController.Accept
// and OpenIddictProvider.GrantResourceOwnerCredentials are expected to reject requests that // and OpenIddictProvider.GrantResourceOwnerCredentials are expected to reject requests that
// don't include the "email" scope if the username corresponds to the registed email address. // don't include the "email" scope if the username corresponds to the registed email address.
if (context.AuthenticationTicket.HasScope(OpenIdConnectConstants.Scopes.Profile)) { if (context.Ticket.HasScope(OpenIdConnectConstants.Scopes.Profile)) {
context.PreferredUsername = await manager.GetUserNameAsync(user); context.PreferredUsername = await manager.GetUserNameAsync(user);
if (manager.SupportsUserClaim) { if (manager.SupportsUserClaim) {
@ -62,7 +63,7 @@ namespace OpenIddict {
} }
// Only add the email address details if the "email" scope was present in the access token. // Only add the email address details if the "email" scope was present in the access token.
if (context.AuthenticationTicket.HasScope(OpenIdConnectConstants.Scopes.Email)) { if (context.Ticket.HasScope(OpenIdConnectConstants.Scopes.Email)) {
context.Email = await manager.GetEmailAsync(user); context.Email = await manager.GetEmailAsync(user);
// Only add the "email_verified" claim // Only add the "email_verified" claim
@ -73,7 +74,7 @@ namespace OpenIddict {
}; };
// Only add the phone number details if the "phone" scope was present in the access token. // Only add the phone number details if the "phone" scope was present in the access token.
if (context.AuthenticationTicket.HasScope(OpenIdConnectConstants.Scopes.Phone)) { if (context.Ticket.HasScope(OpenIdConnectConstants.Scopes.Phone)) {
context.PhoneNumber = await manager.GetPhoneNumberAsync(user); context.PhoneNumber = await manager.GetPhoneNumberAsync(user);
// Only add the "phone_number_verified" // Only add the "phone_number_verified"
@ -84,7 +85,7 @@ namespace OpenIddict {
} }
// Only add the roles list if the "roles" scope was present in the access token. // Only add the roles list if the "roles" scope was present in the access token.
if (manager.SupportsUserRole && context.AuthenticationTicket.HasScope(OpenIddictConstants.Scopes.Roles)) { if (manager.SupportsUserRole && context.Ticket.HasScope(OpenIddictConstants.Scopes.Roles)) {
var roles = await manager.GetRolesAsync(user); var roles = await manager.GetRolesAsync(user);
if (roles.Count != 0) { if (roles.Count != 0) {
context.Claims[OpenIddictConstants.Claims.Roles] = JArray.FromObject(roles); context.Claims[OpenIddictConstants.Claims.Roles] = JArray.FromObject(roles);

2
src/OpenIddict.Core/OpenIddictServices.cs

@ -1,6 +1,6 @@
/* /*
* Licensed under the Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0) * Licensed under the Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
* See https://github.com/openiddict/core for more information concerning * See https://github.com/openiddict/openiddict-core for more information concerning
* the license and the contributors participating to this project. * the license and the contributors participating to this project.
*/ */

27
src/OpenIddict.Core/project.json

@ -4,25 +4,20 @@
"description": "Core components of OpenIddict.", "description": "Core components of OpenIddict.",
"dependencies": { "dependencies": {
"Microsoft.AspNet.Cors": "6.0.0-*",
"Microsoft.AspNet.FileProviders.Embedded": "1.0.0-*",
"Microsoft.AspNet.Identity": "3.0.0-*",
"Microsoft.Extensions.Configuration": "1.0.0-*",
"Microsoft.Extensions.Caching.Memory": "1.0.0-*",
"Microsoft.Extensions.NotNullAttribute.Sources": {
"type": "build",
"version": "1.0.0-*"
},
"AspNet.Security.OpenIdConnect.Server": "1.0.0-*", "AspNet.Security.OpenIdConnect.Server": "1.0.0-*",
"CryptoHelper": "1.0.0-rc2-*",
"CryptoHelper": "1.0.0-rc2-*" "JetBrains.Annotations": "10.1.2-eap",
"Microsoft.AspNetCore.Cors": "1.0.0-*",
"Microsoft.AspNetCore.Identity": "1.0.0-*",
"Microsoft.Extensions.Configuration": "1.0.0-*",
"Microsoft.Extensions.Caching.Memory": "1.0.0-*"
}, },
"frameworks": { "frameworks": {
"dnx451": { }, "net451": { },
"dnxcore50": { }
"dotnet5.4": {
"imports": "portable-net451+win8"
}
} }
} }

6
src/OpenIddict.EF/OpenIddictContext.cs

@ -1,12 +1,12 @@
/* /*
* Licensed under the Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0) * Licensed under the Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
* See https://github.com/openiddict/core for more information concerning * See https://github.com/openiddict/openiddict-core for more information concerning
* the license and the contributors participating to this project. * the license and the contributors participating to this project.
*/ */
using System; using System;
using Microsoft.AspNet.Identity.EntityFramework; using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.Data.Entity; using Microsoft.EntityFrameworkCore;
using OpenIddict.Models; using OpenIddict.Models;
namespace OpenIddict { namespace OpenIddict {

16
src/OpenIddict.EF/OpenIddictExtensions.cs

@ -1,22 +1,26 @@
/* /*
* Licensed under the Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0) * Licensed under the Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
* See https://github.com/openiddict/core for more information concerning * See https://github.com/openiddict/openiddict-core for more information concerning
* the license and the contributors participating to this project. * the license and the contributors participating to this project.
*/ */
using System; using System;
using System.Linq; using System.Linq;
using System.Reflection; using System.Reflection;
using Microsoft.AspNet.Identity; using JetBrains.Annotations;
using Microsoft.AspNet.Identity.EntityFramework; using Microsoft.AspNetCore.Identity;
using Microsoft.Data.Entity; using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Internal;
using OpenIddict; using OpenIddict;
namespace Microsoft.AspNet.Builder { namespace Microsoft.AspNetCore.Builder {
public static class OpenIddictExtensions { public static class OpenIddictExtensions {
public static OpenIddictServices UseEntityFramework([NotNull] this OpenIddictServices services) { public static OpenIddictServices UseEntityFramework([NotNull] this OpenIddictServices services) {
if (services == null) {
throw new ArgumentNullException(nameof(services));
}
services.Services.AddScoped( services.Services.AddScoped(
typeof(IOpenIddictStore<,>).MakeGenericType(services.UserType, services.ApplicationType), typeof(IOpenIddictStore<,>).MakeGenericType(services.UserType, services.ApplicationType),
typeof(OpenIddictStore<,,,,>).MakeGenericType( typeof(OpenIddictStore<,,,,>).MakeGenericType(

4
src/OpenIddict.EF/OpenIddictStore.cs

@ -1,8 +1,8 @@
using System; using System;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.AspNet.Identity.EntityFramework; using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.Data.Entity; using Microsoft.EntityFrameworkCore;
using OpenIddict.Models; using OpenIddict.Models;
namespace OpenIddict { namespace OpenIddict {

16
src/OpenIddict.EF/project.json

@ -4,19 +4,17 @@
"description": "Entity Framework adapter for OpenIddict.", "description": "Entity Framework adapter for OpenIddict.",
"dependencies": { "dependencies": {
"Microsoft.AspNet.Identity.EntityFramework": "3.0.0-*", "JetBrains.Annotations": "10.1.2-eap",
"Microsoft.AspNetCore.Identity.EntityFrameworkCore": "1.0.0-*",
"Microsoft.Extensions.NotNullAttribute.Sources": {
"type": "build",
"version": "1.0.0-*"
},
"OpenIddict.Core": "1.0.0-*", "OpenIddict.Core": "1.0.0-*",
"OpenIddict.Models": "1.0.0-*" "OpenIddict.Models": "1.0.0-*"
}, },
"frameworks": { "frameworks": {
"dnx451": { }, "net451": { },
"dnxcore50": { }
"dotnet5.4": {
"imports": "portable-net451+win8"
}
} }
} }

2
src/OpenIddict.Models/Application.cs

@ -1,6 +1,6 @@
/* /*
* Licensed under the Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0) * Licensed under the Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
* See https://github.com/openiddict/core for more information concerning * See https://github.com/openiddict/openiddict-core for more information concerning
* the license and the contributors participating to this project. * the license and the contributors participating to this project.
*/ */

11
src/OpenIddict.Models/project.json

@ -4,11 +4,14 @@
"description": "Contains the default models used by OpenIddict.", "description": "Contains the default models used by OpenIddict.",
"frameworks": { "frameworks": {
"dnx451": { }, "net451": { },
"dnxcore50": {
"dotnet5.4": {
"dependencies": { "dependencies": {
"System.Runtime": "4.0.21-*" "System.Runtime": "4.1.0-*"
} },
"imports": "portable-net451+win8"
} }
} }
} }

18
src/OpenIddict.Mvc/OpenIddictController.cs

@ -1,6 +1,6 @@
/* /*
* Licensed under the Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0) * Licensed under the Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
* See https://github.com/openiddict/core for more information concerning * See https://github.com/openiddict/openiddict-core for more information concerning
* the license and the contributors participating to this project. * the license and the contributors participating to this project.
*/ */
@ -11,12 +11,12 @@ using System.Security.Claims;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using AspNet.Security.OpenIdConnect.Extensions; using AspNet.Security.OpenIdConnect.Extensions;
using Microsoft.AspNet.Authentication; using JetBrains.Annotations;
using Microsoft.AspNet.Authorization; using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNet.Builder; using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNet.Http.Authentication; using Microsoft.AspNetCore.Builder;
using Microsoft.AspNet.Mvc; using Microsoft.AspNetCore.Http.Authentication;
using Microsoft.Extensions.Internal; using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Protocols.OpenIdConnect; using Microsoft.IdentityModel.Protocols.OpenIdConnect;
namespace OpenIddict.Mvc { namespace OpenIddict.Mvc {
@ -119,7 +119,7 @@ namespace OpenIddict.Mvc {
} }
// Retrieve the user data using the unique identifier. // Retrieve the user data using the unique identifier.
var user = await Manager.FindByIdAsync(User.GetUserId()); var user = await Manager.GetUserAsync(User);
if (user == null) { if (user == null) {
return View("Error", new OpenIdConnectMessage { return View("Error", new OpenIdConnectMessage {
Error = OpenIdConnectConstants.Errors.ServerError, Error = OpenIdConnectConstants.Errors.ServerError,
@ -245,7 +245,7 @@ namespace OpenIddict.Mvc {
// Instruct the cookies middleware to delete the local cookie created // Instruct the cookies middleware to delete the local cookie created
// when the user agent is redirected from the external identity provider // when the user agent is redirected from the external identity provider
// after a successful authentication flow (e.g Google or Facebook). // after a successful authentication flow (e.g Google or Facebook).
await HttpContext.Authentication.SignOutAsync("Microsoft.AspNet.Identity.Application"); await HttpContext.Authentication.SignOutAsync("Microsoft.AspNetCore.Identity.Application");
// This call will instruct AspNet.Security.OpenIdConnect.Server to serialize // This call will instruct AspNet.Security.OpenIdConnect.Server to serialize
// the specified identity to build appropriate tokens (id_token and token). // the specified identity to build appropriate tokens (id_token and token).

34
src/OpenIddict.Mvc/OpenIddictExtensions.cs

@ -1,24 +1,28 @@
/* /*
* Licensed under the Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0) * Licensed under the Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
* See https://github.com/openiddict/core for more information concerning * See https://github.com/openiddict/openiddict-core for more information concerning
* the license and the contributors participating to this project. * the license and the contributors participating to this project.
*/ */
using System; using System;
using System.Diagnostics; using System.Diagnostics;
using System.Reflection; using System.Reflection;
using Microsoft.AspNet.FileProviders; using JetBrains.Annotations;
using Microsoft.AspNet.Http; using Microsoft.AspNetCore.Http;
using Microsoft.AspNet.Identity; using Microsoft.AspNetCore.Identity;
using Microsoft.AspNet.Mvc.ApplicationModels; using Microsoft.AspNetCore.Mvc.ApplicationModels;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Internal; using Microsoft.Extensions.FileProviders;
using OpenIddict; using OpenIddict;
using OpenIddict.Mvc; using OpenIddict.Mvc;
namespace Microsoft.AspNet.Builder { namespace Microsoft.AspNetCore.Builder {
public static class OpenIddictExtensions { public static class OpenIddictExtensions {
public static OpenIddictBuilder UseMvc([NotNull] this OpenIddictBuilder builder) { public static OpenIddictBuilder UseMvc([NotNull] this OpenIddictBuilder builder) {
if (builder == null) {
throw new ArgumentNullException(nameof(builder));
}
// Run MVC in an isolated environment. // Run MVC in an isolated environment.
return builder.AddModule("MVC", 10, app => app.Isolate(map => map.UseMvc(routes => { return builder.AddModule("MVC", 10, app => app.Isolate(map => map.UseMvc(routes => {
// Register the actions corresponding to the authorization endpoint. // Register the actions corresponding to the authorization endpoint.
@ -56,13 +60,11 @@ namespace Microsoft.AspNet.Builder {
.AddMvcOptions(options => options.Conventions.Add(new OpenIddictConvention())) .AddMvcOptions(options => options.Conventions.Add(new OpenIddictConvention()))
.AddRazorOptions(options => { .AddRazorOptions(options => {
// Update the Razor options to also use a combined provider that // Update the Razor options to also use an embedded file provider that
// falls back to the current assembly when searching for views. // falls back to the current assembly when searching for views.
options.FileProvider = new CompositeFileProvider( options.FileProviders.Add(new EmbeddedFileProvider(
options.FileProvider, assembly: typeof(OpenIddictController<,>).GetTypeInfo().Assembly,
new EmbeddedFileProvider( baseNamespace: typeof(OpenIddictController<,>).Namespace));
assembly: typeof(OpenIddictController<,>).GetTypeInfo().Assembly,
baseNamespace: typeof(OpenIddictController<,>).Namespace));
}); });
// Register the sign-in manager in the isolated container. // Register the sign-in manager in the isolated container.
@ -85,6 +87,12 @@ namespace Microsoft.AspNet.Builder {
return container.GetRequiredService(typeof(OpenIddictManager<,>).MakeGenericType(registration.UserType, registration.ApplicationType)); return container.GetRequiredService(typeof(OpenIddictManager<,>).MakeGenericType(registration.UserType, registration.ApplicationType));
}); });
// Register the user manager in the isolated container.
services.AddScoped(typeof(UserManager<>).MakeGenericType(registration.UserType), provider => {
return provider.GetRequiredService(typeof(OpenIddictManager<,>)
.MakeGenericType(registration.UserType, registration.ApplicationType));
});
// Register the options in the isolated container. // Register the options in the isolated container.
services.AddScoped(provider => builder.Options); services.AddScoped(provider => builder.Options);
})); }));

2
src/OpenIddict.Mvc/Views/Shared/SignIn.cshtml

@ -1,4 +1,4 @@
@using Microsoft.AspNet.Http.Authentication @using Microsoft.AspNetCore.Http.Authentication
@model IEnumerable<AuthenticationDescription> @model IEnumerable<AuthenticationDescription>
<div class="jumbotron"> <div class="jumbotron">

23
src/OpenIddict.Mvc/project.json

@ -7,25 +7,18 @@
"dependencies": { "dependencies": {
"AspNet.Hosting.Extensions": "1.0.0-*", "AspNet.Hosting.Extensions": "1.0.0-*",
"JetBrains.Annotations": "10.1.2-eap",
"Microsoft.AspNet.FileProviders.Composite": "1.0.0-*", "Microsoft.AspNetCore.Mvc": "1.0.0-*",
"Microsoft.AspNet.FileProviders.Embedded": "1.0.0-*", "Microsoft.Extensions.FileProviders.Embedded": "1.0.0-*",
"Microsoft.AspNet.Mvc": "6.0.0-*", "Microsoft.Extensions.FileProviders.Composite": "1.0.0-*",
"Microsoft.Extensions.NotNullAttribute.Sources": {
"type": "build",
"version": "1.0.0-*"
},
"OpenIddict.Core": "1.0.0-*" "OpenIddict.Core": "1.0.0-*"
}, },
"frameworks": { "frameworks": {
"dnx451": { }, "net451": { },
"dnxcore50": {
"dependencies": { "dotnet5.6": {
"System.Reflection": "4.1.0-*" "imports": "portable-net451+win8"
}
} }
} }
} }

21
src/OpenIddict.Security/OpenIddictExtensions.cs

@ -1,10 +1,14 @@
using System; using System;
using Microsoft.Extensions.Internal; using JetBrains.Annotations;
using NWebsec.Middleware; using NWebsec.Middleware;
namespace Microsoft.AspNet.Builder { namespace Microsoft.AspNetCore.Builder {
public static class OpenIddictExtensions { public static class OpenIddictExtensions {
public static OpenIddictBuilder UseNWebsec([NotNull] this OpenIddictBuilder builder) { public static OpenIddictBuilder UseNWebsec([NotNull] this OpenIddictBuilder builder) {
if (builder == null) {
throw new ArgumentNullException(nameof(builder));
}
return builder.UseNWebsec(options => { return builder.UseNWebsec(options => {
options.DefaultSources(directive => directive.Self()) options.DefaultSources(directive => directive.Self())
.ImageSources(directive => directive.Self().CustomSources("*")) .ImageSources(directive => directive.Self().CustomSources("*"))
@ -16,6 +20,14 @@ namespace Microsoft.AspNet.Builder {
public static OpenIddictBuilder UseNWebsec( public static OpenIddictBuilder UseNWebsec(
[NotNull] this OpenIddictBuilder builder, [NotNull] this OpenIddictBuilder builder,
[NotNull] Action<IFluentCspOptions> configuration) { [NotNull] Action<IFluentCspOptions> configuration) {
if (builder == null) {
throw new ArgumentNullException(nameof(builder));
}
if (configuration == null) {
throw new ArgumentNullException(nameof(configuration));
}
return builder.AddModule("NWebsec", 5, app => { return builder.AddModule("NWebsec", 5, app => {
// Insert a new middleware responsible of setting the Content-Security-Policy header. // Insert a new middleware responsible of setting the Content-Security-Policy header.
// See https://nwebsec.codeplex.com/wikipage?title=Configuring%20Content%20Security%20Policy&referringTitle=NWebsec // See https://nwebsec.codeplex.com/wikipage?title=Configuring%20Content%20Security%20Policy&referringTitle=NWebsec
@ -36,7 +48,10 @@ namespace Microsoft.AspNet.Builder {
} }
public static OpenIddictBuilder UseCors([NotNull] this OpenIddictBuilder builder) { public static OpenIddictBuilder UseCors([NotNull] this OpenIddictBuilder builder) {
//Add CORS to the app if (builder == null) {
throw new ArgumentNullException(nameof(builder));
}
builder.AddModule("CORS", -10, map => map.UseCors(options => { builder.AddModule("CORS", -10, map => map.UseCors(options => {
options.AllowAnyHeader(); options.AllowAnyHeader();
options.AllowAnyMethod(); options.AllowAnyMethod();

17
src/OpenIddict.Security/project.json

@ -4,19 +4,20 @@
"description": "Security headers module for OpenIddict.", "description": "Security headers module for OpenIddict.",
"dependencies": { "dependencies": {
"JetBrains.Annotations": "10.1.2-eap",
"OpenIddict.Core": "1.0.0-*", "OpenIddict.Core": "1.0.0-*",
"NWebsec": { "NWebsec": {
"type": "build", "type": "build",
"version": "1.0.0-internal-*" "version": "1.0.0-internal-*"
},
"Microsoft.Extensions.NotNullAttribute.Sources": {
"type": "build",
"version": "1.0.0-*"
} }
}, },
"frameworks": { "frameworks": {
"dnx451": { }, "net451": { },
"dnxcore50": { }
} "dotnet5.4": {
"imports": "portable-net451+win8"
}
}
} }

24
src/OpenIddict/OpenIddictExtensions.cs

@ -1,17 +1,21 @@
/* /*
* Licensed under the Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0) * Licensed under the Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
* See https://github.com/openiddict/core for more information concerning * See https://github.com/openiddict/openiddict-core for more information concerning
* the license and the contributors participating to this project. * the license and the contributors participating to this project.
*/ */
using System; using System;
using Microsoft.AspNet.Identity; using JetBrains.Annotations;
using Microsoft.Extensions.Internal; using Microsoft.AspNetCore.Identity;
using OpenIddict.Models; using OpenIddict.Models;
namespace Microsoft.AspNet.Builder { namespace Microsoft.AspNetCore.Builder {
public static class OpenIddictExtensions { public static class OpenIddictExtensions {
public static IdentityBuilder AddOpenIddict([NotNull] this IdentityBuilder builder) { public static IdentityBuilder AddOpenIddict([NotNull] this IdentityBuilder builder) {
if (builder == null) {
throw new ArgumentNullException(nameof(builder));
}
return builder.AddOpenIddictCore<Application>(configuration => { return builder.AddOpenIddictCore<Application>(configuration => {
// Use the EF adapter by default. // Use the EF adapter by default.
configuration.UseEntityFramework(); configuration.UseEntityFramework();
@ -20,6 +24,10 @@ namespace Microsoft.AspNet.Builder {
public static IdentityBuilder AddOpenIddict<TApplication>([NotNull] this IdentityBuilder builder) public static IdentityBuilder AddOpenIddict<TApplication>([NotNull] this IdentityBuilder builder)
where TApplication : Application { where TApplication : Application {
if (builder == null) {
throw new ArgumentNullException(nameof(builder));
}
return builder.AddOpenIddictCore<TApplication>(configuration => { return builder.AddOpenIddictCore<TApplication>(configuration => {
// Use the EF adapter by default. // Use the EF adapter by default.
configuration.UseEntityFramework(); configuration.UseEntityFramework();
@ -33,6 +41,14 @@ namespace Microsoft.AspNet.Builder {
public static IApplicationBuilder UseOpenIddict( public static IApplicationBuilder UseOpenIddict(
[NotNull] this IApplicationBuilder app, [NotNull] this IApplicationBuilder app,
[NotNull] Action<OpenIddictBuilder> configuration) { [NotNull] Action<OpenIddictBuilder> configuration) {
if (app == null) {
throw new ArgumentNullException(nameof(app));
}
if (configuration == null) {
throw new ArgumentNullException(nameof(configuration));
}
return app.UseOpenIddictCore(builder => { return app.UseOpenIddictCore(builder => {
builder.UseAssets(); builder.UseAssets();
builder.UseCors(); builder.UseCors();

15
src/OpenIddict/project.json

@ -4,19 +4,18 @@
"description": "Easy-to-use OpenID Connect server for ASP.NET 5.", "description": "Easy-to-use OpenID Connect server for ASP.NET 5.",
"dependencies": { "dependencies": {
"JetBrains.Annotations": "10.1.2-eap",
"OpenIddict.Assets": "1.0.0-*", "OpenIddict.Assets": "1.0.0-*",
"OpenIddict.EF": "1.0.0-*", "OpenIddict.EF": "1.0.0-*",
"OpenIddict.Mvc": "1.0.0-*", "OpenIddict.Mvc": "1.0.0-*",
"OpenIddict.Security": "1.0.0-*", "OpenIddict.Security": "1.0.0-*"
"Microsoft.Extensions.NotNullAttribute.Sources": {
"type": "build",
"version": "1.0.0-*"
}
}, },
"frameworks": { "frameworks": {
"dnx451": { }, "net451": { },
"dnxcore50": { }
"dotnet5.6": {
"imports": "portable-net451+win8"
}
} }
} }
Loading…
Cancel
Save