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

Commit ff9f145

Browse files
committed
Refactor Events + Add IAuthenticationBuilder
1 parent e1cd8c9 commit ff9f145

File tree

95 files changed

+1712
-1459
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

95 files changed

+1712
-1459
lines changed

samples/CookieSample/Startup.cs

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -18,9 +18,7 @@ public void ConfigureServices(IServiceCollection services)
1818
{
1919
options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
2020
options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
21-
});
22-
23-
services.AddCookieAuthentication();
21+
}).AddCookie();
2422
}
2523

2624
public void Configure(IApplicationBuilder app)

samples/CookieSessionSample/Startup.cs

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -19,9 +19,7 @@ public void ConfigureServices(IServiceCollection services)
1919
{
2020
options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
2121
options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
22-
});
23-
24-
services.AddCookieAuthentication(o => o.SessionStore = new MemoryCacheTicketStore());
22+
}).AddCookie(o => o.SessionStore = new MemoryCacheTicketStore());
2523
}
2624

2725
public void Configure(IApplicationBuilder app)

samples/JwtBearerSample/Startup.cs

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -48,9 +48,7 @@ public void ConfigureServices(IServiceCollection services)
4848
{
4949
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
5050
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
51-
});
52-
53-
services.AddJwtBearerAuthentication(o =>
51+
}).AddJwtBearer(o =>
5452
{
5553
// You also need to update /wwwroot/app/scripts/app.js
5654
o.Authority = Configuration["jwt:authority"];
@@ -59,7 +57,7 @@ public void ConfigureServices(IServiceCollection services)
5957
{
6058
OnAuthenticationFailed = c =>
6159
{
62-
c.HandleResponse();
60+
c.NoResult();
6361

6462
c.Response.StatusCode = 500;
6563
c.Response.ContentType = "text/plain";

samples/OpenIdConnect.AzureAdSample/Startup.cs

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -48,11 +48,9 @@ public void ConfigureServices(IServiceCollection services)
4848
sharedOptions.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
4949
sharedOptions.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
5050
sharedOptions.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
51-
});
52-
53-
services.AddCookieAuthentication();
54-
55-
services.AddOpenIdConnectAuthentication(o =>
51+
})
52+
.AddCookie()
53+
.AddOpenIdConnect(o =>
5654
{
5755
o.ClientId = ClientId;
5856
o.ClientSecret = ClientSecret; // for code flow

samples/OpenIdConnectSample/Startup.cs

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -45,11 +45,9 @@ public void ConfigureServices(IServiceCollection services)
4545
sharedOptions.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
4646
sharedOptions.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
4747
sharedOptions.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
48-
});
49-
50-
services.AddCookieAuthentication();
51-
52-
services.AddOpenIdConnectAuthentication(o =>
48+
})
49+
.AddCookie()
50+
.AddOpenIdConnect(o =>
5351
{
5452
o.ClientId = Configuration["oidc:clientid"];
5553
o.ClientSecret = Configuration["oidc:clientsecret"]; // for code flow

samples/SocialSample/Startup.cs

Lines changed: 37 additions & 46 deletions
Original file line numberDiff line numberDiff line change
@@ -55,25 +55,22 @@ public void ConfigureServices(IServiceCollection services)
5555
options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
5656
options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
5757
options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
58-
});
59-
60-
services.AddCookieAuthentication(o => o.LoginPath = new PathString("/login"));
61-
62-
// You must first create an app with Facebook and add its ID and Secret to your user-secrets.
63-
// https://developers.facebook.com/apps/
64-
services.AddFacebookAuthentication(o =>
58+
})
59+
.AddCookie(o => o.LoginPath = new PathString("/login"))
60+
// You must first create an app with Facebook and add its ID and Secret to your user-secrets.
61+
// https://developers.facebook.com/apps/
62+
.AddFacebook(o =>
6563
{
6664
o.AppId = Configuration["facebook:appid"];
6765
o.AppSecret = Configuration["facebook:appsecret"];
6866
o.Scope.Add("email");
6967
o.Fields.Add("name");
7068
o.Fields.Add("email");
7169
o.SaveTokens = true;
72-
});
73-
74-
// You must first create an app with Google and add its ID and Secret to your user-secrets.
75-
// https://console.developers.google.com/project
76-
services.AddOAuthAuthentication("Google-AccessToken", o =>
70+
})
71+
// You must first create an app with Google and add its ID and Secret to your user-secrets.
72+
// https://console.developers.google.com/project
73+
.AddOAuth("Google-AccessToken", o =>
7774
{
7875
o.ClientId = Configuration["google:clientid"];
7976
o.ClientSecret = Configuration["google:clientsecret"];
@@ -84,11 +81,10 @@ public void ConfigureServices(IServiceCollection services)
8481
o.Scope.Add("profile");
8582
o.Scope.Add("email");
8683
o.SaveTokens = true;
87-
});
88-
89-
// You must first create an app with Google and add its ID and Secret to your user-secrets.
90-
// https://console.developers.google.com/project
91-
services.AddGoogleAuthentication(o =>
84+
})
85+
// You must first create an app with Google and add its ID and Secret to your user-secrets.
86+
// https://console.developers.google.com/project
87+
.AddGoogle(o =>
9288
{
9389
o.ClientId = Configuration["google:clientid"];
9490
o.ClientSecret = Configuration["google:clientsecret"];
@@ -104,11 +100,10 @@ public void ConfigureServices(IServiceCollection services)
104100
};
105101
o.ClaimActions.MapJsonSubKey("urn:google:image", "image", "url");
106102
o.ClaimActions.Remove(ClaimTypes.GivenName);
107-
});
108-
109-
// You must first create an app with Twitter and add its key and Secret to your user-secrets.
110-
// https://apps.twitter.com/
111-
services.AddTwitterAuthentication(o =>
103+
})
104+
// You must first create an app with Twitter and add its key and Secret to your user-secrets.
105+
// https://apps.twitter.com/
106+
.AddTwitter(o =>
112107
{
113108
o.ConsumerKey = Configuration["twitter:consumerkey"];
114109
o.ConsumerSecret = Configuration["twitter:consumersecret"];
@@ -126,15 +121,14 @@ public void ConfigureServices(IServiceCollection services)
126121
return Task.FromResult(0);
127122
}
128123
};
129-
});
130-
131-
/* Azure AD app model v2 has restrictions that prevent the use of plain HTTP for redirect URLs.
132-
Therefore, to authenticate through microsoft accounts, tryout the sample using the following URL:
133-
https://localhost:44318/
134-
*/
135-
// You must first create an app with Microsoft Account and add its ID and Secret to your user-secrets.
136-
// https://apps.dev.microsoft.com/
137-
services.AddOAuthAuthentication("Microsoft-AccessToken", o =>
124+
})
125+
/* Azure AD app model v2 has restrictions that prevent the use of plain HTTP for redirect URLs.
126+
Therefore, to authenticate through microsoft accounts, tryout the sample using the following URL:
127+
https://localhost:44318/
128+
*/
129+
// You must first create an app with Microsoft Account and add its ID and Secret to your user-secrets.
130+
// https://apps.dev.microsoft.com/
131+
.AddOAuth("Microsoft-AccessToken", o =>
138132
{
139133
o.ClientId = Configuration["microsoftaccount:clientid"];
140134
o.ClientSecret = Configuration["microsoftaccount:clientsecret"];
@@ -143,32 +137,29 @@ public void ConfigureServices(IServiceCollection services)
143137
o.TokenEndpoint = MicrosoftAccountDefaults.TokenEndpoint;
144138
o.Scope.Add("https://graph.microsoft.com/user.read");
145139
o.SaveTokens = true;
146-
});
147-
148-
// You must first create an app with Microsoft Account and add its ID and Secret to your user-secrets.
149-
// https://azure.microsoft.com/en-us/documentation/articles/active-directory-v2-app-registration/
150-
services.AddMicrosoftAccountAuthentication(o =>
140+
})
141+
// You must first create an app with Microsoft Account and add its ID and Secret to your user-secrets.
142+
// https://azure.microsoft.com/en-us/documentation/articles/active-directory-v2-app-registration/
143+
.AddMicrosoftAccount(o =>
151144
{
152145
o.ClientId = Configuration["microsoftaccount:clientid"];
153146
o.ClientSecret = Configuration["microsoftaccount:clientsecret"];
154147
o.SaveTokens = true;
155-
});
156-
157-
// You must first create an app with GitHub and add its ID and Secret to your user-secrets.
158-
// https://github.com/settings/applications/
159-
services.AddOAuthAuthentication("GitHub-AccessToken", o =>
148+
})
149+
// You must first create an app with GitHub and add its ID and Secret to your user-secrets.
150+
// https://github.com/settings/applications/
151+
.AddOAuth("GitHub-AccessToken", o =>
160152
{
161153
o.ClientId = Configuration["github-token:clientid"];
162154
o.ClientSecret = Configuration["github-token:clientsecret"];
163155
o.CallbackPath = new PathString("/signin-github-token");
164156
o.AuthorizationEndpoint = "https://github.com/login/oauth/authorize";
165157
o.TokenEndpoint = "https://github.com/login/oauth/access_token";
166158
o.SaveTokens = true;
167-
});
168-
169-
// You must first create an app with GitHub and add its ID and Secret to your user-secrets.
170-
// https://github.com/settings/applications/
171-
services.AddOAuthAuthentication("GitHub", o =>
159+
})
160+
// You must first create an app with GitHub and add its ID and Secret to your user-secrets.
161+
// https://github.com/settings/applications/
162+
.AddOAuth("GitHub", o =>
172163
{
173164
o.ClientId = Configuration["github:clientid"];
174165
o.ClientSecret = Configuration["github:clientsecret"];

src/Microsoft.AspNetCore.Authentication.Cookies/CookieAuthenticationHandler.cs

Lines changed: 28 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,10 @@
1414

1515
namespace Microsoft.AspNetCore.Authentication.Cookies
1616
{
17-
public class CookieAuthenticationHandler : AuthenticationHandler<CookieAuthenticationOptions>
17+
public class CookieAuthenticationHandler :
18+
AuthenticationHandler<CookieAuthenticationOptions>,
19+
IAuthenticationSignInHandler,
20+
IAuthenticationSignOutHandler
1821
{
1922
private const string HeaderValueNoCache = "no-cache";
2023
private const string HeaderValueMinusOne = "-1";
@@ -104,7 +107,7 @@ private async Task<AuthenticateResult> ReadCookieTicket()
104107
var cookie = Options.CookieManager.GetRequestCookie(Context, Options.CookieName);
105108
if (string.IsNullOrEmpty(cookie))
106109
{
107-
return AuthenticateResult.None();
110+
return AuthenticateResult.NoResult();
108111
}
109112

110113
var ticket = Options.TicketDataFormat.Unprotect(cookie, GetTlsTokenBinding());
@@ -155,7 +158,7 @@ protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
155158
return result;
156159
}
157160

158-
var context = new CookieValidatePrincipalContext(Context, Scheme, result.Ticket, Options);
161+
var context = new CookieValidatePrincipalContext(Context, Scheme, Options, result.Ticket);
159162
await Events.ValidatePrincipal(context);
160163

161164
if (context.Principal == null)
@@ -244,8 +247,15 @@ protected virtual async Task FinishResponseAsync()
244247
}
245248
}
246249

247-
protected override async Task HandleSignInAsync(ClaimsPrincipal user, AuthenticationProperties properties)
250+
public async virtual Task SignInAsync(ClaimsPrincipal user, AuthenticationProperties properties)
248251
{
252+
if (user == null)
253+
{
254+
throw new ArgumentNullException(nameof(user));
255+
}
256+
257+
properties = properties ?? new AuthenticationProperties();
258+
249259
_signInCalled = true;
250260

251261
// Process the request cookie to initialize members like _sessionKey.
@@ -284,7 +294,8 @@ protected override async Task HandleSignInAsync(ClaimsPrincipal user, Authentica
284294
signInContext.CookieOptions.Expires = expiresUtc.ToUniversalTime();
285295
}
286296

287-
var ticket = new AuthenticationTicket(signInContext.Principal, signInContext.Properties, signInContext.AuthenticationScheme);
297+
var ticket = new AuthenticationTicket(signInContext.Principal, signInContext.Properties, signInContext.Scheme.Name);
298+
288299
if (Options.SessionStore != null)
289300
{
290301
if (_sessionKey != null)
@@ -310,20 +321,23 @@ protected override async Task HandleSignInAsync(ClaimsPrincipal user, Authentica
310321
var signedInContext = new CookieSignedInContext(
311322
Context,
312323
Scheme,
313-
Options,
314-
Scheme.Name,
315324
signInContext.Principal,
316-
signInContext.Properties);
325+
signInContext.Properties,
326+
Options);
317327

318328
await Events.SignedIn(signedInContext);
319329

320330
// Only redirect on the login path
321331
var shouldRedirect = Options.LoginPath.HasValue && OriginalPath == Options.LoginPath;
322332
await ApplyHeaders(shouldRedirect, signedInContext.Properties);
333+
334+
Logger.SignedIn(Scheme.Name);
323335
}
324336

325-
protected override async Task HandleSignOutAsync(AuthenticationProperties properties)
337+
public async virtual Task SignOutAsync(AuthenticationProperties properties)
326338
{
339+
properties = properties ?? new AuthenticationProperties();
340+
327341
_signOutCalled = true;
328342

329343
// Process the request cookie to initialize members like _sessionKey.
@@ -351,6 +365,8 @@ protected override async Task HandleSignOutAsync(AuthenticationProperties proper
351365
// Only redirect on the logout path
352366
var shouldRedirect = Options.LogoutPath.HasValue && OriginalPath == Options.LogoutPath;
353367
await ApplyHeaders(shouldRedirect, context.Properties);
368+
369+
Logger.SignedOut(Scheme.Name);
354370
}
355371

356372
private async Task ApplyHeaders(bool shouldRedirectToReturnUrl, AuthenticationProperties properties)
@@ -380,7 +396,7 @@ private async Task ApplyHeaders(bool shouldRedirectToReturnUrl, AuthenticationPr
380396
if (redirectUri != null)
381397
{
382398
await Events.RedirectToReturnUrl(
383-
new CookieRedirectContext(Context, Scheme, Options, redirectUri, properties));
399+
new RedirectContext<CookieAuthenticationOptions>(Context, Scheme, Options, properties, redirectUri));
384400
}
385401
}
386402
}
@@ -406,7 +422,7 @@ protected override async Task HandleForbiddenAsync(AuthenticationProperties prop
406422
returnUrl = OriginalPathBase + Request.Path + Request.QueryString;
407423
}
408424
var accessDeniedUri = Options.AccessDeniedPath + QueryString.Create(Options.ReturnUrlParameter, returnUrl);
409-
var redirectContext = new CookieRedirectContext(Context, Scheme, Options, BuildRedirectUri(accessDeniedUri), properties);
425+
var redirectContext = new RedirectContext<CookieAuthenticationOptions>(Context, Scheme, Options, properties, BuildRedirectUri(accessDeniedUri));
410426
await Events.RedirectToAccessDenied(redirectContext);
411427
}
412428

@@ -419,7 +435,7 @@ protected override async Task HandleChallengeAsync(AuthenticationProperties prop
419435
}
420436

421437
var loginUri = Options.LoginPath + QueryString.Create(Options.ReturnUrlParameter, redirectUri);
422-
var redirectContext = new CookieRedirectContext(Context, Scheme, Options, BuildRedirectUri(loginUri), properties);
438+
var redirectContext = new RedirectContext<CookieAuthenticationOptions>(Context, Scheme, Options, properties, BuildRedirectUri(loginUri));
423439
await Events.RedirectToLogin(redirectContext);
424440
}
425441

src/Microsoft.AspNetCore.Authentication.Cookies/CookieExtensions.cs

Lines changed: 19 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,16 +2,32 @@
22
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
33

44
using System;
5+
using Microsoft.AspNetCore.Authentication;
56
using Microsoft.AspNetCore.Authentication.Cookies;
6-
using Microsoft.AspNetCore.DataProtection;
7-
using Microsoft.Extensions.Options;
87
using Microsoft.Extensions.DependencyInjection.Extensions;
9-
using Microsoft.AspNetCore.Authentication;
8+
using Microsoft.Extensions.Options;
109

1110
namespace Microsoft.Extensions.DependencyInjection
1211
{
1312
public static class CookieExtensions
1413
{
14+
public static AuthenticationBuilder AddCookie(this AuthenticationBuilder builder)
15+
=> builder.AddCookie(CookieAuthenticationDefaults.AuthenticationScheme);
16+
17+
public static AuthenticationBuilder AddCookie(this AuthenticationBuilder builder, string authenticationScheme)
18+
=> builder.AddCookie(authenticationScheme, configureOptions: null);
19+
20+
public static AuthenticationBuilder AddCookie(this AuthenticationBuilder builder, Action<CookieAuthenticationOptions> configureOptions)
21+
=> builder.AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, configureOptions);
22+
23+
public static AuthenticationBuilder AddCookie(this AuthenticationBuilder builder, string authenticationScheme, Action<CookieAuthenticationOptions> configureOptions)
24+
{
25+
builder.Services.TryAddEnumerable(ServiceDescriptor.Singleton<IPostConfigureOptions<CookieAuthenticationOptions>, PostConfigureCookieAuthenticationOptions>());
26+
return builder.AddScheme<CookieAuthenticationOptions, CookieAuthenticationHandler>(authenticationScheme, configureOptions);
27+
}
28+
29+
30+
// REMOVE below once callers have been updated
1531
public static IServiceCollection AddCookieAuthentication(this IServiceCollection services) => services.AddCookieAuthentication(CookieAuthenticationDefaults.AuthenticationScheme);
1632

1733
public static IServiceCollection AddCookieAuthentication(this IServiceCollection services, string authenticationScheme) => services.AddCookieAuthentication(authenticationScheme, configureOptions: null);

src/Microsoft.AspNetCore.Authentication.Cookies/Events/BaseCookieContext.cs

Lines changed: 0 additions & 30 deletions
This file was deleted.

0 commit comments

Comments
 (0)