-
Notifications
You must be signed in to change notification settings - Fork 68
Add owin cookie auth-based signin/signout endpoints to ASP.NET app #4
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 1 commit
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
87ff50a
Add owin cookie auth-based signin/signout endpoints to ASP.NET app
mjrousos c3de202
Merge remote-tracking branch 'origin/main' into mikerou/aspnet-auth
mjrousos 627e5b0
Remove explicit xunit references
mjrousos 135d510
Upgrade Microsoft.Owin.Security* versions to 4.2.1
mjrousos File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,2 @@ | ||
| Placeholder file to make sure the App_Data folder exists (so that | ||
| a SQL mdf file can be created there when running locally). |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,108 @@ | ||
| using System; | ||
| using System.Collections.Generic; | ||
| using System.Linq; | ||
| using System.Security.Claims; | ||
| using System.Threading.Tasks; | ||
| using System.Web; | ||
| using Microsoft.AspNet.Identity; | ||
| using Microsoft.AspNet.Identity.EntityFramework; | ||
| using Microsoft.AspNet.Identity.Owin; | ||
| using Microsoft.Owin; | ||
| using Microsoft.Owin.Security; | ||
| using MvcApp.Models; | ||
|
|
||
| namespace MvcApp | ||
| { | ||
| public class EmailService : IIdentityMessageService | ||
| { | ||
| public Task SendAsync(IdentityMessage message) | ||
| { | ||
| // Plug in your email service here to send an email. | ||
| return Task.FromResult(0); | ||
| } | ||
| } | ||
|
|
||
| public class SmsService : IIdentityMessageService | ||
| { | ||
| public Task SendAsync(IdentityMessage message) | ||
| { | ||
| // Plug in your SMS service here to send a text message. | ||
| return Task.FromResult(0); | ||
| } | ||
| } | ||
|
|
||
| // Configure the application user manager used in this application. UserManager is defined in ASP.NET Identity and is used by the application. | ||
| public class ApplicationUserManager : UserManager<ApplicationUser> | ||
| { | ||
| public ApplicationUserManager(IUserStore<ApplicationUser> store) | ||
| : base(store) | ||
| { | ||
| } | ||
|
|
||
| public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options, IOwinContext context) | ||
| { | ||
| var manager = new ApplicationUserManager(new UserStore<ApplicationUser>(context.Get<ApplicationDbContext>())); | ||
| // Configure validation logic for usernames | ||
| manager.UserValidator = new UserValidator<ApplicationUser>(manager) | ||
| { | ||
| AllowOnlyAlphanumericUserNames = false, | ||
| RequireUniqueEmail = true | ||
| }; | ||
|
|
||
| // Configure validation logic for passwords | ||
| manager.PasswordValidator = new PasswordValidator | ||
| { | ||
| RequiredLength = 6, | ||
| RequireNonLetterOrDigit = true, | ||
| RequireDigit = true, | ||
| RequireLowercase = true, | ||
| RequireUppercase = true, | ||
| }; | ||
|
|
||
| // Configure user lockout defaults | ||
| manager.UserLockoutEnabledByDefault = true; | ||
| manager.DefaultAccountLockoutTimeSpan = TimeSpan.FromMinutes(5); | ||
| manager.MaxFailedAccessAttemptsBeforeLockout = 5; | ||
|
|
||
| // Register two factor authentication providers. This application uses Phone and Emails as a step of receiving a code for verifying the user | ||
| // You can write your own provider and plug it in here. | ||
| manager.RegisterTwoFactorProvider("Phone Code", new PhoneNumberTokenProvider<ApplicationUser> | ||
| { | ||
| MessageFormat = "Your security code is {0}" | ||
| }); | ||
| manager.RegisterTwoFactorProvider("Email Code", new EmailTokenProvider<ApplicationUser> | ||
| { | ||
| Subject = "Security Code", | ||
| BodyFormat = "Your security code is {0}" | ||
| }); | ||
| manager.EmailService = new EmailService(); | ||
| manager.SmsService = new SmsService(); | ||
| var dataProtectionProvider = options.DataProtectionProvider; | ||
| if (dataProtectionProvider != null) | ||
| { | ||
| manager.UserTokenProvider = | ||
| new DataProtectorTokenProvider<ApplicationUser>(dataProtectionProvider.Create("ASP.NET Identity")); | ||
| } | ||
| return manager; | ||
| } | ||
| } | ||
|
|
||
| // Configure the application sign-in manager which is used in this application. | ||
| public class ApplicationSignInManager : SignInManager<ApplicationUser, string> | ||
| { | ||
| public ApplicationSignInManager(ApplicationUserManager userManager, IAuthenticationManager authenticationManager) | ||
| : base(userManager, authenticationManager) | ||
| { | ||
| } | ||
|
|
||
| public override Task<ClaimsIdentity> CreateUserIdentityAsync(ApplicationUser user) | ||
| { | ||
| return user.GenerateUserIdentityAsync((ApplicationUserManager)UserManager); | ||
| } | ||
|
|
||
| public static ApplicationSignInManager Create(IdentityFactoryOptions<ApplicationSignInManager> options, IOwinContext context) | ||
| { | ||
| return new ApplicationSignInManager(context.GetUserManager<ApplicationUserManager>(), context.Authentication); | ||
| } | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,67 @@ | ||
| using System; | ||
| using Microsoft.AspNet.Identity; | ||
| using Microsoft.AspNet.Identity.Owin; | ||
| using Microsoft.Owin; | ||
| using Microsoft.Owin.Security.Cookies; | ||
| using MvcApp.Models; | ||
| using Owin; | ||
|
|
||
| namespace MvcApp | ||
| { | ||
| public partial class Startup | ||
| { | ||
| // For more information on configuring authentication, please visit https://go.microsoft.com/fwlink/?LinkId=301864 | ||
| public void ConfigureAuth(IAppBuilder app) | ||
| { | ||
| // Configure the db context, user manager and signin manager to use a single instance per request | ||
| app.CreatePerOwinContext(ApplicationDbContext.Create); | ||
| app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create); | ||
| app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create); | ||
|
|
||
| // Enable the application to use a cookie to store information for the signed in user | ||
| // and to use a cookie to temporarily store information about a user logging in with a third party login provider | ||
| // Configure the sign in cookie | ||
| app.UseCookieAuthentication(new CookieAuthenticationOptions | ||
| { | ||
| AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie, | ||
| LoginPath = new PathString("/Account/Login"), | ||
| Provider = new CookieAuthenticationProvider | ||
| { | ||
| // Enables the application to validate the security stamp when the user logs in. | ||
| // This is a security feature which is used when you change a password or add an external login to your account. | ||
| OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>( | ||
| validateInterval: TimeSpan.FromMinutes(30), | ||
| regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager)) | ||
| } | ||
| }); | ||
| app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie); | ||
|
|
||
| // Enables the application to temporarily store user information when they are verifying the second factor in the two-factor authentication process. | ||
| app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5)); | ||
|
|
||
| // Enables the application to remember the second login verification factor such as phone or email. | ||
| // Once you check this option, your second step of verification during the login process will be remembered on the device where you logged in from. | ||
| // This is similar to the RememberMe option when you log in. | ||
| app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie); | ||
|
|
||
| // Uncomment the following lines to enable logging in with third party login providers | ||
| //app.UseMicrosoftAccountAuthentication( | ||
| // clientId: "", | ||
| // clientSecret: ""); | ||
|
|
||
| //app.UseTwitterAuthentication( | ||
| // consumerKey: "", | ||
| // consumerSecret: ""); | ||
|
|
||
| //app.UseFacebookAuthentication( | ||
| // appId: "", | ||
| // appSecret: ""); | ||
|
|
||
| //app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions() | ||
| //{ | ||
| // ClientId = "", | ||
| // ClientSecret = "" | ||
| //}); | ||
| } | ||
| } | ||
| } | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
We're going to need different samples apps for each auth scenario, none of the different auth types are compatible.
The ones we wanted to start with were JWT and OpenIdConnect. Microsoft.AspNet.Identity is one of the harder scenarios to do interop for since there's a user database to deal with.
The owin cookie interop package would be used with both OpenIdConnect and Identity.
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Yea, we'll definitely need multiple samples here soon. I've updated this with identity for now because that's the scenario that I think would be most beneficial to learn about first.
I'm expecting JWT will be pretty trivial. On the other hand, it seems like Identity should be doable with the owin cookie interop package but there are still a lot of unknowns in that scenario (for me at least), so I'd like to play around with it first.