Skip to content
This repository was archived by the owner on Dec 13, 2018. It is now read-only.

[Prototype] Rework events (support DI) #1055

Closed
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@ internal class CookieAuthenticationHandler : AuthenticationHandler<CookieAuthent
private string _sessionKey;
private Task<AuthenticateResult> _readCookieTask;

private CookieAuthenticationEvents Events => Options.Events.ResolveEvents(Context.RequestServices);

private Task<AuthenticateResult> EnsureCookieTicket()
{
// We only need to read the ticket once
Expand Down Expand Up @@ -127,7 +129,7 @@ protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
}

var context = new CookieValidatePrincipalContext(Context, result.Ticket, Options);
await Options.Events.ValidatePrincipal(context);
await Events.ValidatePrincipal(context);

if (context.Principal == null)
{
Expand Down Expand Up @@ -244,7 +246,7 @@ protected override async Task HandleSignInAsync(SignInContext signin)
signInContext.Properties.ExpiresUtc = issuedUtc.Add(Options.ExpireTimeSpan);
}

await Options.Events.SigningIn(signInContext);
await Events.SigningIn(signInContext);

if (signInContext.Properties.IsPersistent)
{
Expand Down Expand Up @@ -282,7 +284,7 @@ protected override async Task HandleSignInAsync(SignInContext signin)
signInContext.Principal,
signInContext.Properties);

await Options.Events.SignedIn(signedInContext);
await Events.SignedIn(signedInContext);

// Only redirect on the login path
var shouldRedirect = Options.LoginPath.HasValue && OriginalPath == Options.LoginPath;
Expand All @@ -305,7 +307,7 @@ protected override async Task HandleSignOutAsync(SignOutContext signOutContext)
new AuthenticationProperties(signOutContext.Properties),
cookieOptions);

await Options.Events.SigningOut(context);
await Events.SigningOut(context);

Options.CookieManager.DeleteCookie(
Context,
Expand Down Expand Up @@ -343,7 +345,7 @@ private async Task ApplyHeaders(bool shouldRedirectToReturnUrl, AuthenticationPr

if (redirectUri != null)
{
await Options.Events.RedirectToReturnUrl(
await Events.RedirectToReturnUrl(
new CookieRedirectContext(Context, Options, redirectUri, properties));
}
}
Expand Down Expand Up @@ -372,7 +374,7 @@ protected override async Task<bool> HandleForbiddenAsync(ChallengeContext contex
}
var accessDeniedUri = Options.AccessDeniedPath + QueryString.Create(Options.ReturnUrlParameter, returnUrl);
var redirectContext = new CookieRedirectContext(Context, Options, BuildRedirectUri(accessDeniedUri), properties);
await Options.Events.RedirectToAccessDenied(redirectContext);
await Events.RedirectToAccessDenied(redirectContext);
return true;
}

Expand All @@ -392,7 +394,7 @@ protected override async Task<bool> HandleUnauthorizedAsync(ChallengeContext con

var loginUri = Options.LoginPath + QueryString.Create(Options.ReturnUrlParameter, redirectUri);
var redirectContext = new CookieRedirectContext(Context, Options, BuildRedirectUri(loginUri), properties);
await Options.Events.RedirectToLogin(redirectContext);
await Events.RedirectToLogin(redirectContext);
return true;

}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,8 @@ public CookieAuthenticationMiddleware(
IDataProtectionProvider dataProtectionProvider,
ILoggerFactory loggerFactory,
UrlEncoder urlEncoder,
IOptions<CookieAuthenticationOptions> options)
IOptions<CookieAuthenticationOptions> options,
IServiceProvider services)
: base(next, options, loggerFactory, urlEncoder)
{
if (dataProtectionProvider == null)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,10 @@ public string CookieName
/// calls methods on the provider which give the application control at certain points where processing is occurring.
/// If it is not provided a default instance is supplied which does nothing when the methods are called.
/// </summary>
public ICookieAuthenticationEvents Events { get; set; }
public new CookieAuthenticationEvents Events {
get { return (CookieAuthenticationEvents)base.Events; }
set { base.Events = value; }
}

/// <summary>
/// The TicketDataFormat is used to protect and unprotect the identity and other properties which are stored in the
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,11 @@
namespace Microsoft.AspNetCore.Authentication.Cookies
{
/// <summary>
/// This default implementation of the ICookieAuthenticationEvents may be used if the
/// This default implementation of the CookieAuthenticationEvents may be used if the
/// application only needs to override a few of the interface methods. This may be used as a base class
/// or may be instantiated directly.
/// </summary>
public class CookieAuthenticationEvents : ICookieAuthenticationEvents
public class CookieAuthenticationEvents : AuthenticationEvents
{
/// <summary>
/// A delegate assigned to this property will be invoked when the related method is called.
Expand Down Expand Up @@ -155,5 +155,11 @@ private static bool IsAjaxRequest(HttpRequest request)
/// </summary>
/// <param name="context">Contains information about the event</param>
public virtual Task RedirectToAccessDenied(CookieRedirectContext context) => OnRedirectToAccessDenied(context);

public new CookieAuthenticationEvents ResolveEvents(IServiceProvider services)
{
return base.ResolveEvents(services) as CookieAuthenticationEvents;
}

}
}

This file was deleted.

Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.

using System;
using System.Globalization;
using System.Net.Http;
using System.Security.Claims;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,14 +27,16 @@ public class FacebookMiddleware : OAuthMiddleware<FacebookOptions>
/// <param name="encoder"></param>
/// <param name="sharedOptions"></param>
/// <param name="options">Configuration options for the middleware.</param>
/// <param name="services"></param>
public FacebookMiddleware(
RequestDelegate next,
IDataProtectionProvider dataProtectionProvider,
ILoggerFactory loggerFactory,
UrlEncoder encoder,
IOptions<SharedAuthenticationOptions> sharedOptions,
IOptions<FacebookOptions> options)
: base(next, dataProtectionProvider, loggerFactory, encoder, sharedOptions, options)
IOptions<FacebookOptions> options,
IServiceProvider services)
: base(next, dataProtectionProvider, loggerFactory, encoder, sharedOptions, options, services)
{
if (next == null)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,14 +26,16 @@ public class GoogleMiddleware : OAuthMiddleware<GoogleOptions>
/// <param name="encoder"></param>
/// <param name="sharedOptions"></param>
/// <param name="options">Configuration options for the middleware.</param>
/// <param name="services"></param>
public GoogleMiddleware(
RequestDelegate next,
IDataProtectionProvider dataProtectionProvider,
ILoggerFactory loggerFactory,
UrlEncoder encoder,
IOptions<SharedAuthenticationOptions> sharedOptions,
IOptions<GoogleOptions> options)
: base(next, dataProtectionProvider, loggerFactory, encoder, sharedOptions, options)
IOptions<GoogleOptions> options,
IServiceProvider services)
: base(next, dataProtectionProvider, loggerFactory, encoder, sharedOptions, options, services)
{
if (next == null)
{
Expand Down

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ namespace Microsoft.AspNetCore.Authentication.JwtBearer
/// <summary>
/// Specifies events which the <see cref="JwtBearerMiddleware"/> invokes to enable developer control over the authentication process.
/// </summary>
public class JwtBearerEvents : IJwtBearerEvents
public class JwtBearerEvents : AuthenticationEvents
{
/// <summary>
/// Invoked if exceptions are thrown during request processing. The exceptions will be re-thrown after this event unless suppressed.
Expand Down Expand Up @@ -39,5 +39,10 @@ public class JwtBearerEvents : IJwtBearerEvents
public virtual Task TokenValidated(TokenValidatedContext context) => OnTokenValidated(context);

public virtual Task Challenge(JwtBearerChallengeContext context) => OnChallenge(context);

public new JwtBearerEvents ResolveEvents(IServiceProvider services)
{
return base.ResolveEvents(services) as JwtBearerEvents;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@ internal class JwtBearerHandler : AuthenticationHandler<JwtBearerOptions>
{
private OpenIdConnectConfiguration _configuration;

private JwtBearerEvents Events => Options.Events.ResolveEvents(Context.RequestServices);

/// <summary>
/// Searches the 'Authorization' header for a 'Bearer' token. If the 'Bearer' token is found, it is validated using <see cref="TokenValidationParameters"/> set in the options.
/// </summary>
Expand All @@ -36,7 +38,7 @@ protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
var messageReceivedContext = new MessageReceivedContext(Context, Options);

// event can set the token
await Options.Events.MessageReceived(messageReceivedContext);
await Events.MessageReceived(messageReceivedContext);
if (messageReceivedContext.CheckEventResult(out result))
{
return result;
Expand Down Expand Up @@ -127,7 +129,7 @@ protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
SecurityToken = validatedToken,
};

await Options.Events.TokenValidated(tokenValidatedContext);
await Events.TokenValidated(tokenValidatedContext);
if (tokenValidatedContext.CheckEventResult(out result))
{
return result;
Expand All @@ -153,7 +155,7 @@ protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
Exception = (validationFailures.Count == 1) ? validationFailures[0] : new AggregateException(validationFailures)
};

await Options.Events.AuthenticationFailed(authenticationFailedContext);
await Events.AuthenticationFailed(authenticationFailedContext);
if (authenticationFailedContext.CheckEventResult(out result))
{
return result;
Expand All @@ -173,7 +175,7 @@ protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
Exception = ex
};

await Options.Events.AuthenticationFailed(authenticationFailedContext);
await Events.AuthenticationFailed(authenticationFailedContext);
if (authenticationFailedContext.CheckEventResult(out result))
{
return result;
Expand All @@ -199,7 +201,7 @@ protected override async Task<bool> HandleUnauthorizedAsync(ChallengeContext con
eventContext.ErrorDescription = CreateErrorDescription(eventContext.AuthenticateFailure);
}

await Options.Events.Challenge(eventContext);
await Events.Challenge(eventContext);
if (eventContext.HandledResponse)
{
return true;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,8 @@

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IdentityModel.Tokens.Jwt;
using System.Net.Http;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Protocols;
using Microsoft.IdentityModel.Protocols.OpenIdConnect;
Expand Down Expand Up @@ -63,7 +61,11 @@ public JwtBearerOptions() : base()
/// The application may implement the interface fully, or it may create an instance of JwtBearerAuthenticationEvents
/// and assign delegates only to the events it wants to process.
/// </summary>
public IJwtBearerEvents Events { get; set; } = new JwtBearerEvents();
public new JwtBearerEvents Events
{
get { return (JwtBearerEvents)base.Events; }
set { base.Events = value; }
}

/// <summary>
/// The HttpMessageHandler used to retrieve metadata.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,14 +26,16 @@ public class MicrosoftAccountMiddleware : OAuthMiddleware<MicrosoftAccountOption
/// <param name="encoder"></param>
/// <param name="sharedOptions"></param>
/// <param name="options">Configuration options for the middleware.</param>
/// <param name="services"></param>
public MicrosoftAccountMiddleware(
RequestDelegate next,
IDataProtectionProvider dataProtectionProvider,
ILoggerFactory loggerFactory,
UrlEncoder encoder,
IOptions<SharedAuthenticationOptions> sharedOptions,
IOptions<MicrosoftAccountOptions> options)
: base(next, dataProtectionProvider, loggerFactory, encoder, sharedOptions, options)
IOptions<MicrosoftAccountOptions> options,
IServiceProvider services)
: base(next, dataProtectionProvider, loggerFactory, encoder, sharedOptions, options, services)
{
if (next == null)
{
Expand Down
Loading