Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Secure your apps with ASP.NET Identity

Secure your apps with ASP.NET Identity

ASP.NET 4.5.1 heeft een complete vernieuwd security model. Het maakt gebruik van claims-based security en Entity Framework 6. In deze sessie leer je hoe je ASP.NET identity gebruikt om authenticatie en autorisatie in je web applicaties te implementeren.

Avatar for Alex Thissen

Alex Thissen

April 29, 2014
Tweet

More Decks by Alex Thissen

Other Decks in Programming

Transcript

  1. Laat ons weten wat u vindt van deze sessie! Vul

    de evaluatie in via www.techdaysapp.nl en maak kans op een van de 20 prijzen*. Prijswinnaars worden bekend gemaakt via Twitter (#TechDaysNL). Gebruik hiervoor de code op uw badge. Let us know how you feel about this session! Give your feedback via www.techdaysapp.nl and possibly win one of the 20 prizes*. Winners will be announced via Twitter (#TechDaysNL). Use your personal code on your badge. * Over de uitslag kan niet worden gecorrespondeerd, prijzen zijn voorbeelden – All results are final, prizes are examples
  2. A brief history of identity and membership in ASP.NET ASP.NET

    1.0 • Windows • FBA • Passport ASP.NET 2.0 • Membership • Roles • Profile • Provider model Universal Providers • New providers • All SQL Server versions Web Matrix • Simple membership Windows Identity Foundation 1.0 & 4.5 • Claims-based • Federation Evolution of ASP.NET security ASP.NET Identity •Claims-based •Social logins •Flexible storage
  3. One ASP.NET identity system • Claims based membership system built

    on OWIN • Variety of identity providers • Windows Azure Active Directory • Social logins • Combines profile data • Control over persistence • Replace identity store with your own storage • Unit testing Just like One ASP.NET itself
  4. Out-of-the box functionality V1 project template Register Login Change password

    Social logins Associate account with social login V2 features Account activation Password reset and complexity Two factor authentication Account management Control over primary key for users and roles Security Token Provider (support for regenerating security token) IQueryable support
  5. Authentication types Individual users • ASP.NET Identity • “Internal” accounts

    • Uses OWIN Organizational accounts • Active Directory • Azure Active Directory • “External” accounts • Uses WIF Choose wisely
  6. Configuring ASP.NET identity Three NuGet packages • Microsoft.AspNet.Identity.Core • Microsoft.AspNet.Identity.Owin

    • Microsoft.AspNet.Identity.EntityFramework Getting started from scratch public void Configure(IAppBuilder app) { app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie, LoginPath = new PathString("/Account/Login") }); app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie); app.UseGoogleAuthentication(); // …
  7. Architecture of ASP.NET Identity UserManager, RoleManager AuthenticationManager (from OWIN) UserStore,

    RoleStore (Entity Framework) SQL Server, RavenDB, Azure Table Storage
  8. Assemblies of ASP.NET Identity Things to note: • No dependency

    on System.Web • Lots of OWIN • Loose coupling to EF
  9. Authentication providers 1. Application 2. External identity providers • Google

    • Facebook • Twitter • Microsoft account (previously Windows Live ID) • Azure Active Directory 3. Token based • Bearer tokens from OAuth2 provider Each provider is identified by its AuthenticationType Local, social or generic OAuth
  10. Retrieving users UserManager is entry point to accounts Finding accounts

    Managing accounts Example of ASP.NET Identity API // Anonymous, from Username and Password input ApplicationUser user = manager.Find(UserName.Text, Password.Text); // Authenticated, by ClaimTypes.NameIdentifier claim ApplicationUser user = manager.FindById(User.Identity.GetUserId()); var user = new ApplicationUser() { UserName = UserName.Text }; IdentityResult result = manager.Create(user, Password.Text); IdentityResult result = manager.ChangePassword(User.Identity.GetUserId(), CurrentPassword.Text, NewPassword.Text); UserManager manager = new UserManager();
  11. OWIN •Standard interface of .NET web servers and applications •

    Minimal requirements in specification •Family of pluggable web components • Inject cross-cutting concerns •Microsoft’s additional goals • Drop dependency on System.Web • Develop out of band with .NET FX Open Web Interface for .NET
  12. OWIN and Katana middleware Middleware stack • Static files •

    Security, authentication, CORS • Diagnostics, logging • Other cross-cutting concerns Host process and server Application and framework
  13. Cookies Mostly for storing temporary state A whole new set

    of cookies Authentication type Cookie name Description Application .AspNet.ApplicationCookie Storage of local login External login .AspNet.ExternalCookie Temporary storage of external login information Two factor authentication .AspNet.TwoFactorRememberBrowser Remember browser used 2FA before .AspNet.TwoFactorCookie Storage of two factor authenticated login External bearer .AspNet.ExternalBearer Temporary storage of external bearer token from OAuth authorization server Remember these? Forms based authentication: .ASPXAUTH Windows Identity Foundation: FedAuth
  14. External logins OAuth • Twitter (v1) • Facebook (customized) •

    Microsoft Account Open ID • Google WS-Federation • Azure Active Directory Mostly passive middleware Combining social identities
  15. Claims •Add custom claims to your ClaimsPrincipal •Three options •

    Upon creation of account • Afterwards • During login for temporary claims •Claims get stored in application cookie Putting more claims in your identity user.Claims.Add(new IdentityUserClaim() { ClaimType = ClaimTypes.DateOfBirth, ClaimValue = DateTime.Now.ToShortDateString() } ); IAuthenticationManager authenticationManager = HttpContext.Current.GetOwinContext().Authentication; ClaimsIdentity identity = manager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie); authenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent }, identity);
  16. Control over persistence • Uses Entity Framework 6 by default

    • Code first approach • Migrations to update your database Choose whatever store you like User and role store implementations RavenDB CouchDB MongoDB Azure Table Storage NHibernate Elastic Search Redis
  17. Roles •Helps support Role Based Security scenarios •RoleManager similar to

    UserManager • Focuses on roles management • Simpler in use: lacks login related functionality •UserStore to administer user-role relationship Role-playing with your identity
  18. Multi-factor authentication •Two built-in authentication providers • EmailTokenProvider • SmsTokenProvider

    •Create your own send service Stronger authentication when necessary public class SmsService : IIdentityMessageService { public Task SendAsync(IdentityMessage message) { // Plug in your sms service here to send a text message. return Task.FromResult(0); } } var manager = new ApplicationUserManager(…); manager.SmsService = new SmsService();
  19. Extending ASP.NET Identity •Entity Framework 6.1 Code First and Migrations

    •Two strategies public class ApplicationUser : IdentityUser { // Add additional properties and run migrations public DateTime BirthDate { get; set; } }
  20. Web API and Identity •Web API uses ASP.NET Identity slightly

    different •Three registered middleware components • OAuth Authorization server • Bearer token-based authentication (for local accounts) • External bearer token-based authentication (for external accounts) More proof of One ASP.NET config.SuppressDefaultHostAuthentication(); config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType)); // Enable the application to use bearer tokens to authenticate users app.UseOAuthBearerTokens(OAuthOptions);
  21. Migrate membership to ASP.NET Identity •Install NuGet packages • Microsoft.AspNet.Identity.Owin

    • Microsoft.Owin.Host.SystemWeb • Optionally OAuth social login providers Microsoft.Owin.Security.<Provider> •Generate and execute SQL script for database migration •Extend IdentityUser class •Create account management pages • http://www.asp.net/identity/overview/getting-started/adding-aspnet-identity-to-an-empty-or-existing-web-forms-project Going from classic to modern ASP.NET
  22. Summary •ASP.NET Identity provides functionality for login and account management

    •Modern and extensible system • Claims-based • Social logins • Storage flexibility •Implementation as OWIN authentication middleware •V1 and V2 available now Key takeaways for ASP.NET Identity
  23. Laat ons weten wat u vindt van deze sessie! Vul

    de evaluatie in via www.techdaysapp.nl en maak kans op een van de 20 prijzen*. Prijswinnaars worden bekend gemaakt via Twitter (#TechDaysNL). Gebruik hiervoor de code op uw badge. Let us know how you feel about this session! Give your feedback via www.techdaysapp.nl and possibly win one of the 20 prizes*. Winners will be announced via Twitter (#TechDaysNL). Use your personal code on your badge. * Over de uitslag kan niet worden gecorrespondeerd, prijzen zijn voorbeelden – All results are final, prizes are examples