├── .config └── tsaoptions.json ├── .gitignore ├── .nuget ├── NuGet.targets └── nuget.exe ├── CODE-OF-CONDUCT.md ├── License.txt ├── Microsoft.AspNet.Identity.sln ├── Microsoft.AspNet.Identity.vssscc ├── NuGet.Config ├── README.md ├── SECURITY.md ├── ci.yml ├── src ├── Microsoft.AspNet.Identity.Core │ ├── 35MSSharedLib1024.snk │ ├── AsyncHelper.cs │ ├── ClaimsIdentityFactory.cs │ ├── Crypto.cs │ ├── DefaultAuthenticationTypes.cs │ ├── EmailTokenProvider.cs │ ├── Extensions │ │ ├── IIdentityMessageServiceExtensions.cs │ │ ├── IdentityExtensions.cs │ │ ├── RoleManagerExtensions.cs │ │ └── UserManagerExtensions.cs │ ├── GlobalSuppressions.cs │ ├── IClaimsIdentityFactory.cs │ ├── IIdentityMessageService.cs │ ├── IIdentityValidator.cs │ ├── IPasswordHasher.cs │ ├── IQueryableRoleStore.cs │ ├── IQueryableUserStore.cs │ ├── IRole.cs │ ├── IRoleStore.cs │ ├── IUser.cs │ ├── IUserClaimStore.cs │ ├── IUserEmailStore.cs │ ├── IUserLockoutStore.cs │ ├── IUserLoginStore.cs │ ├── IUserPasswordStore.cs │ ├── IUserPhoneNumberStore.cs │ ├── IUserRoleStore.cs │ ├── IUserSecurityStampStore.cs │ ├── IUserStore.cs │ ├── IUserTokenProvider.cs │ ├── IUserTwoFactorStore.cs │ ├── IdentityResult.cs │ ├── Microsoft.AspNet.Identity.Core.csproj │ ├── MinimumLengthValidator.cs │ ├── PasswordHasher.cs │ ├── PasswordValidator.cs │ ├── PasswordVerificationResult.cs │ ├── PhoneNumberTokenProvider.cs │ ├── Properties │ │ └── AssemblyInfo.cs │ ├── Resources.Designer.cs │ ├── Resources.resx │ ├── Rfc6238AuthenticationService.cs │ ├── RoleManager.cs │ ├── RoleValidator.cs │ ├── TaskExtensions.cs │ ├── TotpSecurityStampBasedTokenProvider.cs │ ├── UserLoginInfo.cs │ ├── UserManager.cs │ └── UserValidator.cs ├── Microsoft.AspNet.Identity.EntityFramework │ ├── 35MSSharedLib1024.snk │ ├── App.config │ ├── EntityStore.cs │ ├── GlobalSuppressions.cs │ ├── IdentityDbContext.cs │ ├── IdentityResources.Designer.cs │ ├── IdentityResources.resx │ ├── IdentityRole.cs │ ├── IdentityUser.cs │ ├── IdentityUserClaim.cs │ ├── IdentityUserLogin.cs │ ├── IdentityUserRole.cs │ ├── Microsoft.AspNet.Identity.EntityFramework.csproj │ ├── Properties │ │ └── AssemblyInfo.cs │ ├── RoleStore.cs │ ├── UserStore.cs │ └── packages.config └── Microsoft.AspNet.Identity.Owin │ ├── 35MSSharedLib1024.snk │ ├── DataProtectorTokenProvider.cs │ ├── Extensions │ ├── AppBuilderExtensions.cs │ ├── AuthenticationManagerExtensions.cs │ ├── OwinContextExtensions.cs │ └── SignInManagerExtensions.cs │ ├── ExternalLoginInfo.cs │ ├── GlobalSuppressions.cs │ ├── IIdentityFactoryProvider.cs │ ├── IdentityFactoryMiddleware.cs │ ├── IdentityFactoryOptions.cs │ ├── IdentityFactoryProvider.cs │ ├── Microsoft.AspNet.Identity.Owin.csproj │ ├── Properties │ └── AssemblyInfo.cs │ ├── SecurityStampValidator.cs │ ├── SignInManager.cs │ ├── SignInStatus.cs │ ├── app.config │ └── packages.config ├── test └── Identity.Test │ ├── 35MSSharedLib1024.snk │ ├── App.config │ ├── ApplicationUserTest.cs │ ├── AsyncHelperTest.cs │ ├── AuthenticationManagerExtensionsTest.cs │ ├── ClaimsIdentityFactoryTest.cs │ ├── CustomGuidKeyTest.cs │ ├── CustomIntKeyTest.cs │ ├── ExceptionHelper.cs │ ├── Identity.Test.csproj │ ├── IdentityDbContextTest.cs │ ├── IdentityExtensionsTest.cs │ ├── IdentityResultTest.cs │ ├── InMemoryStore.cs │ ├── InMemoryStoreTest.cs │ ├── LoginsTest.cs │ ├── OwinContextExtensionsTest.cs │ ├── PasswordValidatorTest.cs │ ├── Properties │ └── AssemblyInfo.cs │ ├── RolesTest.cs │ ├── SecurityStampTest.cs │ ├── SignInManagerTest.cs │ ├── TestUtil.cs │ ├── UnitTestHelper.cs │ ├── UserClaimsTest.cs │ ├── UserLockoutStoreTests.cs │ ├── UserManagerTest.cs │ ├── UserStoreTest.cs │ └── packages.config └── unittest.testsettings /.config/tsaoptions.json: -------------------------------------------------------------------------------- 1 | { 2 | "areaPath": "DevDiv\\ASP.NET Core\\Policy Violations", 3 | "codebaseName": "AspNetIdentity", 4 | "instanceUrl": "https://devdiv.visualstudio.com/", 5 | "iterationPath": "DevDiv", 6 | "notificationAliases": [ 7 | "aspnetcore-build@microsoft.com" 8 | ], 9 | "projectName": "DEVDIV", 10 | "repositoryName": "AspNetIdentity", 11 | "template": "TFSDEVDIV" 12 | } 13 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | [Oo]bj/ 2 | [Bb]in/ 3 | packages/ -------------------------------------------------------------------------------- /.nuget/nuget.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aspnet/AspNetIdentity/a9b3a489e0942f09a2ab473039a9183ba095188d/.nuget/nuget.exe -------------------------------------------------------------------------------- /CODE-OF-CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Code of Conduct 2 | 3 | This project has adopted the code of conduct defined by the Contributor Covenant 4 | to clarify expected behavior in our community. 5 | 6 | For more information, see the [.NET Foundation Code of Conduct](https://dotnetfoundation.org/code-of-conduct). 7 | -------------------------------------------------------------------------------- /License.txt: -------------------------------------------------------------------------------- 1 | [ASP.NET Identity] 2 | Copyright (c) Microsoft Corporation 3 | All rights reserved. 4 | MIT License 5 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the Software), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 6 | 7 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 8 | 9 | THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 10 | 11 | -------------------------------------------------------------------------------- /Microsoft.AspNet.Identity.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio 2013 4 | VisualStudioVersion = 12.0.30408.0 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Microsoft.AspNet.Identity.Core", "src\Microsoft.AspNet.Identity.Core\Microsoft.AspNet.Identity.Core.csproj", "{D2F24972-0F56-4C18-BD65-C26A320A0C68}" 7 | EndProject 8 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{0C1D4BD7-0771-4899-AF55-43D8791660A0}" 9 | EndProject 10 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Microsoft.AspNet.Identity.EntityFramework", "src\Microsoft.AspNet.Identity.EntityFramework\Microsoft.AspNet.Identity.EntityFramework.csproj", "{D7298DAD-AB04-4502-9567-0461D0AD059E}" 11 | EndProject 12 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "test", "test", "{FD5D1AFD-204F-4504-B8F3-74C2E1EEC848}" 13 | EndProject 14 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{8883A4C2-A8DF-4F24-ADF7-DAEBFBEFD21B}" 15 | ProjectSection(SolutionItems) = preProject 16 | License.txt = License.txt 17 | unittest.testsettings = unittest.testsettings 18 | EndProjectSection 19 | EndProject 20 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Microsoft.AspNet.Identity.Owin", "src\Microsoft.AspNet.Identity.Owin\Microsoft.AspNet.Identity.Owin.csproj", "{943170EB-F4E7-4A6D-989E-2CF6C681DD89}" 21 | EndProject 22 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Identity.Test", "test\Identity.Test\Identity.Test.csproj", "{A7082BDD-985B-47B9-915B-7FA4CF541B5E}" 23 | EndProject 24 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = ".nuget", ".nuget", "{99DB175F-B1B4-4C9B-9D4A-C21F1ED2FB86}" 25 | ProjectSection(SolutionItems) = preProject 26 | .nuget\NuGet.Config = .nuget\NuGet.Config 27 | .nuget\NuGet.exe = .nuget\NuGet.exe 28 | .nuget\NuGet.targets = .nuget\NuGet.targets 29 | .nuget\packages.config = .nuget\packages.config 30 | EndProjectSection 31 | EndProject 32 | Global 33 | GlobalSection(TeamFoundationVersionControl) = preSolution 34 | SccNumberOfProjects = 5 35 | SccEnterpriseProvider = {4CA58AB2-18FA-4F8D-95D4-32DDF27D184C} 36 | SccTeamFoundationServer = https://tfs.codeplex.com/tfs/tfs18 37 | SccLocalPath0 = . 38 | SccProjectUniqueName1 = src\\Microsoft.AspNet.Identity.Core\\Microsoft.AspNet.Identity.Core.csproj 39 | SccProjectTopLevelParentUniqueName1 = Microsoft.AspNet.Identity.sln 40 | SccProjectName1 = src/Microsoft.AspNet.Identity.Core 41 | SccLocalPath1 = src\\Microsoft.AspNet.Identity.Core 42 | SccProjectUniqueName2 = src\\Microsoft.AspNet.Identity.EntityFramework\\Microsoft.AspNet.Identity.EntityFramework.csproj 43 | SccProjectTopLevelParentUniqueName2 = Microsoft.AspNet.Identity.sln 44 | SccProjectName2 = src/Microsoft.AspNet.Identity.EntityFramework 45 | SccLocalPath2 = src\\Microsoft.AspNet.Identity.EntityFramework 46 | SccProjectUniqueName3 = src\\Microsoft.AspNet.Identity.Owin\\Microsoft.AspNet.Identity.Owin.csproj 47 | SccProjectTopLevelParentUniqueName3 = Microsoft.AspNet.Identity.sln 48 | SccProjectName3 = src/Microsoft.AspNet.Identity.Owin 49 | SccLocalPath3 = src\\Microsoft.AspNet.Identity.Owin 50 | SccProjectUniqueName4 = test\\Identity.Test\\Identity.Test.csproj 51 | SccProjectTopLevelParentUniqueName4 = Microsoft.AspNet.Identity.sln 52 | SccProjectName4 = test/Identity.Test 53 | SccLocalPath4 = test\\Identity.Test 54 | EndGlobalSection 55 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 56 | Debug|Any CPU = Debug|Any CPU 57 | Release|Any CPU = Release|Any CPU 58 | EndGlobalSection 59 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 60 | {D2F24972-0F56-4C18-BD65-C26A320A0C68}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 61 | {D2F24972-0F56-4C18-BD65-C26A320A0C68}.Debug|Any CPU.Build.0 = Debug|Any CPU 62 | {D2F24972-0F56-4C18-BD65-C26A320A0C68}.Release|Any CPU.ActiveCfg = Release|Any CPU 63 | {D2F24972-0F56-4C18-BD65-C26A320A0C68}.Release|Any CPU.Build.0 = Release|Any CPU 64 | {D7298DAD-AB04-4502-9567-0461D0AD059E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 65 | {D7298DAD-AB04-4502-9567-0461D0AD059E}.Debug|Any CPU.Build.0 = Debug|Any CPU 66 | {D7298DAD-AB04-4502-9567-0461D0AD059E}.Release|Any CPU.ActiveCfg = Release|Any CPU 67 | {D7298DAD-AB04-4502-9567-0461D0AD059E}.Release|Any CPU.Build.0 = Release|Any CPU 68 | {943170EB-F4E7-4A6D-989E-2CF6C681DD89}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 69 | {943170EB-F4E7-4A6D-989E-2CF6C681DD89}.Debug|Any CPU.Build.0 = Debug|Any CPU 70 | {943170EB-F4E7-4A6D-989E-2CF6C681DD89}.Release|Any CPU.ActiveCfg = Release|Any CPU 71 | {943170EB-F4E7-4A6D-989E-2CF6C681DD89}.Release|Any CPU.Build.0 = Release|Any CPU 72 | {A7082BDD-985B-47B9-915B-7FA4CF541B5E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 73 | {A7082BDD-985B-47B9-915B-7FA4CF541B5E}.Debug|Any CPU.Build.0 = Debug|Any CPU 74 | {A7082BDD-985B-47B9-915B-7FA4CF541B5E}.Release|Any CPU.ActiveCfg = Release|Any CPU 75 | {A7082BDD-985B-47B9-915B-7FA4CF541B5E}.Release|Any CPU.Build.0 = Release|Any CPU 76 | EndGlobalSection 77 | GlobalSection(SolutionProperties) = preSolution 78 | HideSolutionNode = FALSE 79 | EndGlobalSection 80 | GlobalSection(NestedProjects) = preSolution 81 | {D2F24972-0F56-4C18-BD65-C26A320A0C68} = {0C1D4BD7-0771-4899-AF55-43D8791660A0} 82 | {D7298DAD-AB04-4502-9567-0461D0AD059E} = {0C1D4BD7-0771-4899-AF55-43D8791660A0} 83 | {943170EB-F4E7-4A6D-989E-2CF6C681DD89} = {0C1D4BD7-0771-4899-AF55-43D8791660A0} 84 | {A7082BDD-985B-47B9-915B-7FA4CF541B5E} = {FD5D1AFD-204F-4504-B8F3-74C2E1EEC848} 85 | EndGlobalSection 86 | GlobalSection(TestCaseManagementSettings) = postSolution 87 | CategoryFile = Microsoft.AspNet.Identity.vsmdi 88 | EndGlobalSection 89 | EndGlobal 90 | -------------------------------------------------------------------------------- /Microsoft.AspNet.Identity.vssscc: -------------------------------------------------------------------------------- 1 | "" 2 | { 3 | "FILE_VERSION" = "9237" 4 | "ENLISTMENT_CHOICE" = "NEVER" 5 | "PROJECT_FILE_RELATIVE_PATH" = "" 6 | "NUMBER_OF_EXCLUDED_FILES" = "0" 7 | "ORIGINAL_PROJECT_FILE_PATH" = "" 8 | "NUMBER_OF_NESTED_PROJECTS" = "0" 9 | "SOURCE_CONTROL_SETTINGS_PROVIDER" = "PROJECT" 10 | } 11 | -------------------------------------------------------------------------------- /NuGet.Config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | This repo contains the source code for ASP.NET Identity 2.1, which used to live at: https://aspnetidentity.codeplex.com/ 2 | -------------------------------------------------------------------------------- /SECURITY.md: -------------------------------------------------------------------------------- 1 | # Security Policy 2 | 3 | ## Supported Versions 4 | 5 | The .NET Core and ASP.NET Core support policy, including supported versions can be found at the [.NET Core Support Policy Page](https://dotnet.microsoft.com/platform/support/policy/dotnet-core). 6 | 7 | ## Reporting a Vulnerability 8 | 9 | Security issues and bugs should be reported privately to the Microsoft Security Response Center (MSRC), either by emailing secure@microsoft.com or via the portal at https://msrc.microsoft.com. 10 | You should receive a response within 24 hours. If for some reason you do not, please follow up via email to ensure we received your 11 | original message. Further information, including the MSRC PGP key, can be found in the [MSRC Report an Issue FAQ](https://www.microsoft.com/en-us/msrc/faqs-report-an-issue). 12 | 13 | Reports via MSRC may qualify for the .NET Core Bug Bounty. Details of the .NET Core Bug Bounty including terms and conditions are at [https://aka.ms/corebounty](https://aka.ms/corebounty). 14 | 15 | Please do not open issues for anything you think might have a security implication. 16 | -------------------------------------------------------------------------------- /ci.yml: -------------------------------------------------------------------------------- 1 | # Configure which branches trigger builds 2 | trigger: 3 | batch: true 4 | branches: 5 | include: 6 | - main 7 | 8 | variables: 9 | - name: TeamName 10 | value: AspNetCore 11 | 12 | resources: 13 | repositories: 14 | # Repo: 1ESPipelineTemplates/1ESPipelineTemplates 15 | - repository: 1esPipelines 16 | type: git 17 | name: 1ESPipelineTemplates/1ESPipelineTemplates 18 | ref: refs/tags/release 19 | extends: 20 | template: v1/1ES.Official.PipelineTemplate.yml@1esPipelines 21 | parameters: 22 | sdl: 23 | policheck: 24 | enabled: true 25 | tsa: 26 | enabled: true 27 | pool: 28 | name: NetCore1ESPool-Svc-Internal 29 | image: windows.vs2019.amd64 30 | os: windows 31 | stages: 32 | - stage: buildStage 33 | displayName: Build Stage 34 | jobs: 35 | - job: Build 36 | displayName: Windows Build 37 | timeoutInMinutes: 90 38 | workspace: 39 | clean: all 40 | steps: 41 | - script: echo "Hello World" 42 | displayName: Build Step 43 | -------------------------------------------------------------------------------- /src/Microsoft.AspNet.Identity.Core/35MSSharedLib1024.snk: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aspnet/AspNetIdentity/a9b3a489e0942f09a2ab473039a9183ba095188d/src/Microsoft.AspNet.Identity.Core/35MSSharedLib1024.snk -------------------------------------------------------------------------------- /src/Microsoft.AspNet.Identity.Core/AsyncHelper.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation, Inc. All rights reserved. 2 | // Licensed under the MIT License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using System; 5 | using System.Globalization; 6 | using System.Threading; 7 | using System.Threading.Tasks; 8 | 9 | namespace Microsoft.AspNet.Identity 10 | { 11 | internal static class AsyncHelper 12 | { 13 | private static readonly TaskFactory _myTaskFactory = new TaskFactory(CancellationToken.None, 14 | TaskCreationOptions.None, TaskContinuationOptions.None, TaskScheduler.Default); 15 | 16 | public static TResult RunSync(Func> func) 17 | { 18 | var cultureUi = CultureInfo.CurrentUICulture; 19 | var culture = CultureInfo.CurrentCulture; 20 | return _myTaskFactory.StartNew(() => 21 | { 22 | Thread.CurrentThread.CurrentCulture = culture; 23 | Thread.CurrentThread.CurrentUICulture = cultureUi; 24 | return func(); 25 | }).Unwrap().GetAwaiter().GetResult(); 26 | } 27 | 28 | public static void RunSync(Func func) 29 | { 30 | var cultureUi = CultureInfo.CurrentUICulture; 31 | var culture = CultureInfo.CurrentCulture; 32 | _myTaskFactory.StartNew(() => 33 | { 34 | Thread.CurrentThread.CurrentCulture = culture; 35 | Thread.CurrentThread.CurrentUICulture = cultureUi; 36 | return func(); 37 | }).Unwrap().GetAwaiter().GetResult(); 38 | } 39 | } 40 | } -------------------------------------------------------------------------------- /src/Microsoft.AspNet.Identity.Core/ClaimsIdentityFactory.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation, Inc. All rights reserved. 2 | // Licensed under the MIT License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using System; 5 | using System.Collections.Generic; 6 | using System.Security.Claims; 7 | using System.Threading.Tasks; 8 | 9 | namespace Microsoft.AspNet.Identity 10 | { 11 | /// 12 | /// Constants class 13 | /// 14 | public static class Constants 15 | { 16 | /// 17 | /// ClaimType used for the security stamp by default 18 | /// 19 | public const string DefaultSecurityStampClaimType = "AspNet.Identity.SecurityStamp"; 20 | } 21 | 22 | /// 23 | /// Creates a ClaimsIdentity from a User 24 | /// 25 | /// 26 | public class ClaimsIdentityFactory : ClaimsIdentityFactory where TUser : class, IUser 27 | { 28 | } 29 | 30 | /// 31 | /// Creates a ClaimsIdentity from a User 32 | /// 33 | /// 34 | /// 35 | public class ClaimsIdentityFactory : IClaimsIdentityFactory 36 | where TUser : class, IUser 37 | where TKey : IEquatable 38 | { 39 | internal const string IdentityProviderClaimType = 40 | "http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider"; 41 | 42 | internal const string DefaultIdentityProviderClaimValue = "ASP.NET Identity"; 43 | 44 | /// 45 | /// Constructor 46 | /// 47 | public ClaimsIdentityFactory() 48 | { 49 | RoleClaimType = ClaimsIdentity.DefaultRoleClaimType; 50 | UserIdClaimType = ClaimTypes.NameIdentifier; 51 | UserNameClaimType = ClaimsIdentity.DefaultNameClaimType; 52 | SecurityStampClaimType = Constants.DefaultSecurityStampClaimType; 53 | } 54 | 55 | /// 56 | /// Claim type used for role claims 57 | /// 58 | public string RoleClaimType { get; set; } 59 | 60 | /// 61 | /// Claim type used for the user name 62 | /// 63 | public string UserNameClaimType { get; set; } 64 | 65 | /// 66 | /// Claim type used for the user id 67 | /// 68 | public string UserIdClaimType { get; set; } 69 | 70 | /// 71 | /// Claim type used for the user security stamp 72 | /// 73 | public string SecurityStampClaimType { get; set; } 74 | 75 | /// 76 | /// Create a ClaimsIdentity from a user 77 | /// 78 | /// 79 | /// 80 | /// 81 | /// 82 | public virtual async Task CreateAsync(UserManager manager, TUser user, 83 | string authenticationType) 84 | { 85 | if (manager == null) 86 | { 87 | throw new ArgumentNullException("manager"); 88 | } 89 | if (user == null) 90 | { 91 | throw new ArgumentNullException("user"); 92 | } 93 | var id = new ClaimsIdentity(authenticationType, UserNameClaimType, RoleClaimType); 94 | id.AddClaim(new Claim(UserIdClaimType, ConvertIdToString(user.Id), ClaimValueTypes.String)); 95 | id.AddClaim(new Claim(UserNameClaimType, user.UserName, ClaimValueTypes.String)); 96 | id.AddClaim(new Claim(IdentityProviderClaimType, DefaultIdentityProviderClaimValue, ClaimValueTypes.String)); 97 | if (manager.SupportsUserSecurityStamp) 98 | { 99 | id.AddClaim(new Claim(SecurityStampClaimType, 100 | await manager.GetSecurityStampAsync(user.Id).WithCurrentCulture())); 101 | } 102 | if (manager.SupportsUserRole) 103 | { 104 | IList roles = await manager.GetRolesAsync(user.Id).WithCurrentCulture(); 105 | foreach (string roleName in roles) 106 | { 107 | id.AddClaim(new Claim(RoleClaimType, roleName, ClaimValueTypes.String)); 108 | } 109 | } 110 | if (manager.SupportsUserClaim) 111 | { 112 | id.AddClaims(await manager.GetClaimsAsync(user.Id).WithCurrentCulture()); 113 | } 114 | return id; 115 | } 116 | 117 | /// 118 | /// Convert the key to a string, by default just calls .ToString() 119 | /// 120 | /// 121 | /// 122 | public virtual string ConvertIdToString(TKey key) 123 | { 124 | if (key == null) 125 | { 126 | throw new ArgumentNullException("key"); 127 | } 128 | return key.ToString(); 129 | } 130 | } 131 | } -------------------------------------------------------------------------------- /src/Microsoft.AspNet.Identity.Core/Crypto.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation, Inc. All rights reserved. 2 | // Licensed under the MIT License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using System; 5 | using System.Runtime.CompilerServices; 6 | using System.Security.Cryptography; 7 | 8 | namespace Microsoft.AspNet.Identity 9 | { 10 | internal static class Crypto 11 | { 12 | private const int PBKDF2IterCount = 1000; // default for Rfc2898DeriveBytes 13 | private const int PBKDF2SubkeyLength = 256/8; // 256 bits 14 | private const int SaltSize = 128/8; // 128 bits 15 | 16 | /* ======================= 17 | * HASHED PASSWORD FORMATS 18 | * ======================= 19 | * 20 | * Version 0: 21 | * PBKDF2 with HMAC-SHA1, 128-bit salt, 256-bit subkey, 1000 iterations. 22 | * (See also: SDL crypto guidelines v5.1, Part III) 23 | * Format: { 0x00, salt, subkey } 24 | */ 25 | 26 | public static string HashPassword(string password) 27 | { 28 | if (password == null) 29 | { 30 | throw new ArgumentNullException("password"); 31 | } 32 | 33 | // Produce a version 0 (see comment above) text hash. 34 | byte[] salt; 35 | byte[] subkey; 36 | using (var deriveBytes = new Rfc2898DeriveBytes(password, SaltSize, PBKDF2IterCount)) 37 | { 38 | salt = deriveBytes.Salt; 39 | subkey = deriveBytes.GetBytes(PBKDF2SubkeyLength); 40 | } 41 | 42 | var outputBytes = new byte[1 + SaltSize + PBKDF2SubkeyLength]; 43 | Buffer.BlockCopy(salt, 0, outputBytes, 1, SaltSize); 44 | Buffer.BlockCopy(subkey, 0, outputBytes, 1 + SaltSize, PBKDF2SubkeyLength); 45 | return Convert.ToBase64String(outputBytes); 46 | } 47 | 48 | // hashedPassword must be of the format of HashWithPassword (salt + Hash(salt+input) 49 | public static bool VerifyHashedPassword(string hashedPassword, string password) 50 | { 51 | if (hashedPassword == null) 52 | { 53 | return false; 54 | } 55 | if (password == null) 56 | { 57 | throw new ArgumentNullException("password"); 58 | } 59 | 60 | var hashedPasswordBytes = Convert.FromBase64String(hashedPassword); 61 | 62 | // Verify a version 0 (see comment above) text hash. 63 | 64 | if (hashedPasswordBytes.Length != (1 + SaltSize + PBKDF2SubkeyLength) || hashedPasswordBytes[0] != 0x00) 65 | { 66 | // Wrong length or version header. 67 | return false; 68 | } 69 | 70 | var salt = new byte[SaltSize]; 71 | Buffer.BlockCopy(hashedPasswordBytes, 1, salt, 0, SaltSize); 72 | var storedSubkey = new byte[PBKDF2SubkeyLength]; 73 | Buffer.BlockCopy(hashedPasswordBytes, 1 + SaltSize, storedSubkey, 0, PBKDF2SubkeyLength); 74 | 75 | byte[] generatedSubkey; 76 | using (var deriveBytes = new Rfc2898DeriveBytes(password, salt, PBKDF2IterCount)) 77 | { 78 | generatedSubkey = deriveBytes.GetBytes(PBKDF2SubkeyLength); 79 | } 80 | return ByteArraysEqual(storedSubkey, generatedSubkey); 81 | } 82 | 83 | // Compares two byte arrays for equality. The method is specifically written so that the loop is not optimized. 84 | [MethodImpl(MethodImplOptions.NoOptimization)] 85 | private static bool ByteArraysEqual(byte[] a, byte[] b) 86 | { 87 | if (ReferenceEquals(a, b)) 88 | { 89 | return true; 90 | } 91 | 92 | if (a == null || b == null || a.Length != b.Length) 93 | { 94 | return false; 95 | } 96 | 97 | var areSame = true; 98 | for (var i = 0; i < a.Length; i++) 99 | { 100 | areSame &= (a[i] == b[i]); 101 | } 102 | return areSame; 103 | } 104 | } 105 | } -------------------------------------------------------------------------------- /src/Microsoft.AspNet.Identity.Core/DefaultAuthenticationTypes.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation, Inc. All rights reserved. 2 | // Licensed under the MIT License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | namespace Microsoft.AspNet.Identity 5 | { 6 | /// 7 | /// Default authentication types values 8 | /// 9 | public static class DefaultAuthenticationTypes 10 | { 11 | /// 12 | /// Default value for the main application cookie used by UseSignInCookies 13 | /// 14 | public const string ApplicationCookie = "ApplicationCookie"; 15 | 16 | /// 17 | /// Default value used for the ExternalSignInAuthenticationType configured by UseSignInCookies 18 | /// 19 | public const string ExternalCookie = "ExternalCookie"; 20 | 21 | /// 22 | /// Default value used by the UseOAuthBearerTokens method 23 | /// 24 | public const string ExternalBearer = "ExternalBearer"; 25 | 26 | /// 27 | /// Default value for authentication type used for two factor partial sign in 28 | /// 29 | public const string TwoFactorCookie = "TwoFactorCookie"; 30 | 31 | /// 32 | /// Default value for authentication type used for two factor remember browser 33 | /// 34 | public const string TwoFactorRememberBrowserCookie = "TwoFactorRememberBrowser"; 35 | } 36 | } -------------------------------------------------------------------------------- /src/Microsoft.AspNet.Identity.Core/EmailTokenProvider.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation, Inc. All rights reserved. 2 | // Licensed under the MIT License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using System; 5 | using System.Globalization; 6 | using System.Threading.Tasks; 7 | 8 | namespace Microsoft.AspNet.Identity 9 | { 10 | /// 11 | /// TokenProvider that generates tokens from the user's security stamp and notifies a user via their email 12 | /// 13 | /// 14 | public class EmailTokenProvider : EmailTokenProvider where TUser : class, IUser 15 | { 16 | } 17 | 18 | /// 19 | /// TokenProvider that generates tokens from the user's security stamp and notifies a user via their email 20 | /// 21 | /// 22 | /// 23 | public class EmailTokenProvider : TotpSecurityStampBasedTokenProvider 24 | where TUser : class, IUser 25 | where TKey : IEquatable 26 | { 27 | private string _body; 28 | private string _subject; 29 | 30 | /// 31 | /// Email subject used when a token notification is received 32 | /// 33 | public string Subject 34 | { 35 | get { return _subject ?? string.Empty; } 36 | set { _subject = value; } 37 | } 38 | 39 | /// 40 | /// Email body which should contain a formatted string which the token will be the only argument 41 | /// 42 | public string BodyFormat 43 | { 44 | get { return _body ?? "{0}"; } 45 | set { _body = value; } 46 | } 47 | 48 | /// 49 | /// True if the user has an email set 50 | /// 51 | /// 52 | /// 53 | /// 54 | public override async Task IsValidProviderForUserAsync(UserManager manager, TUser user) 55 | { 56 | var email = await manager.GetEmailAsync(user.Id).WithCurrentCulture(); 57 | return !String.IsNullOrWhiteSpace(email) && await manager.IsEmailConfirmedAsync(user.Id).WithCurrentCulture(); 58 | } 59 | 60 | /// 61 | /// Returns the email of the user for entropy in the token 62 | /// 63 | /// 64 | /// 65 | /// 66 | /// 67 | public override async Task GetUserModifierAsync(string purpose, UserManager manager, 68 | TUser user) 69 | { 70 | var email = await manager.GetEmailAsync(user.Id).WithCurrentCulture(); 71 | return "Email:" + purpose + ":" + email; 72 | } 73 | 74 | /// 75 | /// Notifies the user with a token via email using the Subject and BodyFormat 76 | /// 77 | /// 78 | /// 79 | /// 80 | /// 81 | public override Task NotifyAsync(string token, UserManager manager, TUser user) 82 | { 83 | if (manager == null) 84 | { 85 | throw new ArgumentNullException("manager"); 86 | } 87 | return manager.SendEmailAsync(user.Id, Subject, String.Format(CultureInfo.CurrentCulture, BodyFormat, token)); 88 | } 89 | } 90 | } -------------------------------------------------------------------------------- /src/Microsoft.AspNet.Identity.Core/Extensions/IIdentityMessageServiceExtensions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace Microsoft.AspNet.Identity 4 | { 5 | // Extension methods for IIdentityMessageService 6 | public static class IIdentityMessageServiceExtensions 7 | { 8 | /// 9 | /// Sync method to send the IdentityMessage 10 | /// 11 | /// 12 | /// 13 | public static void Send(this IIdentityMessageService service, IdentityMessage message) 14 | { 15 | if (service == null) 16 | { 17 | throw new ArgumentNullException("service"); 18 | } 19 | 20 | AsyncHelper.RunSync(() => service.SendAsync(message)); 21 | } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/Microsoft.AspNet.Identity.Core/Extensions/IdentityExtensions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Globalization; 3 | using System.Security.Claims; 4 | using System.Security.Principal; 5 | 6 | namespace Microsoft.AspNet.Identity 7 | { 8 | /// 9 | /// Extensions making it easier to get the user name/user id claims off of an identity 10 | /// 11 | public static class IdentityExtensions 12 | { 13 | /// 14 | /// Return the user name using the UserNameClaimType 15 | /// 16 | /// 17 | /// 18 | public static string GetUserName(this IIdentity identity) 19 | { 20 | if (identity == null) 21 | { 22 | throw new ArgumentNullException("identity"); 23 | } 24 | var ci = identity as ClaimsIdentity; 25 | if (ci != null) 26 | { 27 | return ci.FindFirstValue(ClaimsIdentity.DefaultNameClaimType); 28 | } 29 | return null; 30 | } 31 | 32 | /// 33 | /// Return the user id using the UserIdClaimType 34 | /// 35 | /// 36 | /// 37 | /// 38 | public static T GetUserId(this IIdentity identity) where T : IConvertible 39 | { 40 | if (identity == null) 41 | { 42 | throw new ArgumentNullException("identity"); 43 | } 44 | var ci = identity as ClaimsIdentity; 45 | if (ci != null) 46 | { 47 | var id = ci.FindFirstValue(ClaimTypes.NameIdentifier); 48 | if (id != null) 49 | { 50 | return (T)Convert.ChangeType(id, typeof(T), CultureInfo.InvariantCulture); 51 | } 52 | } 53 | return default(T); 54 | } 55 | 56 | /// 57 | /// Return the user id using the UserIdClaimType 58 | /// 59 | /// 60 | /// 61 | public static string GetUserId(this IIdentity identity) 62 | { 63 | if (identity == null) 64 | { 65 | throw new ArgumentNullException("identity"); 66 | } 67 | var ci = identity as ClaimsIdentity; 68 | if (ci != null) 69 | { 70 | return ci.FindFirstValue(ClaimTypes.NameIdentifier); 71 | } 72 | return null; 73 | } 74 | 75 | /// 76 | /// Return the claim value for the first claim with the specified type if it exists, null otherwise 77 | /// 78 | /// 79 | /// 80 | /// 81 | public static string FindFirstValue(this ClaimsIdentity identity, string claimType) 82 | { 83 | if (identity == null) 84 | { 85 | throw new ArgumentNullException("identity"); 86 | } 87 | var claim = identity.FindFirst(claimType); 88 | return claim != null ? claim.Value : null; 89 | } 90 | } 91 | } -------------------------------------------------------------------------------- /src/Microsoft.AspNet.Identity.Core/Extensions/RoleManagerExtensions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace Microsoft.AspNet.Identity 4 | { 5 | /// 6 | /// Extension methods for RoleManager 7 | /// 8 | public static class RoleManagerExtensions 9 | { 10 | /// 11 | /// Find a role by id 12 | /// 13 | /// 14 | /// 15 | /// 16 | public static TRole FindById(this RoleManager manager, TKey roleId) 17 | where TKey : IEquatable 18 | where TRole : class, IRole 19 | { 20 | if (manager == null) 21 | { 22 | throw new ArgumentNullException("manager"); 23 | } 24 | return AsyncHelper.RunSync(() => manager.FindByIdAsync(roleId)); 25 | } 26 | 27 | /// 28 | /// Find a role by name 29 | /// 30 | /// 31 | /// 32 | /// 33 | public static TRole FindByName(this RoleManager manager, string roleName) 34 | where TKey : IEquatable 35 | where TRole : class, IRole 36 | { 37 | if (manager == null) 38 | { 39 | throw new ArgumentNullException("manager"); 40 | } 41 | return AsyncHelper.RunSync(() => manager.FindByNameAsync(roleName)); 42 | } 43 | 44 | /// 45 | /// Create a role 46 | /// 47 | /// 48 | /// 49 | /// 50 | public static IdentityResult Create(this RoleManager manager, TRole role) 51 | where TKey : IEquatable 52 | where TRole : class, IRole 53 | { 54 | if (manager == null) 55 | { 56 | throw new ArgumentNullException("manager"); 57 | } 58 | return AsyncHelper.RunSync(() => manager.CreateAsync(role)); 59 | } 60 | 61 | /// 62 | /// Update an existing role 63 | /// 64 | /// 65 | /// 66 | /// 67 | public static IdentityResult Update(this RoleManager manager, TRole role) 68 | where TKey : IEquatable 69 | where TRole : class, IRole 70 | { 71 | if (manager == null) 72 | { 73 | throw new ArgumentNullException("manager"); 74 | } 75 | return AsyncHelper.RunSync(() => manager.UpdateAsync(role)); 76 | } 77 | 78 | /// 79 | /// Delete a role 80 | /// 81 | /// 82 | /// 83 | /// 84 | public static IdentityResult Delete(this RoleManager manager, TRole role) 85 | where TKey : IEquatable 86 | where TRole : class, IRole 87 | { 88 | if (manager == null) 89 | { 90 | throw new ArgumentNullException("manager"); 91 | } 92 | return AsyncHelper.RunSync(() => manager.DeleteAsync(role)); 93 | } 94 | 95 | /// 96 | /// Returns true if the role exists 97 | /// 98 | /// 99 | /// 100 | /// 101 | public static bool RoleExists(this RoleManager manager, string roleName) 102 | where TKey : IEquatable 103 | where TRole : class, IRole 104 | { 105 | if (manager == null) 106 | { 107 | throw new ArgumentNullException("manager"); 108 | } 109 | return AsyncHelper.RunSync(() => manager.RoleExistsAsync(roleName)); 110 | } 111 | } 112 | } -------------------------------------------------------------------------------- /src/Microsoft.AspNet.Identity.Core/GlobalSuppressions.cs: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aspnet/AspNetIdentity/a9b3a489e0942f09a2ab473039a9183ba095188d/src/Microsoft.AspNet.Identity.Core/GlobalSuppressions.cs -------------------------------------------------------------------------------- /src/Microsoft.AspNet.Identity.Core/IClaimsIdentityFactory.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation, Inc. All rights reserved. 2 | // Licensed under the MIT License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using System; 5 | using System.Security.Claims; 6 | using System.Threading.Tasks; 7 | 8 | namespace Microsoft.AspNet.Identity 9 | { 10 | /// 11 | /// Interface for creating a ClaimsIdentity from an IUser 12 | /// 13 | /// 14 | /// 15 | public interface IClaimsIdentityFactory 16 | where TUser : class, IUser 17 | where TKey : IEquatable 18 | { 19 | /// 20 | /// Create a ClaimsIdentity from an user using a UserManager 21 | /// 22 | /// 23 | /// 24 | /// 25 | /// 26 | Task CreateAsync(UserManager manager, TUser user, string authenticationType); 27 | } 28 | 29 | /// 30 | /// Interface for creating a ClaimsIdentity from a user 31 | /// 32 | /// 33 | public interface IClaimsIdentityFactory where TUser : class, IUser 34 | { 35 | /// 36 | /// Create a ClaimsIdentity from an user using a UserManager 37 | /// 38 | /// 39 | /// 40 | /// 41 | /// 42 | Task CreateAsync(UserManager manager, TUser user, string authenticationType); 43 | } 44 | } -------------------------------------------------------------------------------- /src/Microsoft.AspNet.Identity.Core/IIdentityMessageService.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation, Inc. All rights reserved. 2 | // Licensed under the MIT License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using System.Threading.Tasks; 5 | 6 | namespace Microsoft.AspNet.Identity 7 | { 8 | /// 9 | /// Expose a way to send messages (i.e. email/sms) 10 | /// 11 | public interface IIdentityMessageService 12 | { 13 | /// 14 | /// This method should send the message 15 | /// 16 | /// 17 | /// 18 | Task SendAsync(IdentityMessage message); 19 | } 20 | 21 | /// 22 | /// Represents a message 23 | /// 24 | public class IdentityMessage 25 | { 26 | /// 27 | /// Destination, i.e. To email, or SMS phone number 28 | /// 29 | public virtual string Destination { get; set; } 30 | 31 | /// 32 | /// Subject 33 | /// 34 | public virtual string Subject { get; set; } 35 | 36 | /// 37 | /// Message contents 38 | /// 39 | public virtual string Body { get; set; } 40 | } 41 | } -------------------------------------------------------------------------------- /src/Microsoft.AspNet.Identity.Core/IIdentityValidator.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation, Inc. All rights reserved. 2 | // Licensed under the MIT License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using System.Threading.Tasks; 5 | 6 | namespace Microsoft.AspNet.Identity 7 | { 8 | /// 9 | /// Used to validate an item 10 | /// 11 | /// 12 | public interface IIdentityValidator 13 | { 14 | /// 15 | /// Validate the item 16 | /// 17 | /// 18 | /// 19 | Task ValidateAsync(T item); 20 | } 21 | } -------------------------------------------------------------------------------- /src/Microsoft.AspNet.Identity.Core/IPasswordHasher.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation, Inc. All rights reserved. 2 | // Licensed under the MIT License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | namespace Microsoft.AspNet.Identity 5 | { 6 | /// 7 | /// Abstraction for password hashing methods 8 | /// 9 | public interface IPasswordHasher 10 | { 11 | /// 12 | /// Hash a password 13 | /// 14 | /// 15 | /// 16 | string HashPassword(string password); 17 | 18 | /// 19 | /// Verify that a password matches the hashed password 20 | /// 21 | /// 22 | /// 23 | /// 24 | PasswordVerificationResult VerifyHashedPassword(string hashedPassword, string providedPassword); 25 | } 26 | } -------------------------------------------------------------------------------- /src/Microsoft.AspNet.Identity.Core/IQueryableRoleStore.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation, Inc. All rights reserved. 2 | // Licensed under the MIT License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using System.Linq; 5 | 6 | namespace Microsoft.AspNet.Identity 7 | { 8 | /// 9 | /// Interface that exposes an IQueryable roles 10 | /// 11 | /// 12 | public interface IQueryableRoleStore : IQueryableRoleStore where TRole : IRole 13 | { 14 | } 15 | 16 | /// 17 | /// Interface that exposes an IQueryable roles 18 | /// 19 | /// 20 | /// 21 | public interface IQueryableRoleStore : IRoleStore where TRole : IRole 22 | { 23 | /// 24 | /// IQueryable Roles 25 | /// 26 | IQueryable Roles { get; } 27 | } 28 | } -------------------------------------------------------------------------------- /src/Microsoft.AspNet.Identity.Core/IQueryableUserStore.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation, Inc. All rights reserved. 2 | // Licensed under the MIT License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using System.Linq; 5 | 6 | namespace Microsoft.AspNet.Identity 7 | { 8 | /// 9 | /// Interface that exposes an IQueryable users 10 | /// 11 | /// 12 | public interface IQueryableUserStore : IQueryableUserStore where TUser : class, IUser 13 | { 14 | } 15 | 16 | /// 17 | /// Interface that exposes an IQueryable users 18 | /// 19 | /// 20 | /// 21 | public interface IQueryableUserStore : IUserStore where TUser : class, IUser 22 | { 23 | /// 24 | /// IQueryable users 25 | /// 26 | IQueryable Users { get; } 27 | } 28 | } -------------------------------------------------------------------------------- /src/Microsoft.AspNet.Identity.Core/IRole.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation, Inc. All rights reserved. 2 | // Licensed under the MIT License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | namespace Microsoft.AspNet.Identity 5 | { 6 | /// 7 | /// Mimimal set of data needed to persist role information 8 | /// 9 | public interface IRole : IRole 10 | { 11 | } 12 | 13 | /// 14 | /// Mimimal set of data needed to persist role information 15 | /// 16 | /// 17 | public interface IRole 18 | { 19 | /// 20 | /// Id of the role 21 | /// 22 | TKey Id { get; } 23 | 24 | /// 25 | /// Name of the role 26 | /// 27 | string Name { get; set; } 28 | } 29 | } -------------------------------------------------------------------------------- /src/Microsoft.AspNet.Identity.Core/IRoleStore.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation, Inc. All rights reserved. 2 | // Licensed under the MIT License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using System; 5 | using System.Threading.Tasks; 6 | 7 | namespace Microsoft.AspNet.Identity 8 | { 9 | /// 10 | /// Interface that exposes basic role management 11 | /// 12 | /// 13 | public interface IRoleStore : IRoleStore where TRole : IRole 14 | { 15 | } 16 | 17 | /// 18 | /// Interface that exposes basic role management 19 | /// 20 | /// 21 | /// 22 | public interface IRoleStore : IDisposable where TRole : IRole 23 | { 24 | /// 25 | /// Create a new role 26 | /// 27 | /// 28 | /// 29 | Task CreateAsync(TRole role); 30 | 31 | /// 32 | /// Update a role 33 | /// 34 | /// 35 | /// 36 | Task UpdateAsync(TRole role); 37 | 38 | /// 39 | /// Delete a role 40 | /// 41 | /// 42 | /// 43 | Task DeleteAsync(TRole role); 44 | 45 | /// 46 | /// Find a role by id 47 | /// 48 | /// 49 | /// 50 | Task FindByIdAsync(TKey roleId); 51 | 52 | /// 53 | /// Find a role by name 54 | /// 55 | /// 56 | /// 57 | Task FindByNameAsync(string roleName); 58 | } 59 | } -------------------------------------------------------------------------------- /src/Microsoft.AspNet.Identity.Core/IUser.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation, Inc. All rights reserved. 2 | // Licensed under the MIT License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | namespace Microsoft.AspNet.Identity 5 | { 6 | /// 7 | /// Minimal interface for a user with id and username 8 | /// 9 | public interface IUser : IUser 10 | { 11 | } 12 | 13 | /// 14 | /// Minimal interface for a user with id and username 15 | /// 16 | /// 17 | public interface IUser 18 | { 19 | /// 20 | /// Unique key for the user 21 | /// 22 | TKey Id { get; } 23 | 24 | /// 25 | /// Unique username 26 | /// 27 | string UserName { get; set; } 28 | } 29 | } -------------------------------------------------------------------------------- /src/Microsoft.AspNet.Identity.Core/IUserClaimStore.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation, Inc. All rights reserved. 2 | // Licensed under the MIT License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using System.Collections.Generic; 5 | using System.Security.Claims; 6 | using System.Threading.Tasks; 7 | 8 | namespace Microsoft.AspNet.Identity 9 | { 10 | /// 11 | /// Stores user specific claims 12 | /// 13 | /// 14 | public interface IUserClaimStore : IUserClaimStore where TUser : class, IUser 15 | { 16 | } 17 | 18 | /// 19 | /// Stores user specific claims 20 | /// 21 | /// 22 | /// 23 | public interface IUserClaimStore : IUserStore where TUser : class, IUser 24 | { 25 | /// 26 | /// Returns the claims for the user with the issuer set 27 | /// 28 | /// 29 | /// 30 | Task> GetClaimsAsync(TUser user); 31 | 32 | /// 33 | /// Add a new user claim 34 | /// 35 | /// 36 | /// 37 | /// 38 | Task AddClaimAsync(TUser user, Claim claim); 39 | 40 | /// 41 | /// Remove a user claim 42 | /// 43 | /// 44 | /// 45 | /// 46 | Task RemoveClaimAsync(TUser user, Claim claim); 47 | } 48 | } -------------------------------------------------------------------------------- /src/Microsoft.AspNet.Identity.Core/IUserEmailStore.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation, Inc. All rights reserved. 2 | // Licensed under the MIT License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using System.Threading.Tasks; 5 | 6 | namespace Microsoft.AspNet.Identity 7 | { 8 | /// 9 | /// Stores a user's email 10 | /// 11 | /// 12 | public interface IUserEmailStore : IUserEmailStore where TUser : class, IUser 13 | { 14 | } 15 | 16 | /// 17 | /// Stores a user's email 18 | /// 19 | /// 20 | /// 21 | public interface IUserEmailStore : IUserStore where TUser : class, IUser 22 | { 23 | /// 24 | /// Set the user email 25 | /// 26 | /// 27 | /// 28 | /// 29 | Task SetEmailAsync(TUser user, string email); 30 | 31 | /// 32 | /// Get the user email 33 | /// 34 | /// 35 | /// 36 | Task GetEmailAsync(TUser user); 37 | 38 | /// 39 | /// Returns true if the user email is confirmed 40 | /// 41 | /// 42 | /// 43 | Task GetEmailConfirmedAsync(TUser user); 44 | 45 | /// 46 | /// Sets whether the user email is confirmed 47 | /// 48 | /// 49 | /// 50 | /// 51 | Task SetEmailConfirmedAsync(TUser user, bool confirmed); 52 | 53 | /// 54 | /// Returns the user associated with this email 55 | /// 56 | /// 57 | /// 58 | Task FindByEmailAsync(string email); 59 | } 60 | } -------------------------------------------------------------------------------- /src/Microsoft.AspNet.Identity.Core/IUserLockoutStore.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation, Inc. All rights reserved. 2 | // Licensed under the MIT License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using System; 5 | using System.Threading.Tasks; 6 | 7 | namespace Microsoft.AspNet.Identity 8 | { 9 | /// 10 | /// Stores information which can be used to implement account lockout, including access failures and lockout status 11 | /// 12 | /// 13 | /// 14 | public interface IUserLockoutStore : IUserStore where TUser : class, IUser 15 | { 16 | /// 17 | /// Returns the DateTimeOffset that represents the end of a user's lockout, any time in the past should be considered 18 | /// not locked out. 19 | /// 20 | /// 21 | /// 22 | Task GetLockoutEndDateAsync(TUser user); 23 | 24 | /// 25 | /// Locks a user out until the specified end date (set to a past date, to unlock a user) 26 | /// 27 | /// 28 | /// 29 | /// 30 | Task SetLockoutEndDateAsync(TUser user, DateTimeOffset lockoutEnd); 31 | 32 | /// 33 | /// Used to record when an attempt to access the user has failed 34 | /// 35 | /// 36 | /// 37 | Task IncrementAccessFailedCountAsync(TUser user); 38 | 39 | /// 40 | /// Used to reset the access failed count, typically after the account is successfully accessed 41 | /// 42 | /// 43 | /// 44 | Task ResetAccessFailedCountAsync(TUser user); 45 | 46 | /// 47 | /// Returns the current number of failed access attempts. This number usually will be reset whenever the password is 48 | /// verified or the account is locked out. 49 | /// 50 | /// 51 | /// 52 | Task GetAccessFailedCountAsync(TUser user); 53 | 54 | /// 55 | /// Returns whether the user can be locked out. 56 | /// 57 | /// 58 | /// 59 | Task GetLockoutEnabledAsync(TUser user); 60 | 61 | /// 62 | /// Sets whether the user can be locked out. 63 | /// 64 | /// 65 | /// 66 | /// 67 | Task SetLockoutEnabledAsync(TUser user, bool enabled); 68 | } 69 | } -------------------------------------------------------------------------------- /src/Microsoft.AspNet.Identity.Core/IUserLoginStore.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation, Inc. All rights reserved. 2 | // Licensed under the MIT License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using System.Collections.Generic; 5 | using System.Threading.Tasks; 6 | 7 | namespace Microsoft.AspNet.Identity 8 | { 9 | /// 10 | /// Interface that maps users to login providers, i.e. Google, Facebook, Twitter, Microsoft 11 | /// 12 | /// 13 | public interface IUserLoginStore : IUserLoginStore where TUser : class, IUser 14 | { 15 | } 16 | 17 | /// 18 | /// Interface that maps users to login providers, i.e. Google, Facebook, Twitter, Microsoft 19 | /// 20 | /// 21 | /// 22 | public interface IUserLoginStore : IUserStore where TUser : class, IUser 23 | { 24 | /// 25 | /// Adds a user login with the specified provider and key 26 | /// 27 | /// 28 | /// 29 | /// 30 | Task AddLoginAsync(TUser user, UserLoginInfo login); 31 | 32 | /// 33 | /// Removes the user login with the specified combination if it exists 34 | /// 35 | /// 36 | /// 37 | /// 38 | Task RemoveLoginAsync(TUser user, UserLoginInfo login); 39 | 40 | /// 41 | /// Returns the linked accounts for this user 42 | /// 43 | /// 44 | /// 45 | Task> GetLoginsAsync(TUser user); 46 | 47 | /// 48 | /// Returns the user associated with this login 49 | /// 50 | /// 51 | Task FindAsync(UserLoginInfo login); 52 | } 53 | } -------------------------------------------------------------------------------- /src/Microsoft.AspNet.Identity.Core/IUserPasswordStore.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation, Inc. All rights reserved. 2 | // Licensed under the MIT License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using System.Threading.Tasks; 5 | 6 | namespace Microsoft.AspNet.Identity 7 | { 8 | /// 9 | /// Stores a user's password hash 10 | /// 11 | /// 12 | public interface IUserPasswordStore : IUserPasswordStore where TUser : class, IUser 13 | { 14 | } 15 | 16 | /// 17 | /// Stores a user's password hash 18 | /// 19 | /// 20 | /// 21 | public interface IUserPasswordStore : IUserStore where TUser : class, IUser 22 | { 23 | /// 24 | /// Set the user password hash 25 | /// 26 | /// 27 | /// 28 | /// 29 | Task SetPasswordHashAsync(TUser user, string passwordHash); 30 | 31 | /// 32 | /// Get the user password hash 33 | /// 34 | /// 35 | /// 36 | Task GetPasswordHashAsync(TUser user); 37 | 38 | /// 39 | /// Returns true if a user has a password set 40 | /// 41 | /// 42 | /// 43 | Task HasPasswordAsync(TUser user); 44 | } 45 | } -------------------------------------------------------------------------------- /src/Microsoft.AspNet.Identity.Core/IUserPhoneNumberStore.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation, Inc. All rights reserved. 2 | // Licensed under the MIT License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using System.Threading.Tasks; 5 | 6 | namespace Microsoft.AspNet.Identity 7 | { 8 | /// 9 | /// Stores a user's phone number 10 | /// 11 | /// 12 | public interface IUserPhoneNumberStore : IUserPhoneNumberStore 13 | where TUser : class, IUser 14 | { 15 | } 16 | 17 | /// 18 | /// Stores a user's phone number 19 | /// 20 | /// 21 | /// 22 | public interface IUserPhoneNumberStore : IUserStore where TUser : class, IUser 23 | { 24 | /// 25 | /// Set the user's phone number 26 | /// 27 | /// 28 | /// 29 | /// 30 | Task SetPhoneNumberAsync(TUser user, string phoneNumber); 31 | 32 | /// 33 | /// Get the user phone number 34 | /// 35 | /// 36 | /// 37 | Task GetPhoneNumberAsync(TUser user); 38 | 39 | /// 40 | /// Returns true if the user phone number is confirmed 41 | /// 42 | /// 43 | /// 44 | Task GetPhoneNumberConfirmedAsync(TUser user); 45 | 46 | /// 47 | /// Sets whether the user phone number is confirmed 48 | /// 49 | /// 50 | /// 51 | /// 52 | Task SetPhoneNumberConfirmedAsync(TUser user, bool confirmed); 53 | } 54 | } -------------------------------------------------------------------------------- /src/Microsoft.AspNet.Identity.Core/IUserRoleStore.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation, Inc. All rights reserved. 2 | // Licensed under the MIT License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using System.Collections.Generic; 5 | using System.Threading.Tasks; 6 | 7 | namespace Microsoft.AspNet.Identity 8 | { 9 | /// 10 | /// Interface that maps users to their roles 11 | /// 12 | /// 13 | public interface IUserRoleStore : IUserRoleStore where TUser : class, IUser 14 | { 15 | } 16 | 17 | /// 18 | /// Interface that maps users to their roles 19 | /// 20 | /// 21 | /// 22 | public interface IUserRoleStore : IUserStore where TUser : class, IUser 23 | { 24 | /// 25 | /// Adds a user to a role 26 | /// 27 | /// 28 | /// 29 | /// 30 | Task AddToRoleAsync(TUser user, string roleName); 31 | 32 | /// 33 | /// Removes the role for the user 34 | /// 35 | /// 36 | /// 37 | /// 38 | Task RemoveFromRoleAsync(TUser user, string roleName); 39 | 40 | /// 41 | /// Returns the roles for this user 42 | /// 43 | /// 44 | /// 45 | Task> GetRolesAsync(TUser user); 46 | 47 | /// 48 | /// Returns true if a user is in the role 49 | /// 50 | /// 51 | /// 52 | /// 53 | Task IsInRoleAsync(TUser user, string roleName); 54 | } 55 | } -------------------------------------------------------------------------------- /src/Microsoft.AspNet.Identity.Core/IUserSecurityStampStore.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation, Inc. All rights reserved. 2 | // Licensed under the MIT License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using System.Threading.Tasks; 5 | 6 | namespace Microsoft.AspNet.Identity 7 | { 8 | /// 9 | /// Stores a user's security stamp 10 | /// 11 | /// 12 | public interface IUserSecurityStampStore : IUserSecurityStampStore 13 | where TUser : class, IUser 14 | { 15 | } 16 | 17 | /// 18 | /// Stores a user's security stamp 19 | /// 20 | /// 21 | /// 22 | public interface IUserSecurityStampStore : IUserStore where TUser : class, IUser 23 | { 24 | /// 25 | /// Set the security stamp for the user 26 | /// 27 | /// 28 | /// 29 | /// 30 | Task SetSecurityStampAsync(TUser user, string stamp); 31 | 32 | /// 33 | /// Get the user security stamp 34 | /// 35 | /// 36 | /// 37 | Task GetSecurityStampAsync(TUser user); 38 | } 39 | } -------------------------------------------------------------------------------- /src/Microsoft.AspNet.Identity.Core/IUserStore.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation, Inc. All rights reserved. 2 | // Licensed under the MIT License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using System; 5 | using System.Threading.Tasks; 6 | 7 | namespace Microsoft.AspNet.Identity 8 | { 9 | /// 10 | /// Interface that exposes basic user management apis 11 | /// 12 | /// 13 | public interface IUserStore : IUserStore where TUser : class, IUser 14 | { 15 | } 16 | 17 | /// 18 | /// Interface that exposes basic user management apis 19 | /// 20 | /// 21 | /// 22 | public interface IUserStore : IDisposable where TUser : class, IUser 23 | { 24 | /// 25 | /// Insert a new user 26 | /// 27 | /// 28 | /// 29 | Task CreateAsync(TUser user); 30 | 31 | /// 32 | /// Update a user 33 | /// 34 | /// 35 | /// 36 | Task UpdateAsync(TUser user); 37 | 38 | /// 39 | /// Delete a user 40 | /// 41 | /// 42 | /// 43 | Task DeleteAsync(TUser user); 44 | 45 | /// 46 | /// Finds a user 47 | /// 48 | /// 49 | /// 50 | Task FindByIdAsync(TKey userId); 51 | 52 | /// 53 | /// Find a user by name 54 | /// 55 | /// 56 | /// 57 | Task FindByNameAsync(string userName); 58 | } 59 | } -------------------------------------------------------------------------------- /src/Microsoft.AspNet.Identity.Core/IUserTokenProvider.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation, Inc. All rights reserved. 2 | // Licensed under the MIT License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using System; 5 | using System.Threading.Tasks; 6 | 7 | namespace Microsoft.AspNet.Identity 8 | { 9 | /// 10 | /// Interface to generate user tokens 11 | /// 12 | public interface IUserTokenProvider where TUser : class, IUser where TKey : IEquatable 13 | { 14 | /// 15 | /// Generate a token for a user with a specific purpose 16 | /// 17 | /// 18 | /// 19 | /// 20 | /// 21 | Task GenerateAsync(string purpose, UserManager manager, TUser user); 22 | 23 | /// 24 | /// Validate a token for a user with a specific purpose 25 | /// 26 | /// 27 | /// 28 | /// 29 | /// 30 | /// 31 | Task ValidateAsync(string purpose, string token, UserManager manager, TUser user); 32 | 33 | /// 34 | /// Notifies the user that a token has been generated, for example an email or sms could be sent, or 35 | /// this can be a no-op 36 | /// 37 | /// 38 | /// 39 | /// 40 | /// 41 | Task NotifyAsync(string token, UserManager manager, TUser user); 42 | 43 | /// 44 | /// Returns true if provider can be used for this user, i.e. could require a user to have an email 45 | /// 46 | /// 47 | /// 48 | /// 49 | Task IsValidProviderForUserAsync(UserManager manager, TUser user); 50 | } 51 | } -------------------------------------------------------------------------------- /src/Microsoft.AspNet.Identity.Core/IUserTwoFactorStore.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation, Inc. All rights reserved. 2 | // Licensed under the MIT License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using System.Threading.Tasks; 5 | 6 | namespace Microsoft.AspNet.Identity { 7 | /// 8 | /// Stores whether two factor authentication is enabled for a user 9 | /// 10 | /// 11 | /// 12 | public interface IUserTwoFactorStore : IUserStore where TUser : class, IUser { 13 | /// 14 | /// Sets whether two factor authentication is enabled for the user 15 | /// 16 | /// 17 | /// 18 | /// 19 | Task SetTwoFactorEnabledAsync(TUser user, bool enabled); 20 | 21 | /// 22 | /// Returns whether two factor authentication is enabled for the user 23 | /// 24 | /// 25 | /// 26 | Task GetTwoFactorEnabledAsync(TUser user); 27 | } 28 | } -------------------------------------------------------------------------------- /src/Microsoft.AspNet.Identity.Core/IdentityResult.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation, Inc. All rights reserved. 2 | // Licensed under the MIT License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using System.Collections.Generic; 5 | 6 | namespace Microsoft.AspNet.Identity 7 | { 8 | /// 9 | /// Represents the result of an identity operation 10 | /// 11 | public class IdentityResult 12 | { 13 | private static readonly IdentityResult _success = new IdentityResult(true); 14 | 15 | /// 16 | /// Failure constructor that takes error messages 17 | /// 18 | /// 19 | public IdentityResult(params string[] errors) : this((IEnumerable) errors) 20 | { 21 | } 22 | 23 | /// 24 | /// Failure constructor that takes error messages 25 | /// 26 | /// 27 | public IdentityResult(IEnumerable errors) 28 | { 29 | if (errors == null) 30 | { 31 | errors = new[] {Resources.DefaultError}; 32 | } 33 | Succeeded = false; 34 | Errors = errors; 35 | } 36 | 37 | /// 38 | /// Constructor that takes whether the result is successful 39 | /// 40 | /// 41 | protected IdentityResult(bool success) 42 | { 43 | Succeeded = success; 44 | Errors = new string[0]; 45 | } 46 | 47 | /// 48 | /// True if the operation was successful 49 | /// 50 | public bool Succeeded { get; private set; } 51 | 52 | /// 53 | /// List of errors 54 | /// 55 | public IEnumerable Errors { get; private set; } 56 | 57 | /// 58 | /// Static success result 59 | /// 60 | /// 61 | public static IdentityResult Success 62 | { 63 | get { return _success; } 64 | } 65 | 66 | /// 67 | /// Failed helper method 68 | /// 69 | /// 70 | /// 71 | public static IdentityResult Failed(params string[] errors) 72 | { 73 | return new IdentityResult(errors); 74 | } 75 | } 76 | } -------------------------------------------------------------------------------- /src/Microsoft.AspNet.Identity.Core/Microsoft.AspNet.Identity.Core.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | Debug 6 | AnyCPU 7 | {D2F24972-0F56-4C18-BD65-C26A320A0C68} 8 | Library 9 | Properties 10 | Microsoft.AspNet.Identity 11 | Microsoft.AspNet.Identity.Core 12 | v4.5 13 | 512 14 | SAK 15 | SAK 16 | SAK 17 | SAK 18 | 19 | bin\$(Configuration) 20 | 21 | 22 | true 23 | full 24 | false 25 | DEBUG;TRACE 26 | prompt 27 | 4 28 | false 29 | bin\Debug\Microsoft.AspNet.Identity.Core.XML 30 | true 31 | Sdl6.1.ruleset 32 | 33 | 34 | pdbonly 35 | true 36 | TRACE 37 | prompt 38 | 4 39 | false 40 | bin\Release\Microsoft.AspNet.Identity.Core.XML 41 | 42 | 43 | true 44 | 45 | 46 | true 47 | 48 | 49 | 35MSSharedLib1024.snk 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | True 97 | True 98 | Resources.resx 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | ResXFileCodeGenerator 115 | Resources.Designer.cs 116 | 117 | 118 | 119 | 126 | -------------------------------------------------------------------------------- /src/Microsoft.AspNet.Identity.Core/MinimumLengthValidator.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation, Inc. All rights reserved. 2 | // Licensed under the MIT License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using System; 5 | using System.Globalization; 6 | using System.Threading.Tasks; 7 | 8 | namespace Microsoft.AspNet.Identity 9 | { 10 | /// 11 | /// Used to validate that passwords are a minimum length 12 | /// 13 | public class MinimumLengthValidator : IIdentityValidator 14 | { 15 | /// 16 | /// Constructor 17 | /// 18 | /// 19 | public MinimumLengthValidator(int requiredLength) 20 | { 21 | RequiredLength = requiredLength; 22 | } 23 | 24 | /// 25 | /// Minimum required length for the password 26 | /// 27 | public int RequiredLength { get; set; } 28 | 29 | /// 30 | /// Ensures that the password is of the required length 31 | /// 32 | /// 33 | /// 34 | public virtual Task ValidateAsync(string item) 35 | { 36 | if (string.IsNullOrWhiteSpace(item) || item.Length < RequiredLength) 37 | { 38 | return 39 | Task.FromResult( 40 | IdentityResult.Failed(String.Format(CultureInfo.CurrentCulture, Resources.PasswordTooShort, 41 | RequiredLength))); 42 | } 43 | return Task.FromResult(IdentityResult.Success); 44 | } 45 | } 46 | } -------------------------------------------------------------------------------- /src/Microsoft.AspNet.Identity.Core/PasswordHasher.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation, Inc. All rights reserved. 2 | // Licensed under the MIT License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | namespace Microsoft.AspNet.Identity 5 | { 6 | /// 7 | /// Implements password hashing methods 8 | /// 9 | public class PasswordHasher : IPasswordHasher 10 | { 11 | /// 12 | /// Hash a password 13 | /// 14 | /// 15 | /// 16 | public virtual string HashPassword(string password) 17 | { 18 | return Crypto.HashPassword(password); 19 | } 20 | 21 | /// 22 | /// Verify that a password matches the hashedPassword 23 | /// 24 | /// 25 | /// 26 | /// 27 | public virtual PasswordVerificationResult VerifyHashedPassword(string hashedPassword, string providedPassword) 28 | { 29 | if (Crypto.VerifyHashedPassword(hashedPassword, providedPassword)) 30 | { 31 | return PasswordVerificationResult.Success; 32 | } 33 | return PasswordVerificationResult.Failed; 34 | } 35 | } 36 | } -------------------------------------------------------------------------------- /src/Microsoft.AspNet.Identity.Core/PasswordValidator.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation, Inc. All rights reserved. 2 | // Licensed under the MIT License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using System; 5 | using System.Collections.Generic; 6 | using System.Globalization; 7 | using System.Linq; 8 | using System.Threading.Tasks; 9 | 10 | namespace Microsoft.AspNet.Identity 11 | { 12 | /// 13 | /// Used to validate some basic password policy like length and number of non alphanumerics 14 | /// 15 | public class PasswordValidator : IIdentityValidator 16 | { 17 | /// 18 | /// Minimum required length 19 | /// 20 | public int RequiredLength { get; set; } 21 | 22 | /// 23 | /// Require a non letter or digit character 24 | /// 25 | public bool RequireNonLetterOrDigit { get; set; } 26 | 27 | /// 28 | /// Require a lower case letter ('a' - 'z') 29 | /// 30 | public bool RequireLowercase { get; set; } 31 | 32 | /// 33 | /// Require an upper case letter ('A' - 'Z') 34 | /// 35 | public bool RequireUppercase { get; set; } 36 | 37 | /// 38 | /// Require a digit ('0' - '9') 39 | /// 40 | public bool RequireDigit { get; set; } 41 | 42 | /// 43 | /// Ensures that the string is of the required length and meets the configured requirements 44 | /// 45 | /// 46 | /// 47 | public virtual Task ValidateAsync(string item) 48 | { 49 | if (item == null) 50 | { 51 | throw new ArgumentNullException("item"); 52 | } 53 | var errors = new List(); 54 | if (string.IsNullOrWhiteSpace(item) || item.Length < RequiredLength) 55 | { 56 | errors.Add(String.Format(CultureInfo.CurrentCulture, Resources.PasswordTooShort, RequiredLength)); 57 | } 58 | if (RequireNonLetterOrDigit && item.All(IsLetterOrDigit)) 59 | { 60 | errors.Add(Resources.PasswordRequireNonLetterOrDigit); 61 | } 62 | if (RequireDigit && item.All(c => !IsDigit(c))) 63 | { 64 | errors.Add(Resources.PasswordRequireDigit); 65 | } 66 | if (RequireLowercase && item.All(c => !IsLower(c))) 67 | { 68 | errors.Add(Resources.PasswordRequireLower); 69 | } 70 | if (RequireUppercase && item.All(c => !IsUpper(c))) 71 | { 72 | errors.Add(Resources.PasswordRequireUpper); 73 | } 74 | if (errors.Count == 0) 75 | { 76 | return Task.FromResult(IdentityResult.Success); 77 | } 78 | return Task.FromResult(IdentityResult.Failed(String.Join(" ", errors))); 79 | } 80 | 81 | /// 82 | /// Returns true if the character is a digit between '0' and '9' 83 | /// 84 | /// 85 | /// 86 | public virtual bool IsDigit(char c) 87 | { 88 | return c >= '0' && c <= '9'; 89 | } 90 | 91 | /// 92 | /// Returns true if the character is between 'a' and 'z' 93 | /// 94 | /// 95 | /// 96 | public virtual bool IsLower(char c) 97 | { 98 | return c >= 'a' && c <= 'z'; 99 | } 100 | 101 | /// 102 | /// Returns true if the character is between 'A' and 'Z' 103 | /// 104 | /// 105 | /// 106 | public virtual bool IsUpper(char c) 107 | { 108 | return c >= 'A' && c <= 'Z'; 109 | } 110 | 111 | /// 112 | /// Returns true if the character is upper, lower, or a digit 113 | /// 114 | /// 115 | /// 116 | public virtual bool IsLetterOrDigit(char c) 117 | { 118 | return IsUpper(c) || IsLower(c) || IsDigit(c); 119 | } 120 | } 121 | } -------------------------------------------------------------------------------- /src/Microsoft.AspNet.Identity.Core/PasswordVerificationResult.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation, Inc. All rights reserved. 2 | // Licensed under the MIT License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | namespace Microsoft.AspNet.Identity 5 | { 6 | /// 7 | /// Return result for IPasswordHasher 8 | /// 9 | public enum PasswordVerificationResult 10 | { 11 | /// 12 | /// Password verification failed 13 | /// 14 | Failed = 0, 15 | 16 | /// 17 | /// Success 18 | /// 19 | Success = 1, 20 | 21 | /// 22 | /// Success but should update and rehash the password 23 | /// 24 | SuccessRehashNeeded = 2 25 | } 26 | } -------------------------------------------------------------------------------- /src/Microsoft.AspNet.Identity.Core/PhoneNumberTokenProvider.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation, Inc. All rights reserved. 2 | // Licensed under the MIT License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using System; 5 | using System.Globalization; 6 | using System.Threading.Tasks; 7 | 8 | namespace Microsoft.AspNet.Identity 9 | { 10 | /// 11 | /// TokenProvider that generates tokens from the user's security stamp and notifies a user via their phone number 12 | /// 13 | /// 14 | public class PhoneNumberTokenProvider : PhoneNumberTokenProvider 15 | where TUser : class, IUser 16 | { 17 | } 18 | 19 | /// 20 | /// TokenProvider that generates tokens from the user's security stamp and notifies a user via their phone number 21 | /// 22 | /// 23 | /// 24 | public class PhoneNumberTokenProvider : TotpSecurityStampBasedTokenProvider 25 | where TUser : class, IUser 26 | where TKey : IEquatable 27 | { 28 | private string _body; 29 | 30 | /// 31 | /// Message contents which should contain a format string which the token will be the only argument 32 | /// 33 | public string MessageFormat 34 | { 35 | get { return _body ?? "{0}"; } 36 | set { _body = value; } 37 | } 38 | 39 | /// 40 | /// Returns true if the user has a phone number set 41 | /// 42 | /// 43 | /// 44 | /// 45 | public override async Task IsValidProviderForUserAsync(UserManager manager, TUser user) 46 | { 47 | if (manager == null) 48 | { 49 | throw new ArgumentNullException("manager"); 50 | } 51 | var phoneNumber = await manager.GetPhoneNumberAsync(user.Id).WithCurrentCulture(); 52 | return !String.IsNullOrWhiteSpace(phoneNumber) && await manager.IsPhoneNumberConfirmedAsync(user.Id).WithCurrentCulture(); 53 | } 54 | 55 | /// 56 | /// Returns the phone number of the user for entropy in the token 57 | /// 58 | /// 59 | /// 60 | /// 61 | /// 62 | public override async Task GetUserModifierAsync(string purpose, UserManager manager, 63 | TUser user) 64 | { 65 | if (manager == null) 66 | { 67 | throw new ArgumentNullException("manager"); 68 | } 69 | var phoneNumber = await manager.GetPhoneNumberAsync(user.Id).WithCurrentCulture(); 70 | return "PhoneNumber:" + purpose + ":" + phoneNumber; 71 | } 72 | 73 | /// 74 | /// Notifies the user with a token via sms using the MessageFormat 75 | /// 76 | /// 77 | /// 78 | /// 79 | /// 80 | public override Task NotifyAsync(string token, UserManager manager, TUser user) 81 | { 82 | if (manager == null) 83 | { 84 | throw new ArgumentNullException("manager"); 85 | } 86 | return manager.SendSmsAsync(user.Id, String.Format(CultureInfo.CurrentCulture, MessageFormat, token)); 87 | } 88 | } 89 | } -------------------------------------------------------------------------------- /src/Microsoft.AspNet.Identity.Core/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation, Inc. All rights reserved. 2 | // Licensed under the MIT License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using System; 5 | using System.Reflection; 6 | using System.Runtime.CompilerServices; 7 | using System.Runtime.InteropServices; 8 | 9 | // General Information about an assembly is controlled through the following 10 | // set of attributes. Change these attribute values to modify the information 11 | // associated with an assembly. 12 | 13 | [assembly: AssemblyTitle("Microsoft.AspNet.Identity.Core")] 14 | [assembly: AssemblyDescription("")] 15 | [assembly: AssemblyConfiguration("")] 16 | [assembly: AssemblyCompany("Microsoft")] 17 | [assembly: AssemblyProduct("Microsoft.AspNet.Identity.Core")] 18 | [assembly: AssemblyCopyright("Copyright © Microsoft 2012")] 19 | [assembly: AssemblyTrademark("")] 20 | [assembly: AssemblyCulture("")] 21 | [assembly: CLSCompliant(true)] 22 | 23 | // Setting ComVisible to false makes the types in this assembly not visible 24 | // to COM components. If you need to access a type in this assembly from 25 | // COM, set the ComVisible attribute to true on that type. 26 | 27 | [assembly: ComVisible(false)] 28 | 29 | // The following GUID is for the ID of the typelib if this project is exposed to COM 30 | 31 | [assembly: Guid("e318dfc7-3a02-42a5-bb45-16c143f61c30")] 32 | 33 | // Version information for an assembly consists of the following four values: 34 | // 35 | // Major Version 36 | // Minor Version 37 | // Build Number 38 | // Revision 39 | // 40 | // You can specify all the values or you can default the Build and Revision Numbers 41 | // by using the '*' as shown below: 42 | // [assembly: AssemblyVersion("1.0.*")] 43 | 44 | [assembly: AssemblyVersion("2.0.0.0")] 45 | [assembly: AssemblyFileVersion("2.1.0.0")] 46 | [assembly: AssemblyMetadata("Serviceable", "True")] 47 | [assembly: 48 | InternalsVisibleTo( 49 | "Microsoft.AspNet.Identity.Owin, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9" 50 | )] 51 | [assembly: 52 | InternalsVisibleTo( 53 | "Microsoft.AspNet.Identity.EntityFramework, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9" 54 | )] 55 | [assembly: 56 | InternalsVisibleTo( 57 | "Identity.Test, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9" 58 | )] -------------------------------------------------------------------------------- /src/Microsoft.AspNet.Identity.Core/Rfc6238AuthenticationService.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation, Inc. All rights reserved. 2 | // Licensed under the MIT License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using System; 5 | using System.Diagnostics; 6 | using System.Net; 7 | using System.Security.Cryptography; 8 | using System.Text; 9 | 10 | namespace Microsoft.AspNet.Identity 11 | { 12 | internal sealed class SecurityToken 13 | { 14 | private readonly byte[] _data; 15 | 16 | public SecurityToken(byte[] data) 17 | { 18 | _data = (byte[]) data.Clone(); 19 | } 20 | 21 | internal byte[] GetDataNoClone() 22 | { 23 | return _data; 24 | } 25 | } 26 | 27 | internal static class Rfc6238AuthenticationService 28 | { 29 | private static readonly DateTime _unixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); 30 | private static readonly TimeSpan _timestep = TimeSpan.FromMinutes(3); 31 | private static readonly Encoding _encoding = new UTF8Encoding(false, true); 32 | 33 | private static int ComputeTotp(HashAlgorithm hashAlgorithm, ulong timestepNumber, string modifier) 34 | { 35 | // # of 0's = length of pin 36 | const int mod = 1000000; 37 | 38 | // See https://tools.ietf.org/html/rfc4226 39 | // We can add an optional modifier 40 | var timestepAsBytes = BitConverter.GetBytes(IPAddress.HostToNetworkOrder((long) timestepNumber)); 41 | var hash = hashAlgorithm.ComputeHash(ApplyModifier(timestepAsBytes, modifier)); 42 | 43 | // Generate DT string 44 | var offset = hash[hash.Length - 1] & 0xf; 45 | Debug.Assert(offset + 4 < hash.Length); 46 | var binaryCode = (hash[offset] & 0x7f) << 24 47 | | (hash[offset + 1] & 0xff) << 16 48 | | (hash[offset + 2] & 0xff) << 8 49 | | (hash[offset + 3] & 0xff); 50 | 51 | return binaryCode%mod; 52 | } 53 | 54 | private static byte[] ApplyModifier(byte[] input, string modifier) 55 | { 56 | if (String.IsNullOrEmpty(modifier)) 57 | { 58 | return input; 59 | } 60 | 61 | var modifierBytes = _encoding.GetBytes(modifier); 62 | var combined = new byte[checked(input.Length + modifierBytes.Length)]; 63 | Buffer.BlockCopy(input, 0, combined, 0, input.Length); 64 | Buffer.BlockCopy(modifierBytes, 0, combined, input.Length, modifierBytes.Length); 65 | return combined; 66 | } 67 | 68 | // More info: https://tools.ietf.org/html/rfc6238#section-4 69 | private static ulong GetCurrentTimeStepNumber() 70 | { 71 | var delta = DateTime.UtcNow - _unixEpoch; 72 | return (ulong) (delta.Ticks/_timestep.Ticks); 73 | } 74 | 75 | public static int GenerateCode(SecurityToken securityToken, string modifier = null) 76 | { 77 | if (securityToken == null) 78 | { 79 | throw new ArgumentNullException("securityToken"); 80 | } 81 | 82 | // Allow a variance of no greater than 9 minutes in either direction 83 | var currentTimeStep = GetCurrentTimeStepNumber(); 84 | using (var hashAlgorithm = new HMACSHA1(securityToken.GetDataNoClone())) 85 | { 86 | return ComputeTotp(hashAlgorithm, currentTimeStep, modifier); 87 | } 88 | } 89 | 90 | public static bool ValidateCode(SecurityToken securityToken, int code, string modifier = null) 91 | { 92 | if (securityToken == null) 93 | { 94 | throw new ArgumentNullException("securityToken"); 95 | } 96 | 97 | // Allow a variance of no greater than 9 minutes in either direction 98 | var currentTimeStep = GetCurrentTimeStepNumber(); 99 | using (var hashAlgorithm = new HMACSHA1(securityToken.GetDataNoClone())) 100 | { 101 | for (var i = -2; i <= 2; i++) 102 | { 103 | var computedTotp = ComputeTotp(hashAlgorithm, (ulong) ((long) currentTimeStep + i), modifier); 104 | if (computedTotp == code) 105 | { 106 | return true; 107 | } 108 | } 109 | } 110 | 111 | // No match 112 | return false; 113 | } 114 | } 115 | } -------------------------------------------------------------------------------- /src/Microsoft.AspNet.Identity.Core/RoleValidator.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation, Inc. All rights reserved. 2 | // Licensed under the MIT License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using System; 5 | using System.Collections.Generic; 6 | using System.Globalization; 7 | using System.Threading.Tasks; 8 | 9 | namespace Microsoft.AspNet.Identity 10 | { 11 | /// 12 | /// Validates roles before they are saved 13 | /// 14 | /// 15 | public class RoleValidator : RoleValidator where TRole : class, IRole 16 | { 17 | /// 18 | /// Constructor 19 | /// 20 | /// 21 | public RoleValidator(RoleManager manager) 22 | : base(manager) 23 | { 24 | } 25 | } 26 | 27 | /// 28 | /// Validates roles before they are saved 29 | /// 30 | /// 31 | /// 32 | public class RoleValidator : IIdentityValidator 33 | where TRole : class, IRole 34 | where TKey : IEquatable 35 | { 36 | /// 37 | /// Constructor 38 | /// 39 | /// 40 | public RoleValidator(RoleManager manager) 41 | { 42 | if (manager == null) 43 | { 44 | throw new ArgumentNullException("manager"); 45 | } 46 | Manager = manager; 47 | } 48 | 49 | private RoleManager Manager { get; set; } 50 | 51 | /// 52 | /// Validates a role before saving 53 | /// 54 | /// 55 | /// 56 | public virtual async Task ValidateAsync(TRole item) 57 | { 58 | if (item == null) 59 | { 60 | throw new ArgumentNullException("item"); 61 | } 62 | var errors = new List(); 63 | await ValidateRoleName(item, errors).WithCurrentCulture(); 64 | if (errors.Count > 0) 65 | { 66 | return IdentityResult.Failed(errors.ToArray()); 67 | } 68 | return IdentityResult.Success; 69 | } 70 | 71 | private async Task ValidateRoleName(TRole role, List errors) 72 | { 73 | if (string.IsNullOrWhiteSpace(role.Name)) 74 | { 75 | errors.Add(String.Format(CultureInfo.CurrentCulture, Resources.PropertyTooShort, "Name")); 76 | } 77 | else 78 | { 79 | var owner = await Manager.FindByNameAsync(role.Name).WithCurrentCulture(); 80 | if (owner != null && !EqualityComparer.Default.Equals(owner.Id, role.Id)) 81 | { 82 | errors.Add(String.Format(CultureInfo.CurrentCulture, Resources.DuplicateName, role.Name)); 83 | } 84 | } 85 | } 86 | } 87 | } -------------------------------------------------------------------------------- /src/Microsoft.AspNet.Identity.Core/TaskExtensions.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation, Inc. All rights reserved. 2 | // Licensed under the MIT License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | namespace Microsoft.AspNet.Identity 5 | { 6 | using System; 7 | using System.Runtime.CompilerServices; 8 | using System.Threading; 9 | using System.Threading.Tasks; 10 | 11 | internal static class TaskExtensions 12 | { 13 | public static CultureAwaiter WithCurrentCulture(this Task task) 14 | { 15 | return new CultureAwaiter(task); 16 | } 17 | 18 | public static CultureAwaiter WithCurrentCulture(this Task task) 19 | { 20 | return new CultureAwaiter(task); 21 | } 22 | 23 | public struct CultureAwaiter : ICriticalNotifyCompletion 24 | { 25 | private readonly Task _task; 26 | 27 | public CultureAwaiter(Task task) 28 | { 29 | _task = task; 30 | } 31 | 32 | public CultureAwaiter GetAwaiter() 33 | { 34 | return this; 35 | } 36 | 37 | public bool IsCompleted 38 | { 39 | get { return _task.IsCompleted; } 40 | } 41 | 42 | public T GetResult() 43 | { 44 | return _task.GetAwaiter().GetResult(); 45 | } 46 | 47 | public void OnCompleted(Action continuation) 48 | { 49 | // The compiler will never call this method 50 | throw new NotImplementedException(); 51 | } 52 | 53 | public void UnsafeOnCompleted(Action continuation) 54 | { 55 | var currentCulture = Thread.CurrentThread.CurrentCulture; 56 | var currentUiCulture = Thread.CurrentThread.CurrentUICulture; 57 | _task.ConfigureAwait(false).GetAwaiter().UnsafeOnCompleted(() => 58 | { 59 | var originalCulture = Thread.CurrentThread.CurrentCulture; 60 | var originalUiCulture = Thread.CurrentThread.CurrentUICulture; 61 | Thread.CurrentThread.CurrentCulture = currentCulture; 62 | Thread.CurrentThread.CurrentUICulture = currentUiCulture; 63 | try 64 | { 65 | continuation(); 66 | } 67 | finally 68 | { 69 | Thread.CurrentThread.CurrentCulture = originalCulture; 70 | Thread.CurrentThread.CurrentUICulture = originalUiCulture; 71 | } 72 | }); 73 | } 74 | } 75 | 76 | public struct CultureAwaiter : ICriticalNotifyCompletion 77 | { 78 | private readonly Task _task; 79 | 80 | public CultureAwaiter(Task task) 81 | { 82 | _task = task; 83 | } 84 | 85 | public CultureAwaiter GetAwaiter() 86 | { 87 | return this; 88 | } 89 | 90 | public bool IsCompleted 91 | { 92 | get { return _task.IsCompleted; } 93 | } 94 | 95 | public void GetResult() 96 | { 97 | _task.GetAwaiter().GetResult(); 98 | } 99 | 100 | public void OnCompleted(Action continuation) 101 | { 102 | // The compiler will never call this method 103 | throw new NotImplementedException(); 104 | } 105 | 106 | public void UnsafeOnCompleted(Action continuation) 107 | { 108 | var currentCulture = Thread.CurrentThread.CurrentCulture; 109 | var currentUiCulture = Thread.CurrentThread.CurrentUICulture; 110 | _task.ConfigureAwait(false).GetAwaiter().UnsafeOnCompleted(() => 111 | { 112 | var originalCulture = Thread.CurrentThread.CurrentCulture; 113 | var originalUiCulture = Thread.CurrentThread.CurrentUICulture; 114 | Thread.CurrentThread.CurrentCulture = currentCulture; 115 | Thread.CurrentThread.CurrentUICulture = currentUiCulture; 116 | try 117 | { 118 | continuation(); 119 | } 120 | finally 121 | { 122 | Thread.CurrentThread.CurrentCulture = originalCulture; 123 | Thread.CurrentThread.CurrentUICulture = originalUiCulture; 124 | } 125 | }); 126 | } 127 | } 128 | } 129 | } -------------------------------------------------------------------------------- /src/Microsoft.AspNet.Identity.Core/TotpSecurityStampBasedTokenProvider.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation, Inc. All rights reserved. 2 | // Licensed under the MIT License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using System; 5 | using System.Globalization; 6 | using System.Threading.Tasks; 7 | 8 | namespace Microsoft.AspNet.Identity 9 | { 10 | /// 11 | /// TokenProvider that generates time based codes using the user's security stamp 12 | /// 13 | /// 14 | /// 15 | public class TotpSecurityStampBasedTokenProvider : IUserTokenProvider 16 | where TUser : class, IUser 17 | where TKey : IEquatable 18 | { 19 | /// 20 | /// This token provider does not notify the user by default 21 | /// 22 | /// 23 | /// 24 | /// 25 | /// 26 | public virtual Task NotifyAsync(string token, UserManager manager, TUser user) 27 | { 28 | return Task.FromResult(0); 29 | } 30 | 31 | /// 32 | /// Returns true if the provider can generate tokens for the user, by default this is equal to 33 | /// manager.SupportsUserSecurityStamp 34 | /// 35 | /// 36 | /// 37 | /// 38 | public virtual Task IsValidProviderForUserAsync(UserManager manager, TUser user) 39 | { 40 | if (manager == null) 41 | { 42 | throw new ArgumentNullException("manager"); 43 | } 44 | return Task.FromResult(manager.SupportsUserSecurityStamp); 45 | } 46 | 47 | /// 48 | /// Generate a token for the user using their security stamp 49 | /// 50 | /// 51 | /// 52 | /// 53 | /// 54 | public virtual async Task GenerateAsync(string purpose, UserManager manager, TUser user) 55 | { 56 | var token = await manager.CreateSecurityTokenAsync(user.Id).WithCurrentCulture(); 57 | var modifier = await GetUserModifierAsync(purpose, manager, user).WithCurrentCulture(); 58 | return Rfc6238AuthenticationService.GenerateCode(token, modifier).ToString("D6", CultureInfo.InvariantCulture); 59 | } 60 | 61 | /// 62 | /// Validate the token for the user 63 | /// 64 | /// 65 | /// 66 | /// 67 | /// 68 | /// 69 | public virtual async Task ValidateAsync(string purpose, string token, UserManager manager, 70 | TUser user) 71 | { 72 | int code; 73 | if (!Int32.TryParse(token, out code)) 74 | { 75 | return false; 76 | } 77 | var securityToken = await manager.CreateSecurityTokenAsync(user.Id).WithCurrentCulture(); 78 | var modifier = await GetUserModifierAsync(purpose, manager, user).WithCurrentCulture(); 79 | return securityToken != null && Rfc6238AuthenticationService.ValidateCode(securityToken, code, modifier); 80 | } 81 | 82 | /// 83 | /// Used for entropy in the token, uses the user.Id by default 84 | /// 85 | /// 86 | /// 87 | /// 88 | /// 89 | public virtual Task GetUserModifierAsync(string purpose, UserManager manager, TUser user) 90 | { 91 | return Task.FromResult("Totp:" + purpose + ":" + user.Id); 92 | } 93 | } 94 | } -------------------------------------------------------------------------------- /src/Microsoft.AspNet.Identity.Core/UserLoginInfo.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation, Inc. All rights reserved. 2 | // Licensed under the MIT License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | namespace Microsoft.AspNet.Identity 5 | { 6 | /// 7 | /// Represents a linked login for a user (i.e. a facebook/google account) 8 | /// 9 | public sealed class UserLoginInfo 10 | { 11 | /// 12 | /// Constructor 13 | /// 14 | /// 15 | /// 16 | public UserLoginInfo(string loginProvider, string providerKey) 17 | { 18 | LoginProvider = loginProvider; 19 | ProviderKey = providerKey; 20 | } 21 | 22 | /// 23 | /// Provider for the linked login, i.e. Facebook, Google, etc. 24 | /// 25 | public string LoginProvider { get; set; } 26 | 27 | /// 28 | /// User specific key for the login provider 29 | /// 30 | public string ProviderKey { get; set; } 31 | } 32 | } -------------------------------------------------------------------------------- /src/Microsoft.AspNet.Identity.Core/UserValidator.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation, Inc. All rights reserved. 2 | // Licensed under the MIT License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using System; 5 | using System.Collections.Generic; 6 | using System.Globalization; 7 | using System.Net.Mail; 8 | using System.Text.RegularExpressions; 9 | using System.Threading.Tasks; 10 | 11 | namespace Microsoft.AspNet.Identity 12 | { 13 | /// 14 | /// Validates users before they are saved 15 | /// 16 | /// 17 | public class UserValidator : UserValidator where TUser : class, IUser 18 | { 19 | /// 20 | /// Constructor 21 | /// 22 | /// 23 | public UserValidator(UserManager manager) 24 | : base(manager) 25 | { 26 | } 27 | } 28 | 29 | /// 30 | /// Validates users before they are saved 31 | /// 32 | /// 33 | /// 34 | public class UserValidator : IIdentityValidator 35 | where TUser : class, IUser 36 | where TKey : IEquatable 37 | { 38 | /// 39 | /// Constructor 40 | /// 41 | /// 42 | public UserValidator(UserManager manager) 43 | { 44 | if (manager == null) 45 | { 46 | throw new ArgumentNullException("manager"); 47 | } 48 | AllowOnlyAlphanumericUserNames = true; 49 | Manager = manager; 50 | } 51 | 52 | /// 53 | /// Only allow [A-Za-z0-9@_] in UserNames 54 | /// 55 | public bool AllowOnlyAlphanumericUserNames { get; set; } 56 | 57 | /// 58 | /// If set, enforces that emails are non empty, valid, and unique 59 | /// 60 | public bool RequireUniqueEmail { get; set; } 61 | 62 | private UserManager Manager { get; set; } 63 | 64 | /// 65 | /// Validates a user before saving 66 | /// 67 | /// 68 | /// 69 | public virtual async Task ValidateAsync(TUser item) 70 | { 71 | if (item == null) 72 | { 73 | throw new ArgumentNullException("item"); 74 | } 75 | var errors = new List(); 76 | await ValidateUserName(item, errors).WithCurrentCulture(); 77 | if (RequireUniqueEmail) 78 | { 79 | await ValidateEmailAsync(item, errors).WithCurrentCulture(); 80 | } 81 | if (errors.Count > 0) 82 | { 83 | return IdentityResult.Failed(errors.ToArray()); 84 | } 85 | return IdentityResult.Success; 86 | } 87 | 88 | private async Task ValidateUserName(TUser user, List errors) 89 | { 90 | if (string.IsNullOrWhiteSpace(user.UserName)) 91 | { 92 | errors.Add(String.Format(CultureInfo.CurrentCulture, Resources.PropertyTooShort, "Name")); 93 | } 94 | else if (AllowOnlyAlphanumericUserNames && !Regex.IsMatch(user.UserName, @"^[A-Za-z0-9@_\.]+$")) 95 | { 96 | // If any characters are not letters or digits, its an illegal user name 97 | errors.Add(String.Format(CultureInfo.CurrentCulture, Resources.InvalidUserName, user.UserName)); 98 | } 99 | else 100 | { 101 | var owner = await Manager.FindByNameAsync(user.UserName).WithCurrentCulture(); 102 | if (owner != null && !EqualityComparer.Default.Equals(owner.Id, user.Id)) 103 | { 104 | errors.Add(String.Format(CultureInfo.CurrentCulture, Resources.DuplicateName, user.UserName)); 105 | } 106 | } 107 | } 108 | 109 | // make sure email is not empty, valid, and unique 110 | private async Task ValidateEmailAsync(TUser user, List errors) 111 | { 112 | var email = await Manager.GetEmailStore().GetEmailAsync(user).WithCurrentCulture(); 113 | if (string.IsNullOrWhiteSpace(email)) 114 | { 115 | errors.Add(String.Format(CultureInfo.CurrentCulture, Resources.PropertyTooShort, "Email")); 116 | return; 117 | } 118 | try 119 | { 120 | var m = new MailAddress(email); 121 | } 122 | catch (FormatException) 123 | { 124 | errors.Add(String.Format(CultureInfo.CurrentCulture, Resources.InvalidEmail, email)); 125 | return; 126 | } 127 | var owner = await Manager.FindByEmailAsync(email).WithCurrentCulture(); 128 | if (owner != null && !EqualityComparer.Default.Equals(owner.Id, user.Id)) 129 | { 130 | errors.Add(String.Format(CultureInfo.CurrentCulture, Resources.DuplicateEmail, email)); 131 | } 132 | } 133 | } 134 | } -------------------------------------------------------------------------------- /src/Microsoft.AspNet.Identity.EntityFramework/35MSSharedLib1024.snk: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aspnet/AspNetIdentity/a9b3a489e0942f09a2ab473039a9183ba095188d/src/Microsoft.AspNet.Identity.EntityFramework/35MSSharedLib1024.snk -------------------------------------------------------------------------------- /src/Microsoft.AspNet.Identity.EntityFramework/App.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 |
6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | -------------------------------------------------------------------------------- /src/Microsoft.AspNet.Identity.EntityFramework/EntityStore.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation, Inc. All rights reserved. 2 | // Licensed under the MIT License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using System.Data.Entity; 5 | using System.Linq; 6 | using System.Threading.Tasks; 7 | 8 | namespace Microsoft.AspNet.Identity.EntityFramework 9 | { 10 | /// 11 | /// EntityFramework based IIdentityEntityStore that allows query/manipulation of a TEntity set 12 | /// 13 | /// Concrete entity type, i.e .User 14 | internal class EntityStore where TEntity : class 15 | { 16 | /// 17 | /// Constructor that takes a Context 18 | /// 19 | /// 20 | public EntityStore(DbContext context) 21 | { 22 | Context = context; 23 | DbEntitySet = context.Set(); 24 | } 25 | 26 | /// 27 | /// Context for the store 28 | /// 29 | public DbContext Context { get; private set; } 30 | 31 | /// 32 | /// Used to query the entities 33 | /// 34 | public IQueryable EntitySet 35 | { 36 | get { return DbEntitySet; } 37 | } 38 | 39 | /// 40 | /// EntitySet for this store 41 | /// 42 | public DbSet DbEntitySet { get; private set; } 43 | 44 | /// 45 | /// FindAsync an entity by ID 46 | /// 47 | /// 48 | /// 49 | public virtual Task GetByIdAsync(object id) 50 | { 51 | return DbEntitySet.FindAsync(id); 52 | } 53 | 54 | /// 55 | /// Insert an entity 56 | /// 57 | /// 58 | public void Create(TEntity entity) 59 | { 60 | DbEntitySet.Add(entity); 61 | } 62 | 63 | /// 64 | /// Mark an entity for deletion 65 | /// 66 | /// 67 | public void Delete(TEntity entity) 68 | { 69 | DbEntitySet.Remove(entity); 70 | } 71 | 72 | /// 73 | /// Update an entity 74 | /// 75 | /// 76 | public virtual void Update(TEntity entity) 77 | { 78 | if (entity != null) 79 | { 80 | Context.Entry(entity).State = EntityState.Modified; 81 | } 82 | } 83 | } 84 | } -------------------------------------------------------------------------------- /src/Microsoft.AspNet.Identity.EntityFramework/GlobalSuppressions.cs: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aspnet/AspNetIdentity/a9b3a489e0942f09a2ab473039a9183ba095188d/src/Microsoft.AspNet.Identity.EntityFramework/GlobalSuppressions.cs -------------------------------------------------------------------------------- /src/Microsoft.AspNet.Identity.EntityFramework/IdentityRole.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation, Inc. All rights reserved. 2 | // Licensed under the MIT License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using System; 5 | using System.Collections.Generic; 6 | 7 | namespace Microsoft.AspNet.Identity.EntityFramework 8 | { 9 | /// 10 | /// Represents a Role entity 11 | /// 12 | public class IdentityRole : IdentityRole 13 | { 14 | /// 15 | /// Constructor 16 | /// 17 | public IdentityRole() 18 | { 19 | Id = Guid.NewGuid().ToString(); 20 | } 21 | 22 | /// 23 | /// Constructor 24 | /// 25 | /// 26 | public IdentityRole(string roleName) 27 | : this() 28 | { 29 | Name = roleName; 30 | } 31 | } 32 | 33 | /// 34 | /// Represents a Role entity 35 | /// 36 | /// 37 | /// 38 | public class IdentityRole : IRole where TUserRole : IdentityUserRole 39 | { 40 | /// 41 | /// Constructor 42 | /// 43 | public IdentityRole() 44 | { 45 | Users = new List(); 46 | } 47 | 48 | /// 49 | /// Navigation property for users in the role 50 | /// 51 | public virtual ICollection Users { get; private set; } 52 | 53 | /// 54 | /// Role id 55 | /// 56 | public TKey Id { get; set; } 57 | 58 | /// 59 | /// Role name 60 | /// 61 | public string Name { get; set; } 62 | } 63 | } -------------------------------------------------------------------------------- /src/Microsoft.AspNet.Identity.EntityFramework/IdentityUser.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation, Inc. All rights reserved. 2 | // Licensed under the MIT License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using System; 5 | using System.Collections.Generic; 6 | 7 | namespace Microsoft.AspNet.Identity.EntityFramework 8 | { 9 | /// 10 | /// Default EntityFramework IUser implementation 11 | /// 12 | public class IdentityUser : IdentityUser, IUser 13 | { 14 | /// 15 | /// Constructor which creates a new Guid for the Id 16 | /// 17 | public IdentityUser() 18 | { 19 | Id = Guid.NewGuid().ToString(); 20 | } 21 | 22 | /// 23 | /// Constructor that takes a userName 24 | /// 25 | /// 26 | public IdentityUser(string userName) 27 | : this() 28 | { 29 | UserName = userName; 30 | } 31 | } 32 | 33 | /// 34 | /// Default EntityFramework IUser implementation 35 | /// 36 | /// 37 | /// 38 | /// 39 | /// 40 | public class IdentityUser : IUser 41 | where TLogin : IdentityUserLogin 42 | where TRole : IdentityUserRole 43 | where TClaim : IdentityUserClaim 44 | { 45 | /// 46 | /// Constructor 47 | /// 48 | public IdentityUser() 49 | { 50 | Claims = new List(); 51 | Roles = new List(); 52 | Logins = new List(); 53 | } 54 | 55 | /// 56 | /// Email 57 | /// 58 | public virtual string Email { get; set; } 59 | 60 | /// 61 | /// True if the email is confirmed, default is false 62 | /// 63 | public virtual bool EmailConfirmed { get; set; } 64 | 65 | /// 66 | /// The salted/hashed form of the user password 67 | /// 68 | public virtual string PasswordHash { get; set; } 69 | 70 | /// 71 | /// A random value that should change whenever a users credentials have changed (password changed, login removed) 72 | /// 73 | public virtual string SecurityStamp { get; set; } 74 | 75 | /// 76 | /// PhoneNumber for the user 77 | /// 78 | public virtual string PhoneNumber { get; set; } 79 | 80 | /// 81 | /// True if the phone number is confirmed, default is false 82 | /// 83 | public virtual bool PhoneNumberConfirmed { get; set; } 84 | 85 | /// 86 | /// Is two factor enabled for the user 87 | /// 88 | public virtual bool TwoFactorEnabled { get; set; } 89 | 90 | /// 91 | /// DateTime in UTC when lockout ends, any time in the past is considered not locked out. 92 | /// 93 | public virtual DateTime? LockoutEndDateUtc { get; set; } 94 | 95 | /// 96 | /// Is lockout enabled for this user 97 | /// 98 | public virtual bool LockoutEnabled { get; set; } 99 | 100 | /// 101 | /// Used to record failures for the purposes of lockout 102 | /// 103 | public virtual int AccessFailedCount { get; set; } 104 | 105 | /// 106 | /// Navigation property for user roles 107 | /// 108 | public virtual ICollection Roles { get; private set; } 109 | 110 | /// 111 | /// Navigation property for user claims 112 | /// 113 | public virtual ICollection Claims { get; private set; } 114 | 115 | /// 116 | /// Navigation property for user logins 117 | /// 118 | public virtual ICollection Logins { get; private set; } 119 | 120 | /// 121 | /// User ID (Primary Key) 122 | /// 123 | public virtual TKey Id { get; set; } 124 | 125 | /// 126 | /// User name 127 | /// 128 | public virtual string UserName { get; set; } 129 | } 130 | } -------------------------------------------------------------------------------- /src/Microsoft.AspNet.Identity.EntityFramework/IdentityUserClaim.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation, Inc. All rights reserved. 2 | // Licensed under the MIT License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | namespace Microsoft.AspNet.Identity.EntityFramework 5 | { 6 | /// 7 | /// EntityType that represents one specific user claim 8 | /// 9 | public class IdentityUserClaim : IdentityUserClaim 10 | { 11 | } 12 | 13 | /// 14 | /// EntityType that represents one specific user claim 15 | /// 16 | /// 17 | public class IdentityUserClaim 18 | { 19 | /// 20 | /// Primary key 21 | /// 22 | public virtual int Id { get; set; } 23 | 24 | /// 25 | /// User Id for the user who owns this login 26 | /// 27 | public virtual TKey UserId { get; set; } 28 | 29 | /// 30 | /// Claim type 31 | /// 32 | public virtual string ClaimType { get; set; } 33 | 34 | /// 35 | /// Claim value 36 | /// 37 | public virtual string ClaimValue { get; set; } 38 | } 39 | } -------------------------------------------------------------------------------- /src/Microsoft.AspNet.Identity.EntityFramework/IdentityUserLogin.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation, Inc. All rights reserved. 2 | // Licensed under the MIT License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | namespace Microsoft.AspNet.Identity.EntityFramework 5 | { 6 | /// 7 | /// Entity type for a user's login (i.e. facebook, google) 8 | /// 9 | public class IdentityUserLogin : IdentityUserLogin 10 | { 11 | } 12 | 13 | /// 14 | /// Entity type for a user's login (i.e. facebook, google) 15 | /// 16 | /// 17 | public class IdentityUserLogin 18 | { 19 | /// 20 | /// The login provider for the login (i.e. facebook, google) 21 | /// 22 | public virtual string LoginProvider { get; set; } 23 | 24 | /// 25 | /// Key representing the login for the provider 26 | /// 27 | public virtual string ProviderKey { get; set; } 28 | 29 | /// 30 | /// User Id for the user who owns this login 31 | /// 32 | public virtual TKey UserId { get; set; } 33 | } 34 | } -------------------------------------------------------------------------------- /src/Microsoft.AspNet.Identity.EntityFramework/IdentityUserRole.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation, Inc. All rights reserved. 2 | // Licensed under the MIT License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | namespace Microsoft.AspNet.Identity.EntityFramework 5 | { 6 | /// 7 | /// EntityType that represents a user belonging to a role 8 | /// 9 | public class IdentityUserRole : IdentityUserRole 10 | { 11 | } 12 | 13 | /// 14 | /// EntityType that represents a user belonging to a role 15 | /// 16 | /// 17 | public class IdentityUserRole 18 | { 19 | /// 20 | /// UserId for the user that is in the role 21 | /// 22 | public virtual TKey UserId { get; set; } 23 | 24 | /// 25 | /// RoleId for the role 26 | /// 27 | public virtual TKey RoleId { get; set; } 28 | } 29 | } -------------------------------------------------------------------------------- /src/Microsoft.AspNet.Identity.EntityFramework/Microsoft.AspNet.Identity.EntityFramework.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | Debug 6 | AnyCPU 7 | {D7298DAD-AB04-4502-9567-0461D0AD059E} 8 | Library 9 | bin\$(Configuration) 10 | Properties 11 | Microsoft.AspNet.Identity.EntityFramework 12 | Microsoft.AspNet.Identity.EntityFramework 13 | v4.5 14 | 512 15 | SAK 16 | SAK 17 | SAK 18 | SAK 19 | ..\..\ 20 | true 21 | 22 | 23 | true 24 | full 25 | false 26 | DEBUG;TRACE 27 | prompt 28 | 4 29 | bin\Debug\Microsoft.AspNet.Identity.EntityFramework.XML 30 | true 31 | Sdl6.1.ruleset 32 | 33 | 34 | pdbonly 35 | true 36 | TRACE 37 | prompt 38 | 4 39 | bin\Release\Microsoft.AspNet.Identity.EntityFramework.XML 40 | 41 | 42 | true 43 | 44 | 45 | true 46 | 47 | 48 | 35MSSharedLib1024.snk 49 | 50 | 51 | 52 | False 53 | ..\..\packages\EntityFramework.6.1.1\lib\net45\EntityFramework.dll 54 | 55 | 56 | False 57 | ..\..\packages\EntityFramework.6.1.1\lib\net45\EntityFramework.SqlServer.dll 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | True 78 | True 79 | IdentityResources.resx 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | {d2f24972-0f56-4c18-bd65-c26a320a0c68} 90 | Microsoft.AspNet.Identity.Core 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | ResXFileCodeGenerator 101 | IdentityResources.Designer.cs 102 | 103 | 104 | 105 | 106 | 107 | 114 | -------------------------------------------------------------------------------- /src/Microsoft.AspNet.Identity.EntityFramework/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation, Inc. All rights reserved. 2 | // Licensed under the MIT License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using System; 5 | using System.Reflection; 6 | using System.Runtime.CompilerServices; 7 | using System.Runtime.InteropServices; 8 | 9 | // General Information about an assembly is controlled through the following 10 | // set of attributes. Change these attribute values to modify the information 11 | // associated with an assembly. 12 | 13 | [assembly: AssemblyTitle("Microsoft.AspNet.Identity.EntityFramework")] 14 | [assembly: AssemblyDescription("")] 15 | [assembly: AssemblyConfiguration("")] 16 | [assembly: AssemblyCompany("Microsoft")] 17 | [assembly: AssemblyProduct("Microsoft.AspNet.Identity.EntityFramework")] 18 | [assembly: AssemblyCopyright("Copyright © Microsoft 2013")] 19 | [assembly: AssemblyTrademark("")] 20 | [assembly: AssemblyCulture("")] 21 | 22 | // Setting ComVisible to false makes the types in this assembly not visible 23 | // to COM components. If you need to access a type in this assembly from 24 | // COM, set the ComVisible attribute to true on that type. 25 | 26 | [assembly: ComVisible(false)] 27 | [assembly: CLSCompliant(true)] 28 | 29 | // The following GUID is for the ID of the typelib if this project is exposed to COM 30 | 31 | [assembly: Guid("17d56636-0d8d-401e-9484-da7965dcf45a")] 32 | 33 | // Version information for an assembly consists of the following four values: 34 | // 35 | // Major Version 36 | // Minor Version 37 | // Build Number 38 | // Revision 39 | // 40 | // You can specify all the values or you can default the Build and Revision Numbers 41 | // by using the '*' as shown below: 42 | // [assembly: AssemblyVersion("1.0.*")] 43 | 44 | [assembly: AssemblyVersion("2.0.0.0")] 45 | [assembly: AssemblyFileVersion("2.1.0.0")] 46 | [assembly: AssemblyMetadata("Serviceable", "True")] 47 | [assembly: 48 | InternalsVisibleTo( 49 | "Identity.Test, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9" 50 | )] -------------------------------------------------------------------------------- /src/Microsoft.AspNet.Identity.EntityFramework/RoleStore.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation, Inc. All rights reserved. 2 | // Licensed under the MIT License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using System; 5 | using System.Data.Entity; 6 | using System.Linq; 7 | using System.Threading.Tasks; 8 | 9 | namespace Microsoft.AspNet.Identity.EntityFramework 10 | { 11 | /// 12 | /// EntityFramework based implementation 13 | /// 14 | /// 15 | public class RoleStore : RoleStore, IQueryableRoleStore 16 | where TRole : IdentityRole, new() 17 | { 18 | /// 19 | /// Constructor 20 | /// 21 | public RoleStore() 22 | : base(new IdentityDbContext()) 23 | { 24 | DisposeContext = true; 25 | } 26 | 27 | /// 28 | /// Constructor 29 | /// 30 | /// 31 | public RoleStore(DbContext context) : base(context) 32 | { 33 | } 34 | } 35 | 36 | /// 37 | /// EntityFramework based implementation 38 | /// 39 | /// 40 | /// 41 | /// 42 | public class RoleStore : IQueryableRoleStore 43 | where TUserRole : IdentityUserRole, new() 44 | where TRole : IdentityRole, new() 45 | { 46 | private bool _disposed; 47 | private EntityStore _roleStore; 48 | 49 | /// 50 | /// Constructor which takes a db context and wires up the stores with default instances using the context 51 | /// 52 | /// 53 | public RoleStore(DbContext context) 54 | { 55 | if (context == null) 56 | { 57 | throw new ArgumentNullException("context"); 58 | } 59 | Context = context; 60 | _roleStore = new EntityStore(context); 61 | } 62 | 63 | /// 64 | /// Context for the store 65 | /// 66 | public DbContext Context { get; private set; } 67 | 68 | /// 69 | /// If true will call dispose on the DbContext during Dipose 70 | /// 71 | public bool DisposeContext { get; set; } 72 | 73 | /// 74 | /// Find a role by id 75 | /// 76 | /// 77 | /// 78 | public Task FindByIdAsync(TKey roleId) 79 | { 80 | ThrowIfDisposed(); 81 | return _roleStore.GetByIdAsync(roleId); 82 | } 83 | 84 | /// 85 | /// Find a role by name 86 | /// 87 | /// 88 | /// 89 | public Task FindByNameAsync(string roleName) 90 | { 91 | ThrowIfDisposed(); 92 | return _roleStore.EntitySet.FirstOrDefaultAsync(u => u.Name.ToUpper() == roleName.ToUpper()); 93 | } 94 | 95 | /// 96 | /// Insert an entity 97 | /// 98 | /// 99 | public virtual async Task CreateAsync(TRole role) 100 | { 101 | ThrowIfDisposed(); 102 | if (role == null) 103 | { 104 | throw new ArgumentNullException("role"); 105 | } 106 | _roleStore.Create(role); 107 | await Context.SaveChangesAsync().WithCurrentCulture(); 108 | } 109 | 110 | /// 111 | /// Mark an entity for deletion 112 | /// 113 | /// 114 | public virtual async Task DeleteAsync(TRole role) 115 | { 116 | ThrowIfDisposed(); 117 | if (role == null) 118 | { 119 | throw new ArgumentNullException("role"); 120 | } 121 | _roleStore.Delete(role); 122 | await Context.SaveChangesAsync().WithCurrentCulture(); 123 | } 124 | 125 | /// 126 | /// Update an entity 127 | /// 128 | /// 129 | public virtual async Task UpdateAsync(TRole role) 130 | { 131 | ThrowIfDisposed(); 132 | if (role == null) 133 | { 134 | throw new ArgumentNullException("role"); 135 | } 136 | _roleStore.Update(role); 137 | await Context.SaveChangesAsync().WithCurrentCulture(); 138 | } 139 | 140 | /// 141 | /// Returns an IQueryable of users 142 | /// 143 | public IQueryable Roles 144 | { 145 | get { return _roleStore.EntitySet; } 146 | } 147 | 148 | /// 149 | /// Dispose the store 150 | /// 151 | public void Dispose() 152 | { 153 | Dispose(true); 154 | GC.SuppressFinalize(this); 155 | } 156 | 157 | private void ThrowIfDisposed() 158 | { 159 | if (_disposed) 160 | { 161 | throw new ObjectDisposedException(GetType().Name); 162 | } 163 | } 164 | 165 | /// 166 | /// If disposing, calls dispose on the Context. Always nulls out the Context 167 | /// 168 | /// 169 | protected virtual void Dispose(bool disposing) 170 | { 171 | if (DisposeContext && disposing && Context != null) 172 | { 173 | Context.Dispose(); 174 | } 175 | _disposed = true; 176 | Context = null; 177 | _roleStore = null; 178 | } 179 | } 180 | } -------------------------------------------------------------------------------- /src/Microsoft.AspNet.Identity.EntityFramework/packages.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | -------------------------------------------------------------------------------- /src/Microsoft.AspNet.Identity.Owin/35MSSharedLib1024.snk: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aspnet/AspNetIdentity/a9b3a489e0942f09a2ab473039a9183ba095188d/src/Microsoft.AspNet.Identity.Owin/35MSSharedLib1024.snk -------------------------------------------------------------------------------- /src/Microsoft.AspNet.Identity.Owin/Extensions/OwinContextExtensions.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation, Inc. All rights reserved. 2 | // Licensed under the MIT License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using System; 5 | using Microsoft.Owin; 6 | 7 | namespace Microsoft.AspNet.Identity.Owin 8 | { 9 | /// 10 | /// Extension methods for OwinContext/> 11 | /// 12 | public static class OwinContextExtensions 13 | { 14 | private static readonly string IdentityKeyPrefix = "AspNet.Identity.Owin:"; 15 | 16 | private static string GetKey(Type t) 17 | { 18 | return IdentityKeyPrefix + t.AssemblyQualifiedName; 19 | } 20 | 21 | /// 22 | /// Stores an object in the OwinContext using a key based on the AssemblyQualified type name 23 | /// 24 | /// 25 | /// 26 | /// 27 | /// 28 | public static IOwinContext Set(this IOwinContext context, T value) 29 | { 30 | if (context == null) 31 | { 32 | throw new ArgumentNullException("context"); 33 | } 34 | return context.Set(GetKey(typeof (T)), value); 35 | } 36 | 37 | /// 38 | /// Retrieves an object from the OwinContext using a key based on the AssemblyQualified type name 39 | /// 40 | /// 41 | /// 42 | /// 43 | public static T Get(this IOwinContext context) 44 | { 45 | if (context == null) 46 | { 47 | throw new ArgumentNullException("context"); 48 | } 49 | return context.Get(GetKey(typeof (T))); 50 | } 51 | 52 | /// 53 | /// Get the user manager from the context 54 | /// 55 | /// 56 | /// 57 | /// 58 | public static TManager GetUserManager(this IOwinContext context) 59 | { 60 | if (context == null) 61 | { 62 | throw new ArgumentNullException("context"); 63 | } 64 | return context.Get(); 65 | } 66 | } 67 | } -------------------------------------------------------------------------------- /src/Microsoft.AspNet.Identity.Owin/ExternalLoginInfo.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation, Inc. All rights reserved. 2 | // Licensed under the MIT License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using System.Security.Claims; 5 | 6 | namespace Microsoft.AspNet.Identity.Owin 7 | { 8 | /// 9 | /// Used to return information needed to associate an external login 10 | /// 11 | public class ExternalLoginInfo 12 | { 13 | /// 14 | /// Associated login data 15 | /// 16 | public UserLoginInfo Login { get; set; } 17 | 18 | /// 19 | /// Suggested user name for a user 20 | /// 21 | public string DefaultUserName { get; set; } 22 | 23 | /// 24 | /// Email claim from the external identity 25 | /// 26 | public string Email { get; set; } 27 | 28 | /// 29 | /// The external identity 30 | /// 31 | public ClaimsIdentity ExternalIdentity { get; set; } 32 | } 33 | } -------------------------------------------------------------------------------- /src/Microsoft.AspNet.Identity.Owin/GlobalSuppressions.cs: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aspnet/AspNetIdentity/a9b3a489e0942f09a2ab473039a9183ba095188d/src/Microsoft.AspNet.Identity.Owin/GlobalSuppressions.cs -------------------------------------------------------------------------------- /src/Microsoft.AspNet.Identity.Owin/IIdentityFactoryProvider.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation, Inc. All rights reserved. 2 | // Licensed under the MIT License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using System; 5 | using Microsoft.Owin; 6 | 7 | namespace Microsoft.AspNet.Identity.Owin 8 | { 9 | /// 10 | /// Interface used to create objects per request 11 | /// 12 | /// 13 | public interface IIdentityFactoryProvider where T : IDisposable 14 | { 15 | /// 16 | /// Called once per request to create an object 17 | /// 18 | /// 19 | /// 20 | /// 21 | T Create(IdentityFactoryOptions options, IOwinContext context); 22 | 23 | /// 24 | /// Called at the end of the request to dispose the object created 25 | /// 26 | /// 27 | /// 28 | void Dispose(IdentityFactoryOptions options, T instance); 29 | } 30 | } -------------------------------------------------------------------------------- /src/Microsoft.AspNet.Identity.Owin/IdentityFactoryMiddleware.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation, Inc. All rights reserved. 2 | // Licensed under the MIT License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using System; 5 | using System.Threading.Tasks; 6 | using Microsoft.Owin; 7 | 8 | namespace Microsoft.AspNet.Identity.Owin 9 | { 10 | /// 11 | /// OwinMiddleware that initializes an object for use in the OwinContext via the Get/Set generic extensions method 12 | /// 13 | /// 14 | /// 15 | public class IdentityFactoryMiddleware : OwinMiddleware 16 | where TResult : IDisposable 17 | where TOptions : IdentityFactoryOptions 18 | { 19 | /// 20 | /// Constructor 21 | /// 22 | /// The next middleware in the OWIN pipeline to invoke 23 | /// Configuration options for the middleware 24 | public IdentityFactoryMiddleware(OwinMiddleware next, TOptions options) 25 | : base(next) 26 | { 27 | if (options == null) 28 | { 29 | throw new ArgumentNullException("options"); 30 | } 31 | if (options.Provider == null) 32 | { 33 | throw new ArgumentNullException("options.Provider"); 34 | } 35 | Options = options; 36 | } 37 | 38 | /// 39 | /// Configuration options 40 | /// 41 | public TOptions Options { get; private set; } 42 | 43 | /// 44 | /// Create an object using the Options.Provider, storing it in the OwinContext and then disposes the object when finished 45 | /// 46 | /// 47 | /// 48 | public override async Task Invoke(IOwinContext context) 49 | { 50 | var instance = Options.Provider.Create(Options, context); 51 | try 52 | { 53 | context.Set(instance); 54 | if (Next != null) 55 | { 56 | await Next.Invoke(context); 57 | } 58 | } 59 | finally 60 | { 61 | Options.Provider.Dispose(Options, instance); 62 | } 63 | } 64 | } 65 | } -------------------------------------------------------------------------------- /src/Microsoft.AspNet.Identity.Owin/IdentityFactoryOptions.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation, Inc. All rights reserved. 2 | // Licensed under the MIT License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using System; 5 | using Microsoft.Owin.Security.DataProtection; 6 | 7 | namespace Microsoft.AspNet.Identity.Owin 8 | { 9 | /// 10 | /// Configuration options for a IdentityFactoryMiddleware 11 | /// 12 | /// 13 | public class IdentityFactoryOptions where T : IDisposable 14 | { 15 | /// 16 | /// Used to configure the data protection provider 17 | /// 18 | public IDataProtectionProvider DataProtectionProvider { get; set; } 19 | 20 | /// 21 | /// Provider used to Create and Dispose objects 22 | /// 23 | public IIdentityFactoryProvider Provider { get; set; } 24 | } 25 | } -------------------------------------------------------------------------------- /src/Microsoft.AspNet.Identity.Owin/IdentityFactoryProvider.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation, Inc. All rights reserved. 2 | // Licensed under the MIT License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using System; 5 | using Microsoft.Owin; 6 | 7 | namespace Microsoft.AspNet.Identity.Owin 8 | { 9 | /// 10 | /// Used to configure how the IdentityFactoryMiddleware will create an instance of the specified type for each OwinContext 11 | /// 12 | /// 13 | public class IdentityFactoryProvider : IIdentityFactoryProvider where T : class, IDisposable 14 | { 15 | /// 16 | /// Constructor 17 | /// 18 | public IdentityFactoryProvider() 19 | { 20 | OnDispose = (options, instance) => { }; 21 | OnCreate = (options, context) => null; 22 | } 23 | 24 | /// 25 | /// A delegate assigned to this property will be invoked when the related method is called 26 | /// 27 | public Func, IOwinContext, T> OnCreate { get; set; } 28 | 29 | /// 30 | /// A delegate assigned to this property will be invoked when the related method is called 31 | /// 32 | public Action, T> OnDispose { get; set; } 33 | 34 | /// 35 | /// Calls the OnCreate Delegate 36 | /// 37 | /// 38 | /// 39 | /// 40 | public virtual T Create(IdentityFactoryOptions options, IOwinContext context) 41 | { 42 | return OnCreate(options, context); 43 | } 44 | 45 | /// 46 | /// Calls the OnDispose delegate 47 | /// 48 | /// 49 | /// 50 | public virtual void Dispose(IdentityFactoryOptions options, T instance) 51 | { 52 | OnDispose(options, instance); 53 | } 54 | } 55 | } -------------------------------------------------------------------------------- /src/Microsoft.AspNet.Identity.Owin/Microsoft.AspNet.Identity.Owin.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | Debug 6 | AnyCPU 7 | {943170EB-F4E7-4A6D-989E-2CF6C681DD89} 8 | Library 9 | bin\$(Configuration) 10 | Properties 11 | Microsoft.AspNet.Identity.Owin 12 | Microsoft.AspNet.Identity.Owin 13 | v4.5 14 | 512 15 | SAK 16 | SAK 17 | SAK 18 | SAK 19 | ..\..\ 20 | true 21 | 22 | 23 | true 24 | full 25 | false 26 | bin\Debug\ 27 | DEBUG;TRACE 28 | prompt 29 | 4 30 | Sdl6.1.ruleset 31 | true 32 | bin\Debug\Microsoft.AspNet.Identity.Owin.XML 33 | 34 | 35 | pdbonly 36 | true 37 | bin\Release\ 38 | TRACE 39 | prompt 40 | 4 41 | bin\Release\Microsoft.AspNet.Identity.Owin.XML 42 | 43 | 44 | true 45 | 46 | 47 | true 48 | 49 | 50 | 35MSSharedLib1024.snk 51 | 52 | 53 | 54 | ..\..\packages\Microsoft.Owin.4.2.2\lib\net45\Microsoft.Owin.dll 55 | 56 | 57 | ..\..\packages\Microsoft.Owin.Security.4.2.2\lib\net45\Microsoft.Owin.Security.dll 58 | 59 | 60 | ..\..\packages\Microsoft.Owin.Security.Cookies.4.2.2\lib\net45\Microsoft.Owin.Security.Cookies.dll 61 | 62 | 63 | ..\..\packages\Microsoft.Owin.Security.OAuth.4.2.2\lib\net45\Microsoft.Owin.Security.OAuth.dll 64 | 65 | 66 | ..\..\packages\Newtonsoft.Json.13.0.3\lib\net45\Newtonsoft.Json.dll 67 | 68 | 69 | False 70 | ..\..\packages\Owin.1.0\lib\net40\Owin.dll 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | {d2f24972-0f56-4c18-bd65-c26a320a0c68} 101 | Microsoft.AspNet.Identity.Core 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 118 | -------------------------------------------------------------------------------- /src/Microsoft.AspNet.Identity.Owin/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation, Inc. All rights reserved. 2 | // Licensed under the MIT License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using System; 5 | using System.Reflection; 6 | using System.Runtime.CompilerServices; 7 | using System.Runtime.InteropServices; 8 | 9 | // General Information about an assembly is controlled through the following 10 | // set of attributes. Change these attribute values to modify the information 11 | // associated with an assembly. 12 | 13 | [assembly: AssemblyTitle("Microsoft.AspNet.Identity.Owin")] 14 | [assembly: AssemblyDescription("")] 15 | [assembly: AssemblyConfiguration("")] 16 | [assembly: AssemblyCompany("")] 17 | [assembly: AssemblyProduct("Microsoft.AspNet.Identity.Owin")] 18 | [assembly: AssemblyCopyright("Copyright © 2013")] 19 | [assembly: AssemblyTrademark("")] 20 | [assembly: AssemblyCulture("")] 21 | 22 | // Setting ComVisible to false makes the types in this assembly not visible 23 | // to COM components. If you need to access a type in this assembly from 24 | // COM, set the ComVisible attribute to true on that type. 25 | 26 | [assembly: ComVisible(false)] 27 | [assembly: CLSCompliant(true)] 28 | 29 | // The following GUID is for the ID of the typelib if this project is exposed to COM 30 | 31 | [assembly: Guid("351aed40-9d23-4f3d-b323-a31cd7ba4964")] 32 | 33 | // Version information for an assembly consists of the following four values: 34 | // 35 | // Major Version 36 | // Minor Version 37 | // Build Number 38 | // Revision 39 | // 40 | // You can specify all the values or you can default the Build and Revision Numbers 41 | // by using the '*' as shown below: 42 | // [assembly: AssemblyVersion("1.0.*")] 43 | 44 | [assembly: AssemblyVersion("2.0.0.0")] 45 | [assembly: AssemblyFileVersion("2.1.0.0")] 46 | [assembly: AssemblyMetadata("Serviceable", "True")] 47 | [assembly: 48 | InternalsVisibleTo( 49 | "Identity.Test, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9" 50 | )] -------------------------------------------------------------------------------- /src/Microsoft.AspNet.Identity.Owin/SecurityStampValidator.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation, Inc. All rights reserved. 2 | // Licensed under the MIT License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using System; 5 | using System.Security.Claims; 6 | using System.Threading.Tasks; 7 | 8 | 9 | using Microsoft.Owin.Security; 10 | using Microsoft.Owin.Security.Cookies; 11 | 12 | namespace Microsoft.AspNet.Identity.Owin 13 | { 14 | /// 15 | /// Static helper class used to configure a CookieAuthenticationProvider to validate a cookie against a user's security 16 | /// stamp 17 | /// 18 | public static class SecurityStampValidator 19 | { 20 | /// 21 | /// Can be used as the ValidateIdentity method for a CookieAuthenticationProvider which will check a user's security 22 | /// stamp after validateInterval 23 | /// Rejects the identity if the stamp changes, and otherwise will call regenerateIdentity to sign in a new 24 | /// ClaimsIdentity 25 | /// 26 | /// 27 | /// 28 | /// 29 | /// 30 | /// 31 | public static Func OnValidateIdentity( 32 | TimeSpan validateInterval, Func> regenerateIdentity) 33 | where TManager : UserManager 34 | where TUser : class, IUser 35 | { 36 | return OnValidateIdentity(validateInterval, regenerateIdentity, id => id.GetUserId()); 37 | } 38 | 39 | /// 40 | /// Can be used as the ValidateIdentity method for a CookieAuthenticationProvider which will check a user's security 41 | /// stamp after validateInterval 42 | /// Rejects the identity if the stamp changes, and otherwise will call regenerateIdentity to sign in a new 43 | /// ClaimsIdentity 44 | /// 45 | /// 46 | /// 47 | /// 48 | /// 49 | /// 50 | /// 51 | /// 52 | public static Func OnValidateIdentity( 53 | TimeSpan validateInterval, Func> regenerateIdentityCallback, 54 | Func getUserIdCallback) 55 | where TManager : UserManager 56 | where TUser : class, IUser 57 | where TKey : IEquatable 58 | { 59 | if (getUserIdCallback == null) 60 | { 61 | throw new ArgumentNullException("getUserIdCallback"); 62 | } 63 | return async context => 64 | { 65 | var currentUtc = DateTimeOffset.UtcNow; 66 | if (context.Options != null && context.Options.SystemClock != null) 67 | { 68 | currentUtc = context.Options.SystemClock.UtcNow; 69 | } 70 | var issuedUtc = context.Properties.IssuedUtc; 71 | 72 | // Only validate if enough time has elapsed 73 | var validate = (issuedUtc == null); 74 | if (issuedUtc != null) 75 | { 76 | var timeElapsed = currentUtc.Subtract(issuedUtc.Value); 77 | validate = timeElapsed > validateInterval; 78 | } 79 | if (validate) 80 | { 81 | var manager = context.OwinContext.GetUserManager(); 82 | var userId = getUserIdCallback(context.Identity); 83 | if (manager != null && userId != null) 84 | { 85 | var user = await manager.FindByIdAsync(userId).WithCurrentCulture(); 86 | var reject = true; 87 | // Refresh the identity if the stamp matches, otherwise reject 88 | if (user != null && manager.SupportsUserSecurityStamp) 89 | { 90 | var securityStamp = 91 | context.Identity.FindFirstValue(Constants.DefaultSecurityStampClaimType); 92 | if (securityStamp == await manager.GetSecurityStampAsync(userId).WithCurrentCulture()) 93 | { 94 | reject = false; 95 | // Regenerate fresh claims if possible and resign in 96 | if (regenerateIdentityCallback != null) 97 | { 98 | var identity = await regenerateIdentityCallback.Invoke(manager, user).WithCurrentCulture(); 99 | if (identity != null) 100 | { 101 | // Fix for regression where this value is not updated 102 | // Setting it to null so that it is refreshed by the cookie middleware 103 | context.Properties.IssuedUtc = null; 104 | context.Properties.ExpiresUtc = null; 105 | context.OwinContext.Authentication.SignIn(context.Properties, identity); 106 | } 107 | } 108 | } 109 | } 110 | if (reject) 111 | { 112 | context.RejectIdentity(); 113 | context.OwinContext.Authentication.SignOut(context.Options.AuthenticationType); 114 | } 115 | } 116 | } 117 | }; 118 | } 119 | } 120 | } -------------------------------------------------------------------------------- /src/Microsoft.AspNet.Identity.Owin/SignInStatus.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation, Inc. All rights reserved. 2 | // Licensed under the MIT License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | namespace Microsoft.AspNet.Identity.Owin 5 | { 6 | /// 7 | /// Possible results from a sign in attempt 8 | /// 9 | public enum SignInStatus 10 | { 11 | /// 12 | /// Sign in was successful 13 | /// 14 | Success, 15 | 16 | /// 17 | /// User is locked out 18 | /// 19 | LockedOut, 20 | 21 | /// 22 | /// Sign in requires addition verification (i.e. two factor) 23 | /// 24 | RequiresVerification, 25 | 26 | /// 27 | /// Sign in failed 28 | /// 29 | Failure 30 | } 31 | 32 | } -------------------------------------------------------------------------------- /src/Microsoft.AspNet.Identity.Owin/app.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | -------------------------------------------------------------------------------- /src/Microsoft.AspNet.Identity.Owin/packages.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /test/Identity.Test/35MSSharedLib1024.snk: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aspnet/AspNetIdentity/a9b3a489e0942f09a2ab473039a9183ba095188d/test/Identity.Test/35MSSharedLib1024.snk -------------------------------------------------------------------------------- /test/Identity.Test/App.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 |
6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | -------------------------------------------------------------------------------- /test/Identity.Test/AsyncHelperTest.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation, Inc. All rights reserved. 2 | // Licensed under the MIT License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using System; 5 | using System.Globalization; 6 | using System.Threading; 7 | using System.Threading.Tasks; 8 | using Microsoft.AspNet.Identity; 9 | using Xunit; 10 | 11 | namespace Identity.Test 12 | { 13 | public class AsyncHelperTest 14 | { 15 | [Fact] 16 | public void RunSyncPreservesCulture() 17 | { 18 | var originalCulture = Thread.CurrentThread.CurrentCulture; 19 | var originalUiCulture = Thread.CurrentThread.CurrentUICulture; 20 | var expectedCulture = new CultureInfo("de-DE"); 21 | Thread.CurrentThread.CurrentCulture = expectedCulture; 22 | Thread.CurrentThread.CurrentUICulture = expectedCulture; 23 | try 24 | { 25 | var cultures = AsyncHelper.RunSync(GetCultureAsync); 26 | Assert.Equal(expectedCulture, cultures.Item1); 27 | Assert.Equal(expectedCulture, cultures.Item2); 28 | } 29 | finally 30 | { 31 | Thread.CurrentThread.CurrentCulture = originalCulture; 32 | Thread.CurrentThread.CurrentUICulture = originalUiCulture; 33 | } 34 | } 35 | 36 | [Fact] 37 | public void RunSyncVoidPreservesCulture() 38 | { 39 | var originalCulture = Thread.CurrentThread.CurrentCulture; 40 | var originalUiCulture = Thread.CurrentThread.CurrentUICulture; 41 | var expectedCulture = new CultureInfo("de-DE"); 42 | Thread.CurrentThread.CurrentCulture = expectedCulture; 43 | Thread.CurrentThread.CurrentUICulture = expectedCulture; 44 | try 45 | { 46 | AsyncHelper.RunSync(() => ExpectCulture(expectedCulture)); 47 | } 48 | finally 49 | { 50 | Thread.CurrentThread.CurrentCulture = originalCulture; 51 | Thread.CurrentThread.CurrentUICulture = originalUiCulture; 52 | } 53 | } 54 | 55 | private static Task> GetCultureAsync() 56 | { 57 | return Task.FromResult(new Tuple(CultureInfo.CurrentCulture, CultureInfo.CurrentUICulture)); 58 | } 59 | 60 | private static Task ExpectCulture(CultureInfo culture) 61 | { 62 | Assert.Equal(culture, CultureInfo.CurrentCulture); 63 | Assert.Equal(culture, CultureInfo.CurrentUICulture); 64 | return Task.FromResult(0); 65 | } 66 | } 67 | } -------------------------------------------------------------------------------- /test/Identity.Test/ClaimsIdentityFactoryTest.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation, Inc. All rights reserved. 2 | // Licensed under the MIT License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using System.Linq; 5 | using System.Security.Claims; 6 | using System.Threading.Tasks; 7 | using Microsoft.AspNet.Identity; 8 | using Microsoft.AspNet.Identity.EntityFramework; 9 | using Xunit; 10 | 11 | namespace Identity.Test 12 | { 13 | public class ClaimsIdentityFactoryTest 14 | { 15 | [Fact] 16 | public void CreateIdentityNullCheckTest() 17 | { 18 | var factory = new ClaimsIdentityFactory(); 19 | var manager = new UserManager(new UserStore()); 20 | ExceptionHelper.ThrowsArgumentNull( 21 | () => AsyncHelper.RunSync(() => factory.CreateAsync(null, null, "whatever")), "manager"); 22 | ExceptionHelper.ThrowsArgumentNull( 23 | () => AsyncHelper.RunSync(() => factory.CreateAsync(manager, null, "whatever")), "user"); 24 | ExceptionHelper.ThrowsArgumentNull( 25 | () => AsyncHelper.RunSync(() => factory.CreateAsync(manager, new IdentityUser(), null)), "value"); 26 | ExceptionHelper.ThrowsArgumentNull(() => factory.ConvertIdToString(null), "key"); 27 | } 28 | 29 | [Fact] 30 | public async Task ClaimsIdentityTest() 31 | { 32 | var db = UnitTestHelper.CreateDefaultDb(); 33 | var manager = new UserManager(new UserStore(db)); 34 | var role = new RoleManager(new RoleStore(db)); 35 | var user = new IdentityUser("Hao"); 36 | UnitTestHelper.IsSuccess(await manager.CreateAsync(user)); 37 | UnitTestHelper.IsSuccess(await role.CreateAsync(new IdentityRole("Admin"))); 38 | UnitTestHelper.IsSuccess(await role.CreateAsync(new IdentityRole("Local"))); 39 | UnitTestHelper.IsSuccess(await manager.AddToRoleAsync(user.Id, "Admin")); 40 | UnitTestHelper.IsSuccess(await manager.AddToRoleAsync(user.Id, "Local")); 41 | Claim[] userClaims = 42 | { 43 | new Claim("Whatever", "Value"), 44 | new Claim("Whatever2", "Value2") 45 | }; 46 | foreach (var c in userClaims) 47 | { 48 | UnitTestHelper.IsSuccess(await manager.AddClaimAsync(user.Id, c)); 49 | } 50 | 51 | var identity = await manager.CreateIdentityAsync(user, "test"); 52 | var claimsFactory = manager.ClaimsIdentityFactory as ClaimsIdentityFactory; 53 | Assert.NotNull(claimsFactory); 54 | var claims = identity.Claims; 55 | Assert.NotNull(claims); 56 | Assert.True( 57 | claims.Any(c => c.Type == claimsFactory.UserNameClaimType && c.Value == user.UserName)); 58 | Assert.True(claims.Any(c => c.Type == claimsFactory.UserIdClaimType && c.Value == user.Id)); 59 | Assert.True(claims.Any(c => c.Type == claimsFactory.RoleClaimType && c.Value == "Admin")); 60 | Assert.True(claims.Any(c => c.Type == claimsFactory.RoleClaimType && c.Value == "Local")); 61 | Assert.True( 62 | claims.Any( 63 | c => 64 | c.Type == ClaimsIdentityFactory.IdentityProviderClaimType && 65 | c.Value == ClaimsIdentityFactory.DefaultIdentityProviderClaimValue)); 66 | foreach (var cl in userClaims) 67 | { 68 | Assert.True(claims.Any(c => c.Type == cl.Type && c.Value == cl.Value)); 69 | } 70 | } 71 | 72 | [Fact] 73 | public void ClaimsIdentitySyncTest() 74 | { 75 | var db = UnitTestHelper.CreateDefaultDb(); 76 | var manager = new UserManager(new UserStore(db)); 77 | var role = new RoleManager(new RoleStore(db)); 78 | var user = new IdentityUser("Hao"); 79 | var claimsFactory = manager.ClaimsIdentityFactory as ClaimsIdentityFactory; 80 | Assert.NotNull(claimsFactory); 81 | UnitTestHelper.IsSuccess(manager.Create(user)); 82 | UnitTestHelper.IsSuccess(role.Create(new IdentityRole("Admin"))); 83 | UnitTestHelper.IsSuccess(role.Create(new IdentityRole("Local"))); 84 | UnitTestHelper.IsSuccess(manager.AddToRole(user.Id, "Admin")); 85 | UnitTestHelper.IsSuccess(manager.AddToRole(user.Id, "Local")); 86 | Claim[] userClaims = 87 | { 88 | new Claim("Whatever", "Value"), 89 | new Claim("Whatever2", "Value2") 90 | }; 91 | foreach (var c in userClaims) 92 | { 93 | UnitTestHelper.IsSuccess(manager.AddClaim(user.Id, c)); 94 | } 95 | var identity = manager.CreateIdentity(user, "test"); 96 | var claims = identity.Claims; 97 | Assert.NotNull(claims); 98 | Assert.NotNull(claims); 99 | Assert.True( 100 | claims.Any(c => c.Type == claimsFactory.UserNameClaimType && c.Value == user.UserName)); 101 | Assert.True(claims.Any(c => c.Type == claimsFactory.UserIdClaimType && c.Value == user.Id)); 102 | Assert.True(claims.Any(c => c.Type == claimsFactory.RoleClaimType && c.Value == "Admin")); 103 | Assert.True(claims.Any(c => c.Type == claimsFactory.RoleClaimType && c.Value == "Local")); 104 | Assert.True( 105 | claims.Any( 106 | c => 107 | c.Type == ClaimsIdentityFactory.IdentityProviderClaimType && 108 | c.Value == ClaimsIdentityFactory.DefaultIdentityProviderClaimValue)); 109 | foreach (var cl in userClaims) 110 | { 111 | Assert.True(claims.Any(c => c.Type == cl.Type && c.Value == cl.Value)); 112 | } 113 | } 114 | } 115 | } -------------------------------------------------------------------------------- /test/Identity.Test/ExceptionHelper.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation, Inc. All rights reserved. 2 | // Licensed under the MIT License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using System; 5 | using Xunit; 6 | 7 | namespace Identity.Test 8 | { 9 | public static class ExceptionHelper 10 | { 11 | public static TException ThrowsWithError(Assert.ThrowsDelegate act, string error) 12 | where TException : Exception 13 | { 14 | var e = Assert.Throws(act); 15 | if (e != null) 16 | { 17 | Assert.Equal(error, e.Message); 18 | } 19 | return e; 20 | } 21 | 22 | public static ArgumentException ThrowsArgumentException(Assert.ThrowsDelegate del, string exceptionMessage, 23 | string paramName) 24 | { 25 | var e = Assert.Throws(del); 26 | // Only check exception message on English build and OS, since some exception messages come from the OS 27 | // and will be in the native language. 28 | if (UnitTestHelper.EnglishBuildAndOS) 29 | { 30 | Assert.Equal(exceptionMessage, e.Message); //, "Incorrect exception message."); 31 | Assert.Equal(paramName, e.ParamName); //, "Incorrect exception parameter name."); 32 | } 33 | return e; 34 | } 35 | 36 | public static ArgumentException ThrowsArgumentNullOrEmpty(Assert.ThrowsDelegate del, string paramName) 37 | { 38 | return ThrowsArgumentException(del, "Value cannot be null or empty.\r\nParameter name: " + paramName, 39 | paramName); 40 | } 41 | 42 | public static ArgumentNullException ThrowsArgumentNull(Assert.ThrowsDelegate del, string paramName) 43 | { 44 | var e = Assert.Throws(del); 45 | Assert.Equal(paramName, e.ParamName); 46 | return e; 47 | } 48 | } 49 | } -------------------------------------------------------------------------------- /test/Identity.Test/IdentityDbContextTest.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation, Inc. All rights reserved. 2 | // Licensed under the MIT License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using System.Data.Entity; 5 | using System.Data.Entity.Validation; 6 | using System.Data.SqlClient; 7 | using System.Linq; 8 | using Microsoft.AspNet.Identity.EntityFramework; 9 | using Xunit; 10 | 11 | namespace Identity.Test 12 | { 13 | public class IdentityDbContextTest 14 | { 15 | [Fact] 16 | public void EnsureDefaultSchema() 17 | { 18 | VerifyDefaultSchema(CreateDb()); 19 | } 20 | 21 | internal static void VerifyDefaultSchema(DbContext dbContext) 22 | { 23 | var sqlConn = dbContext.Database.Connection as SqlConnection; 24 | // Give up and assume its ok if its not a sql connection 25 | if (sqlConn == null) 26 | { 27 | Assert.True(false, "Expected a sql connection"); 28 | } 29 | using (var db = new SqlConnection(sqlConn.ConnectionString)) 30 | { 31 | db.Open(); 32 | Assert.True(VerifyColumns(db, "AspNetUsers", "Id", "UserName", "Email", "PasswordHash", "SecurityStamp", 33 | "EmailConfirmed", "PhoneNumber", "PhoneNumberConfirmed", "TwoFactorEnabled", "LockoutEnabled", 34 | "LockoutEndDateUtc", "AccessFailedCount")); 35 | Assert.True(VerifyColumns(db, "AspNetRoles", "Id", "Name")); 36 | Assert.True(VerifyColumns(db, "AspNetUserRoles", "UserId", "RoleId")); 37 | Assert.True(VerifyColumns(db, "AspNetUserClaims", "Id", "UserId", "ClaimType", "ClaimValue")); 38 | Assert.True(VerifyColumns(db, "AspNetUserLogins", "UserId", "ProviderKey", "LoginProvider")); 39 | 40 | VerifyIndex(db, "AspNetRoles", "RoleNameIndex"); 41 | VerifyIndex(db, "AspNetUsers", "UserNameIndex"); 42 | db.Close(); 43 | } 44 | } 45 | 46 | internal static bool VerifyColumns(SqlConnection conn, string table, params string[] columns) 47 | { 48 | var count = 0; 49 | using ( 50 | var command = 51 | new SqlCommand("SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS where TABLE_NAME=@Table", conn)) 52 | { 53 | command.Parameters.Add(new SqlParameter("Table", table)); 54 | using (var reader = command.ExecuteReader()) 55 | { 56 | while (reader.Read()) 57 | { 58 | count++; 59 | if (!columns.Contains(reader.GetString(0))) 60 | { 61 | return false; 62 | } 63 | } 64 | return count == columns.Length; 65 | } 66 | } 67 | } 68 | 69 | internal static void VerifyIndex(SqlConnection conn, string table, string index) 70 | { 71 | using ( 72 | var command = 73 | new SqlCommand( 74 | "SELECT COUNT(*) FROM sys.indexes where NAME=@Index AND object_id = OBJECT_ID(@Table)", conn)) 75 | { 76 | command.Parameters.Add(new SqlParameter("Index", index)); 77 | command.Parameters.Add(new SqlParameter("Table", table)); 78 | using (var reader = command.ExecuteReader()) 79 | { 80 | Assert.True(reader.Read()); 81 | Assert.True(reader.GetInt32(0) > 0); 82 | } 83 | } 84 | } 85 | 86 | [Fact] 87 | public void IdentityDbContextEnsuresUserNamesUniqueTest() 88 | { 89 | var db = CreateDb(); 90 | db.Users.Add(new IdentityUser("Hao")); 91 | db.SaveChanges(); 92 | db.Users.Add(new IdentityUser("HaO")); 93 | try 94 | { 95 | db.SaveChanges(); 96 | Assert.False(true); 97 | } 98 | catch (DbEntityValidationException e) 99 | { 100 | Assert.Equal("User name HaO is already taken.", 101 | e.EntityValidationErrors.First().ValidationErrors.First().ErrorMessage); 102 | } 103 | } 104 | 105 | [Fact] 106 | public void IdentityDbContextEnsuresRoleNamesUniqueTest() 107 | { 108 | var db = CreateDb(); 109 | db.Roles.Add(new IdentityRole("admin")); 110 | db.SaveChanges(); 111 | db.Roles.Add(new IdentityRole("ADMIN")); 112 | try 113 | { 114 | db.SaveChanges(); 115 | Assert.False(true); 116 | } 117 | catch (DbEntityValidationException e) 118 | { 119 | Assert.Equal("Role ADMIN already exists.", 120 | e.EntityValidationErrors.First().ValidationErrors.First().ErrorMessage); 121 | } 122 | } 123 | 124 | private IdentityDbContext CreateDb() 125 | { 126 | Database.SetInitializer(new DropCreateDatabaseAlways()); 127 | var db = new IdentityDbContext(); 128 | db.Database.Initialize(true); 129 | return db; 130 | } 131 | } 132 | } -------------------------------------------------------------------------------- /test/Identity.Test/IdentityExtensionsTest.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation, Inc. All rights reserved. 2 | // Licensed under the MIT License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using System; 5 | using System.Security.Claims; 6 | using System.Security.Principal; 7 | using Microsoft.AspNet.Identity; 8 | using Xunit; 9 | 10 | namespace Identity.Test 11 | { 12 | public class IdentityExtensionsTest 13 | { 14 | public const string ExternalAuthenticationType = "TestExternalAuth"; 15 | 16 | [Fact] 17 | public void IdentityNullCheckTest() 18 | { 19 | IIdentity identity = null; 20 | ExceptionHelper.ThrowsArgumentNull(() => identity.GetUserId(), "identity"); 21 | ExceptionHelper.ThrowsArgumentNull(() => identity.GetUserName(), "identity"); 22 | ClaimsIdentity claimsIdentity = null; 23 | ExceptionHelper.ThrowsArgumentNull(() => claimsIdentity.FindFirstValue(null), "identity"); 24 | } 25 | 26 | [Fact] 27 | public void IdentityNullIfNotClaimsIdentityTest() 28 | { 29 | IIdentity identity = new TestIdentity(); 30 | Assert.Null(identity.GetUserId()); 31 | Assert.Null(identity.GetUserName()); 32 | } 33 | 34 | [Fact] 35 | public void UserNameAndIdTest() 36 | { 37 | var id = CreateTestExternalIdentity(); 38 | Assert.Equal("NameIdentifier", id.GetUserId()); 39 | Assert.Equal("Name", id.GetUserName()); 40 | } 41 | 42 | [Fact] 43 | public void CustomIdTest() 44 | { 45 | var id = new ClaimsIdentity( 46 | new[] 47 | { 48 | new Claim(ClaimTypes.NameIdentifier, "3", null, ExternalAuthenticationType), 49 | }, 50 | ExternalAuthenticationType); 51 | Assert.Equal(3, id.GetUserId()); 52 | } 53 | 54 | [Fact] 55 | public void NoIdReturnsDefaultValue() 56 | { 57 | var id = new ClaimsIdentity(); 58 | Assert.Equal(0, id.GetUserId()); 59 | } 60 | 61 | [Fact] 62 | public void IdentityExtensionsFindFirstValueNullIfUnknownTest() 63 | { 64 | var id = CreateTestExternalIdentity(); 65 | Assert.Null(id.FindFirstValue("bogus")); 66 | } 67 | 68 | private static ClaimsIdentity CreateTestExternalIdentity() 69 | { 70 | return new ClaimsIdentity( 71 | new[] 72 | { 73 | new Claim(ClaimTypes.NameIdentifier, "NameIdentifier", null, ExternalAuthenticationType), 74 | new Claim(ClaimTypes.Name, "Name") 75 | }, 76 | ExternalAuthenticationType); 77 | } 78 | 79 | private class TestIdentity : IIdentity 80 | { 81 | public string AuthenticationType 82 | { 83 | get { throw new NotImplementedException(); } 84 | } 85 | 86 | public bool IsAuthenticated 87 | { 88 | get { throw new NotImplementedException(); } 89 | } 90 | 91 | public string Name 92 | { 93 | get { throw new NotImplementedException(); } 94 | } 95 | } 96 | } 97 | } -------------------------------------------------------------------------------- /test/Identity.Test/IdentityResultTest.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation, Inc. All rights reserved. 2 | // Licensed under the MIT License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using System.Linq; 5 | using Microsoft.AspNet.Identity; 6 | using Xunit; 7 | 8 | namespace Identity.Test 9 | { 10 | public class IdentityResultTest 11 | { 12 | [Fact] 13 | public void NullErrorsBecomeDefaultTest() 14 | { 15 | var result = new IdentityResult(null); 16 | Assert.NotNull(result.Errors); 17 | Assert.False(result.Succeeded); 18 | Assert.Equal(1, result.Errors.Count()); 19 | Assert.Equal("An unknown failure has occured.", result.Errors.First()); 20 | } 21 | } 22 | } -------------------------------------------------------------------------------- /test/Identity.Test/LoginsTest.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation, Inc. All rights reserved. 2 | // Licensed under the MIT License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using System.Linq; 5 | using System.Threading.Tasks; 6 | using Microsoft.AspNet.Identity; 7 | using Microsoft.AspNet.Identity.EntityFramework; 8 | using Xunit; 9 | 10 | namespace Identity.Test 11 | { 12 | public class LoginsTest 13 | { 14 | [Fact] 15 | public async Task LinkUnlinkDeletesTest() 16 | { 17 | var db = UnitTestHelper.CreateDefaultDb(); 18 | var mgr = new UserManager(new UserStore(db)); 19 | var user = new IdentityUser("linkunlinktest"); 20 | UnitTestHelper.IsSuccess(await mgr.CreateAsync(user)); 21 | var userLogin1 = new UserLoginInfo("provider1", "p1-1"); 22 | var userLogin2 = new UserLoginInfo("provider2", "p2-1"); 23 | Assert.Equal(0, (await mgr.GetLoginsAsync(user.Id)).Count); 24 | UnitTestHelper.IsSuccess(await mgr.AddLoginAsync(user.Id, userLogin1)); 25 | Assert.Equal(1, user.Logins.Count(l => l.ProviderKey == "p1-1")); 26 | Assert.Equal(1, (await mgr.GetLoginsAsync(user.Id)).Count); 27 | UnitTestHelper.IsSuccess(await mgr.AddLoginAsync(user.Id, userLogin2)); 28 | Assert.Equal(1, user.Logins.Count(l => l.ProviderKey == "p2-1")); 29 | Assert.Equal(2, (await mgr.GetLoginsAsync(user.Id)).Count); 30 | UnitTestHelper.IsSuccess(await mgr.RemoveLoginAsync(user.Id, userLogin1)); 31 | Assert.Equal(0, user.Logins.Count(l => l.ProviderKey == "p1-1")); 32 | Assert.Equal(1, user.Logins.Count(l => l.ProviderKey == "p2-1")); 33 | Assert.Equal(1, (await mgr.GetLoginsAsync(user.Id)).Count()); 34 | UnitTestHelper.IsSuccess(await mgr.RemoveLoginAsync(user.Id, userLogin2)); 35 | Assert.Equal(0, (await mgr.GetLoginsAsync(user.Id)).Count); 36 | Assert.Equal(0, db.Set().Count()); 37 | } 38 | 39 | [Fact] 40 | public async Task AddDuplicateLoginFailsTest() 41 | { 42 | var db = UnitTestHelper.CreateDefaultDb(); 43 | var mgr = new UserManager(new UserStore(db)); 44 | var user = new IdentityUser("dupeLogintest"); 45 | UnitTestHelper.IsSuccess(await mgr.CreateAsync(user)); 46 | var userLogin1 = new UserLoginInfo("provider1", "p1-1"); 47 | UnitTestHelper.IsSuccess(await mgr.AddLoginAsync(user.Id, userLogin1)); 48 | UnitTestHelper.IsFailure(await mgr.AddLoginAsync(user.Id, userLogin1)); 49 | } 50 | 51 | 52 | //[Fact] 53 | //public async Task RemoveUnknownLoginFailsTest() { 54 | // var store = new UserManager(new UserStore(UnitTestHelper.CreateDefaultDb())); 55 | // UnitTestHelper.IsFailure(await store.Users.RemoveLoginAsync("bogus", "whatever", "ignored")); 56 | //} 57 | 58 | [Fact] 59 | public async Task AddLoginNullLoginFailsTest() 60 | { 61 | var db = UnitTestHelper.CreateDefaultDb(); 62 | var manager = new UserManager(new UserStore(db)); 63 | var user = new IdentityUser("Hao"); 64 | UnitTestHelper.IsSuccess(await manager.CreateAsync(user)); 65 | ExceptionHelper.ThrowsArgumentNull(() => AsyncHelper.RunSync(() => manager.AddLoginAsync(user.Id, null)), 66 | "login"); 67 | } 68 | } 69 | } -------------------------------------------------------------------------------- /test/Identity.Test/OwinContextExtensionsTest.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation, Inc. All rights reserved. 2 | // Licensed under the MIT License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using Microsoft.AspNet.Identity.Owin; 5 | using Microsoft.Owin; 6 | using Xunit; 7 | 8 | namespace Identity.Test 9 | { 10 | public class OwinContextExtensionsTest 11 | { 12 | [Fact] 13 | public void MiddlewareExtensionsNullCheckTest() 14 | { 15 | IOwinContext context = null; 16 | ExceptionHelper.ThrowsArgumentNull(() => context.Get(), "context"); 17 | ExceptionHelper.ThrowsArgumentNull(() => context.GetUserManager(), "context"); 18 | ExceptionHelper.ThrowsArgumentNull(() => context.Set(null), "context"); 19 | } 20 | } 21 | } -------------------------------------------------------------------------------- /test/Identity.Test/PasswordValidatorTest.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation, Inc. All rights reserved. 2 | // Licensed under the MIT License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using System.Threading.Tasks; 5 | using Microsoft.AspNet.Identity; 6 | using Xunit; 7 | 8 | namespace Identity.Test 9 | { 10 | public class PasswordValidatorTest 11 | { 12 | [Fact] 13 | public async Task RequiredLengthTest() 14 | { 15 | var error = "Passwords must be at least 6 characters."; 16 | var valid = new PasswordValidator {RequiredLength = 6}; 17 | UnitTestHelper.IsFailure(await valid.ValidateAsync(""), error); 18 | UnitTestHelper.IsFailure(await valid.ValidateAsync("abcde"), error); 19 | UnitTestHelper.IsSuccess(await valid.ValidateAsync("abcdef")); 20 | UnitTestHelper.IsSuccess(await valid.ValidateAsync("abcdeldkajfd")); 21 | } 22 | 23 | [Fact] 24 | public async Task RequiredNonAlphanumericTest() 25 | { 26 | var error = "Passwords must have at least one non letter or digit character."; 27 | var valid = new PasswordValidator {RequireNonLetterOrDigit = true}; 28 | UnitTestHelper.IsFailure(await valid.ValidateAsync("abcde"), error); 29 | UnitTestHelper.IsSuccess(await valid.ValidateAsync("abcd@e!ld!kajfd")); 30 | UnitTestHelper.IsSuccess(await valid.ValidateAsync("!!!!!!")); 31 | } 32 | 33 | [Fact] 34 | public async Task MixedRequiredTest() 35 | { 36 | var alphaError = "Passwords must have at least one non letter or digit character."; 37 | var upperError = "Passwords must have at least one uppercase ('A'-'Z')."; 38 | var lowerError = "Passwords must have at least one lowercase ('a'-'z')."; 39 | var digitError = "Passwords must have at least one digit ('0'-'9')."; 40 | var lengthError = "Passwords must be at least 6 characters."; 41 | var valid = new PasswordValidator 42 | { 43 | RequireNonLetterOrDigit = true, 44 | RequireDigit = true, 45 | RequireLowercase = true, 46 | RequireUppercase = true, 47 | RequiredLength = 6 48 | }; 49 | UnitTestHelper.IsFailure(await valid.ValidateAsync("abcde"), 50 | string.Join(" ", lengthError, alphaError, digitError, upperError)); 51 | UnitTestHelper.IsFailure(await valid.ValidateAsync("a@B@cd"), digitError); 52 | UnitTestHelper.IsFailure(await valid.ValidateAsync("___"), 53 | string.Join(" ", lengthError, digitError, lowerError, upperError)); 54 | UnitTestHelper.IsFailure(await valid.ValidateAsync("a_b9de"), upperError); 55 | UnitTestHelper.IsSuccess(await valid.ValidateAsync("abcd@e!ld!kaj9Fd")); 56 | } 57 | } 58 | } -------------------------------------------------------------------------------- /test/Identity.Test/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation, Inc. All rights reserved. 2 | // Licensed under the MIT License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using System.Reflection; 5 | using System.Runtime.InteropServices; 6 | 7 | // General Information about an assembly is controlled through the following 8 | // set of attributes. Change these attribute values to modify the information 9 | // associated with an assembly. 10 | 11 | [assembly: AssemblyTitle("Identity.SystemWeb.Test")] 12 | [assembly: AssemblyDescription("")] 13 | [assembly: AssemblyConfiguration("")] 14 | [assembly: AssemblyCompany("Microsoft")] 15 | [assembly: AssemblyProduct("Identity.SystemWeb.Test")] 16 | [assembly: AssemblyCopyright("Copyright © Microsoft 2013")] 17 | [assembly: AssemblyTrademark("")] 18 | [assembly: AssemblyCulture("")] 19 | 20 | // Setting ComVisible to false makes the types in this assembly not visible 21 | // to COM components. If you need to access a type in this assembly from 22 | // COM, set the ComVisible attribute to true on that type. 23 | 24 | [assembly: ComVisible(false)] 25 | 26 | // The following GUID is for the ID of the typelib if this project is exposed to COM 27 | 28 | [assembly: Guid("227caea7-5b0c-42be-91d6-c395febe58ef")] 29 | 30 | // Version information for an assembly consists of the following four values: 31 | // 32 | // Major Version 33 | // Minor Version 34 | // Build Number 35 | // Revision 36 | // 37 | // You can specify all the values or you can default the Build and Revision Numbers 38 | // by using the '*' as shown below: 39 | // [assembly: AssemblyVersion("1.0.*")] 40 | 41 | [assembly: AssemblyVersion("1.0.0.0")] 42 | [assembly: AssemblyFileVersion("1.0.0.0")] -------------------------------------------------------------------------------- /test/Identity.Test/SignInManagerTest.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation, Inc. All rights reserved. 2 | // Licensed under the MIT License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using System; 5 | using System.Threading.Tasks; 6 | using Microsoft.AspNet.Identity; 7 | using Microsoft.AspNet.Identity.EntityFramework; 8 | using Microsoft.AspNet.Identity.Owin; 9 | using Microsoft.Owin; 10 | using Microsoft.Owin.Security.DataProtection; 11 | using Moq; 12 | using Xunit; 13 | using Xunit.Extensions; 14 | 15 | namespace Identity.Test 16 | { 17 | public class SignInManagerTest 18 | { 19 | [Theory] 20 | [InlineData(true, true)] 21 | [InlineData(true, false)] 22 | [InlineData(false, true)] 23 | [InlineData(false, false)] 24 | public async Task SignInAsyncCookiePersistenceTest(bool isPersistent, bool rememberBrowser) 25 | { 26 | var owinContext = new OwinContext(); 27 | await TestUtil.CreateManager(owinContext); 28 | var manager = owinContext.GetUserManager>(); 29 | var user = new IdentityUser("SignInTest"); 30 | UnitTestHelper.IsSuccess(await manager.CreateAsync(user)); 31 | var signInManager = new SignInManager(manager, owinContext.Authentication); 32 | 33 | await signInManager.SignInAsync(user, isPersistent, rememberBrowser); 34 | 35 | Assert.Equal(isPersistent, owinContext.Authentication.AuthenticationResponseGrant.Properties.IsPersistent); 36 | } 37 | 38 | [Fact] 39 | public async Task PasswordSignInFailsWhenResetLockoutFails() 40 | { 41 | // Setup 42 | var owinContext = new OwinContext(); 43 | await TestUtil.CreateManager(owinContext); 44 | var manager = new Mock>(Mock.Of>()); 45 | var user = new IdentityUser("SignInTest"); 46 | manager.Setup(m => m.FindByNameAsync(user.Id)).Returns(Task.FromResult(user)).Verifiable(); 47 | manager.Setup(m => m.IsLockedOutAsync(user.Id)).Returns(Task.FromResult(false)).Verifiable(); 48 | manager.Setup(m => m.CheckPasswordAsync(user, "[PLACEHOLDER]-1a")).Returns(Task.FromResult(true)).Verifiable(); 49 | manager.Setup(m => m.GetTwoFactorEnabledAsync(user.Id)).Returns(Task.FromResult(false)).Verifiable(); 50 | manager.Setup(m => m.ResetAccessFailedCountAsync(user.Id)).Returns(Task.FromResult(IdentityResult.Failed())).Verifiable(); 51 | 52 | var signInManager = new SignInManager(manager.Object, owinContext.Authentication); 53 | 54 | // Act 55 | var result = await signInManager.PasswordSignInAsync(user.Id, "[PLACEHOLDER]-1a", isPersistent: false, shouldLockout: false); 56 | 57 | // Assert 58 | Assert.Equal(SignInStatus.Failure, result); 59 | manager.Verify(); 60 | } 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /test/Identity.Test/TestUtil.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation, Inc. All rights reserved. 2 | // Licensed under the MIT License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using System; 5 | using System.Data.Entity; 6 | using System.Threading.Tasks; 7 | using Microsoft.AspNet.Identity; 8 | using Microsoft.AspNet.Identity.EntityFramework; 9 | using Microsoft.AspNet.Identity.Owin; 10 | using Microsoft.Owin; 11 | using Microsoft.Owin.Security.DataProtection; 12 | 13 | namespace Identity.Test 14 | { 15 | public static class TestUtil 16 | { 17 | public static void SetupDatabase(string dataDirectory) where TDbContext : DbContext 18 | { 19 | AppDomain.CurrentDomain.SetData("DataDirectory", dataDirectory); 20 | Database.SetInitializer(new DropCreateDatabaseAlways()); 21 | } 22 | 23 | public static UserManager CreateManager(DbContext db) 24 | { 25 | var options = new IdentityFactoryOptions> 26 | { 27 | Provider = new TestProvider(db), 28 | DataProtectionProvider = new DpapiDataProtectionProvider() 29 | }; 30 | return options.Provider.Create(options, new OwinContext()); 31 | } 32 | 33 | public static UserManager CreateManager() 34 | { 35 | return CreateManager(UnitTestHelper.CreateDefaultDb()); 36 | } 37 | 38 | public static async Task CreateManager(OwinContext context) 39 | { 40 | var options = new IdentityFactoryOptions> 41 | { 42 | Provider = new TestProvider(UnitTestHelper.CreateDefaultDb()), 43 | DataProtectionProvider = new DpapiDataProtectionProvider() 44 | }; 45 | var middleware = 46 | new IdentityFactoryMiddleware 47 | , IdentityFactoryOptions>>(null, options); 48 | await middleware.Invoke(context); 49 | } 50 | } 51 | 52 | public class TestProvider : IdentityFactoryProvider> 53 | { 54 | public TestProvider(DbContext db) 55 | { 56 | OnCreate = ((options, context) => 57 | { 58 | var manager = 59 | new UserManager(new UserStore(db)); 60 | manager.UserValidator = new UserValidator(manager) 61 | { 62 | AllowOnlyAlphanumericUserNames = true, 63 | RequireUniqueEmail = false 64 | }; 65 | manager.EmailService = new TestMessageService(); 66 | manager.SmsService = new TestMessageService(); 67 | if (options.DataProtectionProvider != null) 68 | { 69 | manager.UserTokenProvider = 70 | new DataProtectorTokenProvider( 71 | options.DataProtectionProvider.Create("ASP.NET Identity")); 72 | } 73 | return manager; 74 | }); 75 | } 76 | } 77 | 78 | public class TestMessageService : IIdentityMessageService 79 | { 80 | public IdentityMessage Message { get; set; } 81 | 82 | public Task SendAsync(IdentityMessage message) 83 | { 84 | Message = message; 85 | return Task.FromResult(0); 86 | } 87 | } 88 | } -------------------------------------------------------------------------------- /test/Identity.Test/UnitTestHelper.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation, Inc. All rights reserved. 2 | // Licensed under the MIT License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using System; 5 | using System.Data.Entity; 6 | using System.Data.Entity.SqlServer; 7 | using System.Globalization; 8 | using System.Linq; 9 | using System.Threading.Tasks; 10 | using Microsoft.AspNet.Identity; 11 | using Microsoft.AspNet.Identity.EntityFramework; 12 | using Xunit; 13 | 14 | namespace Identity.Test 15 | { 16 | public static class UnitTestHelper 17 | { 18 | public static bool EnglishBuildAndOS 19 | { 20 | get 21 | { 22 | var englishBuild = String.Equals(CultureInfo.CurrentUICulture.TwoLetterISOLanguageName, "en", 23 | StringComparison.OrdinalIgnoreCase); 24 | var englishOS = String.Equals(CultureInfo.CurrentCulture.TwoLetterISOLanguageName, "en", 25 | StringComparison.OrdinalIgnoreCase); 26 | return englishBuild && englishOS; 27 | } 28 | } 29 | 30 | public static IdentityDbContext CreateDefaultDb() 31 | { 32 | Database.SetInitializer(new DropCreateDatabaseAlways()); 33 | var db = new IdentityDbContext(); 34 | db.Database.Initialize(true); 35 | var foo = typeof (SqlProviderServices); 36 | return db; 37 | } 38 | 39 | public static void IsSuccess(IdentityResult result) 40 | { 41 | Assert.NotNull(result); 42 | Assert.True(result.Succeeded); 43 | } 44 | 45 | public static void IsFailure(IdentityResult result) 46 | { 47 | Assert.NotNull(result); 48 | Assert.False(result.Succeeded); 49 | } 50 | 51 | public static void IsFailure(IdentityResult result, string error) 52 | { 53 | Assert.NotNull(result); 54 | Assert.False(result.Succeeded); 55 | Assert.Equal(error, result.Errors.First()); 56 | } 57 | } 58 | 59 | public class AlwaysBadValidator : IIdentityValidator 60 | { 61 | public const string ErrorMessage = "I'm Bad."; 62 | 63 | public Task ValidateAsync(T item) 64 | { 65 | return Task.FromResult(IdentityResult.Failed(ErrorMessage)); 66 | } 67 | } 68 | 69 | public class NoopValidator : IIdentityValidator 70 | { 71 | public Task ValidateAsync(T item) 72 | { 73 | return Task.FromResult(IdentityResult.Success); 74 | } 75 | } 76 | } -------------------------------------------------------------------------------- /test/Identity.Test/packages.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /unittest.testsettings: -------------------------------------------------------------------------------- 1 |  2 | 3 | 5 | These are default test settings for a local test run. 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 |
21 |
22 |
23 |
24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | --------------------------------------------------------------------------------