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

Authentication and authorization in Asp.Net Core

Hugo Biarge
April 27, 2019
200

Authentication and authorization in Asp.Net Core

Hugo Biarge

April 27, 2019
Tweet

Transcript

  1. Agenda • Authentication • Schemes, handlers and Options • Authentication

    patterns • Authorization • Policies, requirements and handlers • Testing • Extensibility https://github.com/hbiarge/authentication-samples https://github.com/hbiarge/Authorization-Workshop
  2. Authentication vs Authorization Authentication Identify authentication information in the request,

    use the configured methods to read it and create an instance of ClaimsPrincipal with the ClaimsIdentity and Claims of the requester Authorization Based on the requester Claims, the resource state, and potentially other information, allow or disallow action execution or filter resource information
  3. Authentication in IIS and OWIN • IIS (MVC 5) •

    Authentication modules (FormsAuthentication Module) • Authentication integrated in the IIS processing lifetime • OWIN • Authentication middlewares • Active|passive mode
  4. Authentication in Asp.Net Core • Asp.Net Core 1.x • Based

    on authentication middlewares like OWIN • AutomaticAuthenticate and AutomaticChallenge • Asp.Net Core 2.x • Big change in how authentication is handled • One unique middleware that uses an IAuthenticationService • AuthenticationHandlers as services • IAuthenticationSchemesProvider and IAuthenticationHandlerProvider
  5. Configuration • Add authentication services to the DI container •

    Configure default schemes • Add as many authentication handlers as you need • Use the authentication middleware
  6. Schemes, handlers and options • You register a Scheme that

    uses an AuthenticationHandler with its AuthenticatinSchemeOptions • Scheme names MUST be unique • Different Schemes can use the same AuthenticationHandler type
  7. Authenticate, Challenge and Forbid • Authenticate • Executed in every

    request • Try to get authentication information from the request and create the AuthenticationTicket • Challenge • What to do when no authentication information can be found in the request • Forbid • What to do when authentication is found but authorization is not satisfied
  8. SignIn and SignOut • SignIn • When a handler knows

    how to store authentication information for future use • For example, CookiesAuthenticationHandler stores the authentication information in a cookie • SignOut • When a handler knows how to remove the stored authentication information • For example, CookiesAuthenticationHandler removes the authentication cookie
  9. Local vs Remote authentication handlers • Local • Don´t use

    external resources to perform authentication • For example CookiesAuthenticationHandler or JwtBearerHandler • Remote • These handlers interact with external resources to perform authentication flows • They need to handle request to special endpoints to complete those authentication flows • Delegates SigIn to another configured local authentication handler • For example the OpenIdConnectHandler interacts with an external OpenId Provider to perform the authentication flow
  10. Authentication events • Used as an extensibility point to customize

    an AuthenticationHandler behavior • Deeply integrated with the actions the handler manages • Can be integrated with the DI container https://github.com/hbiarge/Acheve.Authentication.Events
  11. Authentication patterns • Mvc app with local users • Cookies

    • Mvc app integrated with Directory • Cookies + OpenIdConnect • Http API • JwtBearer
  12. Once upon a time… • [Authorize] and [AllowAnonymous] are used

    in WebApi and MVC in the .Net Framework • They are the only “out of the box” resort to manage authorization • Supports Users and Roles • Implemented as an Authorization Filter • Executed early in the request lifecycle
  13. But… it´s the same in .Net Core, right? • [Authorize]

    and [AllowAnonymous] also exist in .Net Core • It makes it easy to learn and use because the behavior is the same • The underlying infrastructure is completely new • Managed as an Authorization Filter in the ResourceInvoker class in an early stage of the request lifecycle • Starting Asp.Net Core 3.0, can be managed as middleware! • Supports only Roles (for compatibility reasons) and Policies
  14. ClaimsPrincipal and ClaimsIdentity • ClaimsPrincipal aggregates one or many ClaimsIdentity.

    A request can use more than one scheme to be authenticated • Each ClaimsIdentity includes the set of Claims for an authentication scheme • A Claim defines: • Type: the name (can be duplicates) • Value: the value • Issuer: who has generated the claim?
  15. What´s a Policy? • Composed by one or more Requirements

    • A Requirement is managed by one or more Handlers • A Policy will be satisficed (authorized) if ALL its Requirements are satisficed • A Requirement will be satisficed if at least one of its Handlers satisfy it • By default, all the Handlers registered for a Requirement are evaluated, although some fail
  16. Simple policies // In Startup ConfigureServices services.AddAuthorization(options => { options.AddPolicy("RequireAdministration",

    policy => { policy.RequireRole("Administration"); policy.RequireClaim("Management"); policy.RequireClaim("OneOfMany", "a", "b"); }); });
  17. Policies as code public class MinimumAgeRequirement : AuthorizationHandler<MinimumAgeRequirement>, IAuthorizationRequirement {

    protected override void Handle( AuthorizationContext context, MinimumAgeRequirement requirement) { // Logic to validate requirement context.Succeed(requirement); } } // In Startup ConfigureServices options.AddPolicy("Over18Only", policy => { policy.Requirements.Add(new MinimumAgeRequirement(18)); });
  18. Requirements and Handlers • IAuthorizationRequirement • Can give context (state)

    for the authorization process • AuthorizationHandler<IAuthorizationRequirement> • AuthorizationHandler<IAuthorizationRequirement, Resource> • Implements the authorization logic receiving: • Authorization context • Requirement • The resource (optional)
  19. Managing the Authorization logic in Handlers • If the request

    should be authorized by the Handler • context.Succeed(requirement) • If the request should not be authorized by the Handler • Do nothing!! • There can be other Handlers registered for the same Requirement • Only in extreme scenarios • context.Fail()
  20. Handlers and DI • All the Handlers should be registered

    in the DI container • Singleton works for handlers without dependencies • Handlers with dependencies should honor the lifetime of it´s dependencies • ValidateScopes = true is your friend
  21. Resource based Authorization • AuthorizationHandler<Requirement, Resource> • In the Handle

    method we have access to the resource in a typed way public class ProductAuthorizationHandler : AuthorizationHandler<OperationAuthorizationRequirement, Product> { protected override void Handle( AuthorizationContext context, OperationAuthorizationRequirement requirement, Product resource) { // Logic to validate requirement } }
  22. Imperative Authorization IAuthorizationService in Controllers or Views public async Task<IActionResult>

    Index() { if (await _authorizationService.AuthorizeAsync(User, Policies.Over21)) { // User is authorized here. } else { return new ChallengeResult(); } }
  23. Extensibility • You can implement your own IAuthorizationPolicyProvider • Create

    policies dynamically • Use an external authorization service (https://policyserver.io/) • … • Only one per application • Fallback mechanism • Cache
  24. Use more than one authentication scheme • We can define

    authentication schemes in Policies or in the [Authorize] attribute • Adds to the ClaimsPrincipal an instance of ClaimsIdentity per scheme • The ClaimsPrincipal expose all the aggregated claims of all the ClaimsIdentity included • Overrides the default authentication scheme
  25. But I´m still working with Asp.Net… • There is a

    backport that can be used in MVC and WebApi with Asp.Net 4 • https://github.com/DavidParks8/Owin-Authorization
  26. www.plainconcepts.com MADRID Paseo de la Castellana 163, 10º 28046 Madrid

    T. (+34) 91 5346 836 BILBAO Ledesma 10-bis, Planta 3 dpto 2 48001 Bilbao T. (+34) 94 6073 371 BARCELONA Av. Josep Tarradellas 10, 6º 1ª 08029 Barcelona T. (+34) 93 3607 114 SEVILLA Avenida de la innovación s/n Edificio Renta Sevilla, 3º A 41020 Sevilla DUBAI Dubai Internet City. Building 1 73030 Dubai. EAU T. (+971) 4 551 6653 LONDON Impact Hub Kings Cross 24B York Way, N1 9AB London. UK SEATTLE 1511, Third Ave Seattle WA 98101. USA T. (+1) 206 708 1285